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 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 16
3.18k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
010040a8f7cb6a7a60b88ae80c43198fc46594d9
|
tests/test_integration.py
|
tests/test_integration.py
|
import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone_id = self.cloudflare.get_zones()[0]['id']
zone = self.cloudflare.get_zone(zone_id)
self.assertIsInstance(zone, dict)
|
import os
import types
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.iter_zones()
self.assertIsInstance(zones, types.GeneratorType)
def test_get_zone(self):
zone_id = self.cloudflare.get_zones()[0]['id']
zone = self.cloudflare.get_zone(zone_id)
self.assertIsInstance(zone, dict)
|
Test iter_zones instead of get_zones
|
Test iter_zones instead of get_zones
|
Python
|
mit
|
yola/pycloudflare,gnowxilef/pycloudflare
|
import os
+ import types
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
- zones = self.cloudflare.get_zones()
+ zones = self.cloudflare.iter_zones()
- self.assertIsInstance(zones, list)
+ self.assertIsInstance(zones, types.GeneratorType)
def test_get_zone(self):
zone_id = self.cloudflare.get_zones()[0]['id']
zone = self.cloudflare.get_zone(zone_id)
self.assertIsInstance(zone, dict)
|
Test iter_zones instead of get_zones
|
## Code Before:
import os
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.get_zones()
self.assertIsInstance(zones, list)
def test_get_zone(self):
zone_id = self.cloudflare.get_zones()[0]['id']
zone = self.cloudflare.get_zone(zone_id)
self.assertIsInstance(zone, dict)
## Instruction:
Test iter_zones instead of get_zones
## Code After:
import os
import types
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase):
def setUp(self):
configure_services('cloudflare', ['cloudflare'], conf.common)
self.cloudflare = CloudFlareService()
def test_get_all_zones(self):
zones = self.cloudflare.iter_zones()
self.assertIsInstance(zones, types.GeneratorType)
def test_get_zone(self):
zone_id = self.cloudflare.get_zones()[0]['id']
zone = self.cloudflare.get_zone(zone_id)
self.assertIsInstance(zone, dict)
|
# ... existing code ...
import os
import types
from unittest import TestCase
# ... modified code ...
def test_get_all_zones(self):
zones = self.cloudflare.iter_zones()
self.assertIsInstance(zones, types.GeneratorType)
# ... rest of the code ...
|
5ebc53fccd79e479d1a39cf02160c8eb2eab247a
|
vulk/__init__.py
|
vulk/__init__.py
|
__version__ = "0.2.0"
|
from os import path as p
__version__ = "0.2.0"
PATH_VULK = p.dirname(p.abspath(__file__))
PATH_VULK_ASSET = p.join(PATH_VULK, 'asset')
PATH_VULK_SHADER = p.join(PATH_VULK_ASSET, 'shader')
|
Add Path to Vulk package
|
Add Path to Vulk package
|
Python
|
apache-2.0
|
Echelon9/vulk,realitix/vulk,realitix/vulk,Echelon9/vulk
|
+ from os import path as p
+
__version__ = "0.2.0"
+ PATH_VULK = p.dirname(p.abspath(__file__))
+ PATH_VULK_ASSET = p.join(PATH_VULK, 'asset')
+ PATH_VULK_SHADER = p.join(PATH_VULK_ASSET, 'shader')
+
|
Add Path to Vulk package
|
## Code Before:
__version__ = "0.2.0"
## Instruction:
Add Path to Vulk package
## Code After:
from os import path as p
__version__ = "0.2.0"
PATH_VULK = p.dirname(p.abspath(__file__))
PATH_VULK_ASSET = p.join(PATH_VULK, 'asset')
PATH_VULK_SHADER = p.join(PATH_VULK_ASSET, 'shader')
|
...
from os import path as p
__version__ = "0.2.0"
PATH_VULK = p.dirname(p.abspath(__file__))
PATH_VULK_ASSET = p.join(PATH_VULK, 'asset')
PATH_VULK_SHADER = p.join(PATH_VULK_ASSET, 'shader')
...
|
5085e2f8c97ecab6617b4f7b0c8250095d47b22d
|
boardinghouse/templatetags/boardinghouse.py
|
boardinghouse/templatetags/boardinghouse.py
|
from django import template
from ..schema import is_shared_model as _is_shared_model
from ..schema import get_schema_model
Schema = get_schema_model()
register = template.Library()
@register.filter
def is_schema_aware(obj):
return obj and not _is_shared_model(obj)
@register.filter
def is_shared_model(obj):
return obj and _is_shared_model(obj)
@register.filter
def schema_name(pk):
try:
return Schema.objects.get(pk=pk).name
except Schema.DoesNotExist:
return "no schema"
|
from django import template
from ..schema import is_shared_model as _is_shared_model
from ..schema import _get_schema
register = template.Library()
@register.filter
def is_schema_aware(obj):
return obj and not _is_shared_model(obj)
@register.filter
def is_shared_model(obj):
return obj and _is_shared_model(obj)
@register.filter
def schema_name(schema):
try:
return _get_schema(schema).name
except AttributeError:
return "no schema"
|
Remove a database access from the template tag.
|
Remove a database access from the template tag.
--HG--
branch : schema-invitations
|
Python
|
bsd-3-clause
|
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
|
from django import template
from ..schema import is_shared_model as _is_shared_model
- from ..schema import get_schema_model
+ from ..schema import _get_schema
-
- Schema = get_schema_model()
register = template.Library()
@register.filter
def is_schema_aware(obj):
return obj and not _is_shared_model(obj)
@register.filter
def is_shared_model(obj):
return obj and _is_shared_model(obj)
@register.filter
- def schema_name(pk):
+ def schema_name(schema):
try:
- return Schema.objects.get(pk=pk).name
- except Schema.DoesNotExist:
+ return _get_schema(schema).name
+ except AttributeError:
return "no schema"
|
Remove a database access from the template tag.
|
## Code Before:
from django import template
from ..schema import is_shared_model as _is_shared_model
from ..schema import get_schema_model
Schema = get_schema_model()
register = template.Library()
@register.filter
def is_schema_aware(obj):
return obj and not _is_shared_model(obj)
@register.filter
def is_shared_model(obj):
return obj and _is_shared_model(obj)
@register.filter
def schema_name(pk):
try:
return Schema.objects.get(pk=pk).name
except Schema.DoesNotExist:
return "no schema"
## Instruction:
Remove a database access from the template tag.
## Code After:
from django import template
from ..schema import is_shared_model as _is_shared_model
from ..schema import _get_schema
register = template.Library()
@register.filter
def is_schema_aware(obj):
return obj and not _is_shared_model(obj)
@register.filter
def is_shared_model(obj):
return obj and _is_shared_model(obj)
@register.filter
def schema_name(schema):
try:
return _get_schema(schema).name
except AttributeError:
return "no schema"
|
...
from ..schema import is_shared_model as _is_shared_model
from ..schema import _get_schema
...
@register.filter
def schema_name(schema):
try:
return _get_schema(schema).name
except AttributeError:
return "no schema"
...
|
4abd7baafcd982993471d5c0137d4b506ea49e8b
|
src/runcommands/util/enums.py
|
src/runcommands/util/enums.py
|
import enum
import os
import subprocess
import sys
import blessings
from .misc import isatty
if isatty(sys.stdout) and os.getenv("TERM"):
Terminal = blessings.Terminal
else:
class Terminal:
def __getattr__(self, name):
return ""
TERM = Terminal()
class Color(enum.Enum):
none = ""
reset = TERM.normal
black = TERM.black
red = TERM.red
green = TERM.green
yellow = TERM.yellow
blue = TERM.blue
magenta = TERM.magenta
cyan = TERM.cyan
white = TERM.white
def __str__(self):
return self.value
class StreamOptions(enum.Enum):
"""Choices for stream handling."""
capture = "capture"
hide = "hide"
none = "none"
@property
def option(self):
return {
"capture": subprocess.PIPE,
"hide": subprocess.DEVNULL,
"none": None,
}[self.value]
|
import enum
import os
import subprocess
import sys
import blessings
from .misc import isatty
if isatty(sys.stdout) and os.getenv("TERM"):
Terminal = blessings.Terminal
else:
# XXX: Mock terminal that returns "" for all attributes
class TerminalValue:
registry = {}
@classmethod
def get(cls, name):
if name not in cls.registry:
cls.registry[name] = cls(name)
return cls.registry[name]
def __init__(self, name):
self.name = name
def __repr__(self):
return f"{self.__class__.__name__}({self.name})"
def __str__(self):
return ""
class Terminal:
def __getattr__(self, name):
return TerminalValue.get(name)
TERM = Terminal()
class Color(enum.Enum):
none = ""
reset = TERM.normal
black = TERM.black
red = TERM.red
green = TERM.green
yellow = TERM.yellow
blue = TERM.blue
magenta = TERM.magenta
cyan = TERM.cyan
white = TERM.white
def __str__(self):
return str(self.value)
class StreamOptions(enum.Enum):
"""Choices for stream handling."""
capture = "capture"
hide = "hide"
none = "none"
@property
def option(self):
return {
"capture": subprocess.PIPE,
"hide": subprocess.DEVNULL,
"none": None,
}[self.value]
|
Fix Color enum setup when TERM isn't set
|
Fix Color enum setup when TERM isn't set
The previous version of this didn't work right because all the values
were the same empty string.
This works around that by creating distinct values that evaluate to "".
Amends 94b55ead63523f7f5677989f1a4999994b205cdf
|
Python
|
mit
|
wylee/runcommands,wylee/runcommands
|
import enum
import os
import subprocess
import sys
import blessings
from .misc import isatty
if isatty(sys.stdout) and os.getenv("TERM"):
Terminal = blessings.Terminal
else:
+ # XXX: Mock terminal that returns "" for all attributes
+ class TerminalValue:
+ registry = {}
+
+ @classmethod
+ def get(cls, name):
+ if name not in cls.registry:
+ cls.registry[name] = cls(name)
+ return cls.registry[name]
+
+ def __init__(self, name):
+ self.name = name
+
+ def __repr__(self):
+ return f"{self.__class__.__name__}({self.name})"
+
+ def __str__(self):
+ return ""
class Terminal:
def __getattr__(self, name):
- return ""
+ return TerminalValue.get(name)
TERM = Terminal()
class Color(enum.Enum):
none = ""
reset = TERM.normal
black = TERM.black
red = TERM.red
green = TERM.green
yellow = TERM.yellow
blue = TERM.blue
magenta = TERM.magenta
cyan = TERM.cyan
white = TERM.white
def __str__(self):
- return self.value
+ return str(self.value)
class StreamOptions(enum.Enum):
"""Choices for stream handling."""
capture = "capture"
hide = "hide"
none = "none"
@property
def option(self):
return {
"capture": subprocess.PIPE,
"hide": subprocess.DEVNULL,
"none": None,
}[self.value]
|
Fix Color enum setup when TERM isn't set
|
## Code Before:
import enum
import os
import subprocess
import sys
import blessings
from .misc import isatty
if isatty(sys.stdout) and os.getenv("TERM"):
Terminal = blessings.Terminal
else:
class Terminal:
def __getattr__(self, name):
return ""
TERM = Terminal()
class Color(enum.Enum):
none = ""
reset = TERM.normal
black = TERM.black
red = TERM.red
green = TERM.green
yellow = TERM.yellow
blue = TERM.blue
magenta = TERM.magenta
cyan = TERM.cyan
white = TERM.white
def __str__(self):
return self.value
class StreamOptions(enum.Enum):
"""Choices for stream handling."""
capture = "capture"
hide = "hide"
none = "none"
@property
def option(self):
return {
"capture": subprocess.PIPE,
"hide": subprocess.DEVNULL,
"none": None,
}[self.value]
## Instruction:
Fix Color enum setup when TERM isn't set
## Code After:
import enum
import os
import subprocess
import sys
import blessings
from .misc import isatty
if isatty(sys.stdout) and os.getenv("TERM"):
Terminal = blessings.Terminal
else:
# XXX: Mock terminal that returns "" for all attributes
class TerminalValue:
registry = {}
@classmethod
def get(cls, name):
if name not in cls.registry:
cls.registry[name] = cls(name)
return cls.registry[name]
def __init__(self, name):
self.name = name
def __repr__(self):
return f"{self.__class__.__name__}({self.name})"
def __str__(self):
return ""
class Terminal:
def __getattr__(self, name):
return TerminalValue.get(name)
TERM = Terminal()
class Color(enum.Enum):
none = ""
reset = TERM.normal
black = TERM.black
red = TERM.red
green = TERM.green
yellow = TERM.yellow
blue = TERM.blue
magenta = TERM.magenta
cyan = TERM.cyan
white = TERM.white
def __str__(self):
return str(self.value)
class StreamOptions(enum.Enum):
"""Choices for stream handling."""
capture = "capture"
hide = "hide"
none = "none"
@property
def option(self):
return {
"capture": subprocess.PIPE,
"hide": subprocess.DEVNULL,
"none": None,
}[self.value]
|
# ... existing code ...
else:
# XXX: Mock terminal that returns "" for all attributes
class TerminalValue:
registry = {}
@classmethod
def get(cls, name):
if name not in cls.registry:
cls.registry[name] = cls(name)
return cls.registry[name]
def __init__(self, name):
self.name = name
def __repr__(self):
return f"{self.__class__.__name__}({self.name})"
def __str__(self):
return ""
# ... modified code ...
def __getattr__(self, name):
return TerminalValue.get(name)
...
def __str__(self):
return str(self.value)
# ... rest of the code ...
|
deb5a6c45d6f52daef7ca5752f574d7c14abbc47
|
admin/base/urls.py
|
admin/base/urls.py
|
from django.conf.urls import include, url
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(
base_pattern,
include([
url(r'^$', views.home, name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^spam/', include('admin.spam.urls', namespace='spam')),
url(r'^account/', include('admin.common_auth.urls', namespace='auth')),
url(r'^password/', include('password_reset.urls')),
url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')),
url(r'^users/', include('admin.users.urls', namespace='users')),
url(r'^meetings/', include('admin.meetings.urls',
namespace='meetings')),
url(r'^project/', include('admin.pre_reg.urls', namespace='pre_reg')),
url(r'^metrics/', include('admin.metrics.urls',
namespace='metrics')),
url(r'^desk/', include('admin.desk.urls',
namespace='desk')),
]),
),
]
admin.site.site_header = 'OSF-Admin administration'
|
from django.conf.urls import include, url
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(
base_pattern,
include([
url(r'^$', views.home, name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^spam/', include('admin.spam.urls', namespace='spam')),
url(r'^account/', include('admin.common_auth.urls', namespace='auth')),
url(r'^password/', include('password_reset.urls')),
url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')),
url(r'^preprints/', include('admin.preprints.urls', namespace='preprints')),
url(r'^users/', include('admin.users.urls', namespace='users')),
url(r'^meetings/', include('admin.meetings.urls',
namespace='meetings')),
url(r'^project/', include('admin.pre_reg.urls', namespace='pre_reg')),
url(r'^metrics/', include('admin.metrics.urls',
namespace='metrics')),
url(r'^desk/', include('admin.desk.urls',
namespace='desk')),
]),
),
]
admin.site.site_header = 'OSF-Admin administration'
|
Add preprints to the sidebar
|
Add preprints to the sidebar
[#OSF-7198]
|
Python
|
apache-2.0
|
mattclark/osf.io,caseyrollins/osf.io,aaxelb/osf.io,icereval/osf.io,felliott/osf.io,cwisecarver/osf.io,adlius/osf.io,crcresearch/osf.io,caneruguz/osf.io,cslzchen/osf.io,pattisdr/osf.io,leb2dg/osf.io,mattclark/osf.io,mfraezz/osf.io,caseyrollins/osf.io,baylee-d/osf.io,chrisseto/osf.io,saradbowman/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,Nesiehr/osf.io,aaxelb/osf.io,cslzchen/osf.io,adlius/osf.io,laurenrevere/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,felliott/osf.io,mfraezz/osf.io,saradbowman/osf.io,hmoco/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,binoculars/osf.io,felliott/osf.io,chennan47/osf.io,TomBaxter/osf.io,hmoco/osf.io,leb2dg/osf.io,felliott/osf.io,baylee-d/osf.io,hmoco/osf.io,cslzchen/osf.io,cslzchen/osf.io,erinspace/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,erinspace/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,caneruguz/osf.io,caneruguz/osf.io,leb2dg/osf.io,erinspace/osf.io,crcresearch/osf.io,Johnetordoff/osf.io,icereval/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,crcresearch/osf.io,sloria/osf.io,icereval/osf.io,Nesiehr/osf.io,sloria/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,TomBaxter/osf.io,binoculars/osf.io,binoculars/osf.io,baylee-d/osf.io,adlius/osf.io,laurenrevere/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,pattisdr/osf.io,chrisseto/osf.io,Nesiehr/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,chennan47/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,cwisecarver/osf.io,hmoco/osf.io,mfraezz/osf.io,pattisdr/osf.io,sloria/osf.io,Nesiehr/osf.io,mfraezz/osf.io,brianjgeiger/osf.io
|
from django.conf.urls import include, url
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(
base_pattern,
include([
url(r'^$', views.home, name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^spam/', include('admin.spam.urls', namespace='spam')),
url(r'^account/', include('admin.common_auth.urls', namespace='auth')),
url(r'^password/', include('password_reset.urls')),
url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')),
+ url(r'^preprints/', include('admin.preprints.urls', namespace='preprints')),
url(r'^users/', include('admin.users.urls', namespace='users')),
url(r'^meetings/', include('admin.meetings.urls',
namespace='meetings')),
url(r'^project/', include('admin.pre_reg.urls', namespace='pre_reg')),
url(r'^metrics/', include('admin.metrics.urls',
namespace='metrics')),
url(r'^desk/', include('admin.desk.urls',
namespace='desk')),
]),
),
]
admin.site.site_header = 'OSF-Admin administration'
|
Add preprints to the sidebar
|
## Code Before:
from django.conf.urls import include, url
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(
base_pattern,
include([
url(r'^$', views.home, name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^spam/', include('admin.spam.urls', namespace='spam')),
url(r'^account/', include('admin.common_auth.urls', namespace='auth')),
url(r'^password/', include('password_reset.urls')),
url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')),
url(r'^users/', include('admin.users.urls', namespace='users')),
url(r'^meetings/', include('admin.meetings.urls',
namespace='meetings')),
url(r'^project/', include('admin.pre_reg.urls', namespace='pre_reg')),
url(r'^metrics/', include('admin.metrics.urls',
namespace='metrics')),
url(r'^desk/', include('admin.desk.urls',
namespace='desk')),
]),
),
]
admin.site.site_header = 'OSF-Admin administration'
## Instruction:
Add preprints to the sidebar
## Code After:
from django.conf.urls import include, url
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(
base_pattern,
include([
url(r'^$', views.home, name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^spam/', include('admin.spam.urls', namespace='spam')),
url(r'^account/', include('admin.common_auth.urls', namespace='auth')),
url(r'^password/', include('password_reset.urls')),
url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')),
url(r'^preprints/', include('admin.preprints.urls', namespace='preprints')),
url(r'^users/', include('admin.users.urls', namespace='users')),
url(r'^meetings/', include('admin.meetings.urls',
namespace='meetings')),
url(r'^project/', include('admin.pre_reg.urls', namespace='pre_reg')),
url(r'^metrics/', include('admin.metrics.urls',
namespace='metrics')),
url(r'^desk/', include('admin.desk.urls',
namespace='desk')),
]),
),
]
admin.site.site_header = 'OSF-Admin administration'
|
# ... existing code ...
url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')),
url(r'^preprints/', include('admin.preprints.urls', namespace='preprints')),
url(r'^users/', include('admin.users.urls', namespace='users')),
# ... rest of the code ...
|
ee425b43502054895986c447e4cdae2c7e6c9278
|
Lib/fontTools/misc/timeTools.py
|
Lib/fontTools/misc/timeTools.py
|
"""fontTools.misc.timeTools.py -- miscellaneous routines."""
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
import time
import calendar
# OpenType timestamp handling
epoch_diff = calendar.timegm((1904, 1, 1, 0, 0, 0, 0, 0, 0))
def timestampToString(value):
try:
value = time.asctime(time.gmtime(max(0, value + epoch_diff)))
except ValueError:
value = time.asctime(time.gmtime(0))
def timestampFromString(value):
return calendar.timegm(time.strptime(value)) - epoch_diff
def timestampNow():
return int(time.time() - epoch_diff)
|
"""fontTools.misc.timeTools.py -- miscellaneous routines."""
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
import time
import calendar
# OpenType timestamp handling
epoch_diff = calendar.timegm((1904, 1, 1, 0, 0, 0, 0, 0, 0))
def timestampToString(value):
# https://github.com/behdad/fonttools/issues/99#issuecomment-66776810
try:
value = time.asctime(time.gmtime(max(0, value + epoch_diff)))
except (OverflowError, ValueError):
value = time.asctime(time.gmtime(0))
def timestampFromString(value):
return calendar.timegm(time.strptime(value)) - epoch_diff
def timestampNow():
return int(time.time() - epoch_diff)
|
Adjust for Python 3.3 change in gmtime() exception type
|
Adjust for Python 3.3 change in gmtime() exception type
https://github.com/behdad/fonttools/issues/99#issuecomment-66776810
Fixes https://github.com/behdad/fonttools/issues/99
|
Python
|
mit
|
googlefonts/fonttools,fonttools/fonttools
|
"""fontTools.misc.timeTools.py -- miscellaneous routines."""
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
import time
import calendar
# OpenType timestamp handling
epoch_diff = calendar.timegm((1904, 1, 1, 0, 0, 0, 0, 0, 0))
def timestampToString(value):
+ # https://github.com/behdad/fonttools/issues/99#issuecomment-66776810
try:
value = time.asctime(time.gmtime(max(0, value + epoch_diff)))
- except ValueError:
+ except (OverflowError, ValueError):
value = time.asctime(time.gmtime(0))
def timestampFromString(value):
return calendar.timegm(time.strptime(value)) - epoch_diff
def timestampNow():
return int(time.time() - epoch_diff)
|
Adjust for Python 3.3 change in gmtime() exception type
|
## Code Before:
"""fontTools.misc.timeTools.py -- miscellaneous routines."""
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
import time
import calendar
# OpenType timestamp handling
epoch_diff = calendar.timegm((1904, 1, 1, 0, 0, 0, 0, 0, 0))
def timestampToString(value):
try:
value = time.asctime(time.gmtime(max(0, value + epoch_diff)))
except ValueError:
value = time.asctime(time.gmtime(0))
def timestampFromString(value):
return calendar.timegm(time.strptime(value)) - epoch_diff
def timestampNow():
return int(time.time() - epoch_diff)
## Instruction:
Adjust for Python 3.3 change in gmtime() exception type
## Code After:
"""fontTools.misc.timeTools.py -- miscellaneous routines."""
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
import time
import calendar
# OpenType timestamp handling
epoch_diff = calendar.timegm((1904, 1, 1, 0, 0, 0, 0, 0, 0))
def timestampToString(value):
# https://github.com/behdad/fonttools/issues/99#issuecomment-66776810
try:
value = time.asctime(time.gmtime(max(0, value + epoch_diff)))
except (OverflowError, ValueError):
value = time.asctime(time.gmtime(0))
def timestampFromString(value):
return calendar.timegm(time.strptime(value)) - epoch_diff
def timestampNow():
return int(time.time() - epoch_diff)
|
...
def timestampToString(value):
# https://github.com/behdad/fonttools/issues/99#issuecomment-66776810
try:
...
value = time.asctime(time.gmtime(max(0, value + epoch_diff)))
except (OverflowError, ValueError):
value = time.asctime(time.gmtime(0))
...
|
47bf5160010d0975297d39b200492270a5279e81
|
common/lib/xmodule/xmodule/discussion_module.py
|
common/lib/xmodule/xmodule/discussion_module.py
|
from lxml import etree
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
import comment_client
import json
class DiscussionModule(XModule):
def get_html(self):
context = {
'discussion_id': self.discussion_id,
}
return self.system.render_template('discussion/_discussion_module.html', context)
def __init__(self, system, location, definition, descriptor, instance_state=None, shared_state=None, **kwargs):
XModule.__init__(self, system, location, definition, descriptor, instance_state, shared_state, **kwargs)
if isinstance(instance_state, str):
instance_state = json.loads(instance_state)
xml_data = etree.fromstring(definition['data'])
self.discussion_id = xml_data.attrib['id']
self.title = xml_data.attrib['for']
self.discussion_category = xml_data.attrib['discussion_category']
class DiscussionDescriptor(RawDescriptor):
module_class = DiscussionModule
|
from lxml import etree
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
import json
class DiscussionModule(XModule):
def get_html(self):
context = {
'discussion_id': self.discussion_id,
}
return self.system.render_template('discussion/_discussion_module.html', context)
def __init__(self, system, location, definition, descriptor, instance_state=None, shared_state=None, **kwargs):
XModule.__init__(self, system, location, definition, descriptor, instance_state, shared_state, **kwargs)
if isinstance(instance_state, str):
instance_state = json.loads(instance_state)
xml_data = etree.fromstring(definition['data'])
self.discussion_id = xml_data.attrib['id']
self.title = xml_data.attrib['for']
self.discussion_category = xml_data.attrib['discussion_category']
class DiscussionDescriptor(RawDescriptor):
module_class = DiscussionModule
|
Remove unnecessary import that was failing a test
|
Remove unnecessary import that was failing a test
|
Python
|
agpl-3.0
|
franosincic/edx-platform,shabab12/edx-platform,motion2015/edx-platform,rue89-tech/edx-platform,nanolearning/edx-platform,J861449197/edx-platform,mcgachey/edx-platform,halvertoluke/edx-platform,cyanna/edx-platform,jruiperezv/ANALYSE,jbassen/edx-platform,abdoosh00/edraak,LearnEra/LearnEraPlaftform,doganov/edx-platform,alexthered/kienhoc-platform,teltek/edx-platform,motion2015/a3,Lektorium-LLC/edx-platform,iivic/BoiseStateX,peterm-itr/edx-platform,martynovp/edx-platform,MSOpenTech/edx-platform,auferack08/edx-platform,mjirayu/sit_academy,EduPepperPDTesting/pepper2013-testing,bitifirefly/edx-platform,pepeportela/edx-platform,philanthropy-u/edx-platform,hkawasaki/kawasaki-aio8-0,adoosii/edx-platform,tiagochiavericosta/edx-platform,LearnEra/LearnEraPlaftform,TsinghuaX/edx-platform,chrisndodge/edx-platform,pepeportela/edx-platform,kursitet/edx-platform,halvertoluke/edx-platform,shashank971/edx-platform,dcosentino/edx-platform,DefyVentures/edx-platform,dkarakats/edx-platform,kmoocdev2/edx-platform,inares/edx-platform,jswope00/GAI,nanolearning/edx-platform,jolyonb/edx-platform,mcgachey/edx-platform,shubhdev/openedx,ubc/edx-platform,4eek/edx-platform,sameetb-cuelogic/edx-platform-test,RPI-OPENEDX/edx-platform,Unow/edx-platform,appliedx/edx-platform,cecep-edu/edx-platform,edx/edx-platform,openfun/edx-platform,ESOedX/edx-platform,ferabra/edx-platform,jjmiranda/edx-platform,CourseTalk/edx-platform,itsjeyd/edx-platform,y12uc231/edx-platform,JioEducation/edx-platform,EduPepperPD/pepper2013,chrisndodge/edx-platform,ampax/edx-platform,motion2015/a3,alexthered/kienhoc-platform,motion2015/edx-platform,jazztpt/edx-platform,Unow/edx-platform,beacloudgenius/edx-platform,EduPepperPD/pepper2013,stvstnfrd/edx-platform,edx-solutions/edx-platform,10clouds/edx-platform,rue89-tech/edx-platform,dsajkl/reqiop,vismartltd/edx-platform,openfun/edx-platform,beni55/edx-platform,playm2mboy/edx-platform,abdoosh00/edx-rtl-final,cognitiveclass/edx-platform,utecuy/edx-platform,mtlchun/edx,pelikanchik/edx-platform,nagyistoce/edx-platform,philanthropy-u/edx-platform,a-parhom/edx-platform,kalebhartje/schoolboost,praveen-pal/edx-platform,PepperPD/edx-pepper-platform,polimediaupv/edx-platform,jolyonb/edx-platform,mcgachey/edx-platform,miptliot/edx-platform,kamalx/edx-platform,motion2015/edx-platform,teltek/edx-platform,dcosentino/edx-platform,shubhdev/edx-platform,etzhou/edx-platform,Edraak/edx-platform,BehavioralInsightsTeam/edx-platform,raccoongang/edx-platform,pomegranited/edx-platform,jamiefolsom/edx-platform,shubhdev/edx-platform,Semi-global/edx-platform,praveen-pal/edx-platform,AkA84/edx-platform,eestay/edx-platform,utecuy/edx-platform,nikolas/edx-platform,ak2703/edx-platform,waheedahmed/edx-platform,shubhdev/openedx,wwj718/ANALYSE,LICEF/edx-platform,jswope00/griffinx,analyseuc3m/ANALYSE-v1,PepperPD/edx-pepper-platform,ak2703/edx-platform,angelapper/edx-platform,alexthered/kienhoc-platform,yokose-ks/edx-platform,chauhanhardik/populo_2,B-MOOC/edx-platform,gymnasium/edx-platform,hkawasaki/kawasaki-aio8-1,gsehub/edx-platform,SravanthiSinha/edx-platform,antoviaque/edx-platform,morenopc/edx-platform,Edraak/edraak-platform,rismalrv/edx-platform,inares/edx-platform,dsajkl/123,Unow/edx-platform,chand3040/cloud_that,chauhanhardik/populo,pdehaye/theming-edx-platform,jonathan-beard/edx-platform,gymnasium/edx-platform,playm2mboy/edx-platform,jelugbo/tundex,nanolearningllc/edx-platform-cypress-2,procangroup/edx-platform,motion2015/edx-platform,carsongee/edx-platform,arifsetiawan/edx-platform,appliedx/edx-platform,morenopc/edx-platform,bitifirefly/edx-platform,halvertoluke/edx-platform,deepsrijit1105/edx-platform,vikas1885/test1,waheedahmed/edx-platform,zerobatu/edx-platform,vismartltd/edx-platform,vasyarv/edx-platform,fintech-circle/edx-platform,EDUlib/edx-platform,wwj718/edx-platform,kalebhartje/schoolboost,PepperPD/edx-pepper-platform,shurihell/testasia,inares/edx-platform,devs1991/test_edx_docmode,jbassen/edx-platform,SivilTaram/edx-platform,deepsrijit1105/edx-platform,leansoft/edx-platform,LICEF/edx-platform,gsehub/edx-platform,dsajkl/123,cyanna/edx-platform,carsongee/edx-platform,lduarte1991/edx-platform,solashirai/edx-platform,amir-qayyum-khan/edx-platform,TsinghuaX/edx-platform,jbzdak/edx-platform,mahendra-r/edx-platform,pomegranited/edx-platform,hamzehd/edx-platform,motion2015/edx-platform,synergeticsedx/deployment-wipro,UOMx/edx-platform,shubhdev/edxOnBaadal,EduPepperPDTesting/pepper2013-testing,EduPepperPDTesting/pepper2013-testing,rue89-tech/edx-platform,DefyVentures/edx-platform,CourseTalk/edx-platform,DNFcode/edx-platform,procangroup/edx-platform,romain-li/edx-platform,dsajkl/123,eduNEXT/edx-platform,bdero/edx-platform,doganov/edx-platform,cognitiveclass/edx-platform,jazkarta/edx-platform-for-isc,romain-li/edx-platform,sameetb-cuelogic/edx-platform-test,eemirtekin/edx-platform,playm2mboy/edx-platform,morenopc/edx-platform,ampax/edx-platform-backup,zhenzhai/edx-platform,cyanna/edx-platform,ferabra/edx-platform,shubhdev/edxOnBaadal,openfun/edx-platform,dsajkl/reqiop,leansoft/edx-platform,cselis86/edx-platform,iivic/BoiseStateX,antonve/s4-project-mooc,Edraak/edx-platform,BehavioralInsightsTeam/edx-platform,rismalrv/edx-platform,mitocw/edx-platform,zerobatu/edx-platform,kalebhartje/schoolboost,kursitet/edx-platform,edx-solutions/edx-platform,hamzehd/edx-platform,morenopc/edx-platform,chand3040/cloud_that,Shrhawk/edx-platform,Lektorium-LLC/edx-platform,prarthitm/edxplatform,Shrhawk/edx-platform,bigdatauniversity/edx-platform,angelapper/edx-platform,JioEducation/edx-platform,gymnasium/edx-platform,Stanford-Online/edx-platform,ZLLab-Mooc/edx-platform,caesar2164/edx-platform,rationalAgent/edx-platform-custom,fly19890211/edx-platform,MSOpenTech/edx-platform,rue89-tech/edx-platform,SravanthiSinha/edx-platform,dkarakats/edx-platform,ampax/edx-platform,edry/edx-platform,shabab12/edx-platform,abdoosh00/edx-rtl-final,ahmadio/edx-platform,zadgroup/edx-platform,marcore/edx-platform,DNFcode/edx-platform,sudheerchintala/LearnEraPlatForm,pomegranited/edx-platform,mcgachey/edx-platform,sameetb-cuelogic/edx-platform-test,zofuthan/edx-platform,arifsetiawan/edx-platform,simbs/edx-platform,franosincic/edx-platform,Edraak/edx-platform,cselis86/edx-platform,B-MOOC/edx-platform,zubair-arbi/edx-platform,alu042/edx-platform,Edraak/circleci-edx-platform,pepeportela/edx-platform,kxliugang/edx-platform,peterm-itr/edx-platform,itsjeyd/edx-platform,solashirai/edx-platform,chauhanhardik/populo,kxliugang/edx-platform,torchingloom/edx-platform,jamiefolsom/edx-platform,chand3040/cloud_that,Livit/Livit.Learn.EdX,pku9104038/edx-platform,vikas1885/test1,doganov/edx-platform,andyzsf/edx,Softmotions/edx-platform,jelugbo/tundex,eduNEXT/edx-platform,TeachAtTUM/edx-platform,Livit/Livit.Learn.EdX,simbs/edx-platform,jruiperezv/ANALYSE,fintech-circle/edx-platform,chrisndodge/edx-platform,doismellburning/edx-platform,zofuthan/edx-platform,pabloborrego93/edx-platform,yokose-ks/edx-platform,olexiim/edx-platform,Ayub-Khan/edx-platform,sameetb-cuelogic/edx-platform-test,knehez/edx-platform,eemirtekin/edx-platform,Semi-global/edx-platform,franosincic/edx-platform,arbrandes/edx-platform,doismellburning/edx-platform,shashank971/edx-platform,shubhdev/edxOnBaadal,jonathan-beard/edx-platform,SravanthiSinha/edx-platform,IONISx/edx-platform,jelugbo/tundex,rismalrv/edx-platform,mbareta/edx-platform-ft,msegado/edx-platform,chauhanhardik/populo_2,chudaol/edx-platform,TeachAtTUM/edx-platform,mbareta/edx-platform-ft,SivilTaram/edx-platform,Shrhawk/edx-platform,dkarakats/edx-platform,eduNEXT/edunext-platform,wwj718/edx-platform,chudaol/edx-platform,Semi-global/edx-platform,zhenzhai/edx-platform,zhenzhai/edx-platform,carsongee/edx-platform,benpatterson/edx-platform,cognitiveclass/edx-platform,ahmadio/edx-platform,edry/edx-platform,valtech-mooc/edx-platform,nagyistoce/edx-platform,nttks/jenkins-test,EduPepperPDTesting/pepper2013-testing,synergeticsedx/deployment-wipro,cpennington/edx-platform,leansoft/edx-platform,kmoocdev2/edx-platform,ampax/edx-platform-backup,ampax/edx-platform,ampax/edx-platform-backup,atsolakid/edx-platform,sudheerchintala/LearnEraPlatForm,PepperPD/edx-pepper-platform,Edraak/edraak-platform,SivilTaram/edx-platform,shubhdev/edx-platform,dsajkl/reqiop,TeachAtTUM/edx-platform,tiagochiavericosta/edx-platform,xingyepei/edx-platform,jazztpt/edx-platform,simbs/edx-platform,xuxiao19910803/edx,jzoldak/edx-platform,cognitiveclass/edx-platform,peterm-itr/edx-platform,CourseTalk/edx-platform,louyihua/edx-platform,ahmadiga/min_edx,a-parhom/edx-platform,WatanabeYasumasa/edx-platform,hastexo/edx-platform,pabloborrego93/edx-platform,tiagochiavericosta/edx-platform,naresh21/synergetics-edx-platform,nanolearningllc/edx-platform-cypress,mushtaqak/edx-platform,rhndg/openedx,hkawasaki/kawasaki-aio8-0,hkawasaki/kawasaki-aio8-2,IONISx/edx-platform,appsembler/edx-platform,devs1991/test_edx_docmode,nttks/jenkins-test,UOMx/edx-platform,WatanabeYasumasa/edx-platform,leansoft/edx-platform,naresh21/synergetics-edx-platform,proversity-org/edx-platform,marcore/edx-platform,IITBinterns13/edx-platform-dev,Semi-global/edx-platform,eestay/edx-platform,Shrhawk/edx-platform,jjmiranda/edx-platform,polimediaupv/edx-platform,valtech-mooc/edx-platform,edry/edx-platform,nanolearningllc/edx-platform-cypress,4eek/edx-platform,alexthered/kienhoc-platform,eestay/edx-platform,don-github/edx-platform,shubhdev/openedx,nikolas/edx-platform,TsinghuaX/edx-platform,appliedx/edx-platform,pabloborrego93/edx-platform,Lektorium-LLC/edx-platform,dsajkl/123,shubhdev/edxOnBaadal,openfun/edx-platform,vikas1885/test1,xinjiguaike/edx-platform,Ayub-Khan/edx-platform,sudheerchintala/LearnEraPlatForm,zerobatu/edx-platform,UOMx/edx-platform,zubair-arbi/edx-platform,jamesblunt/edx-platform,Unow/edx-platform,ahmadiga/min_edx,jswope00/GAI,chauhanhardik/populo_2,pepeportela/edx-platform,atsolakid/edx-platform,andyzsf/edx,mitocw/edx-platform,jzoldak/edx-platform,eduNEXT/edx-platform,abdoosh00/edx-rtl-final,ak2703/edx-platform,10clouds/edx-platform,atsolakid/edx-platform,nanolearning/edx-platform,shabab12/edx-platform,angelapper/edx-platform,mjirayu/sit_academy,jazkarta/edx-platform,fly19890211/edx-platform,ampax/edx-platform-backup,cecep-edu/edx-platform,playm2mboy/edx-platform,jazkarta/edx-platform,chauhanhardik/populo,don-github/edx-platform,devs1991/test_edx_docmode,atsolakid/edx-platform,polimediaupv/edx-platform,don-github/edx-platform,syjeon/new_edx,jelugbo/tundex,chauhanhardik/populo_2,MSOpenTech/edx-platform,cselis86/edx-platform,utecuy/edx-platform,mitocw/edx-platform,naresh21/synergetics-edx-platform,vasyarv/edx-platform,ubc/edx-platform,marcore/edx-platform,jazztpt/edx-platform,shurihell/testasia,unicri/edx-platform,devs1991/test_edx_docmode,Softmotions/edx-platform,franosincic/edx-platform,xuxiao19910803/edx-platform,iivic/BoiseStateX,y12uc231/edx-platform,abdoosh00/edx-rtl-final,don-github/edx-platform,ubc/edx-platform,nanolearningllc/edx-platform-cypress-2,stvstnfrd/edx-platform,bdero/edx-platform,LearnEra/LearnEraPlaftform,IndonesiaX/edx-platform,sameetb-cuelogic/edx-platform-test,Livit/Livit.Learn.EdX,wwj718/edx-platform,arifsetiawan/edx-platform,ahmadiga/min_edx,arifsetiawan/edx-platform,J861449197/edx-platform,antoviaque/edx-platform,jswope00/griffinx,apigee/edx-platform,chrisndodge/edx-platform,UXE/local-edx,procangroup/edx-platform,arbrandes/edx-platform,vasyarv/edx-platform,polimediaupv/edx-platform,Edraak/edraak-platform,halvertoluke/edx-platform,jbzdak/edx-platform,rationalAgent/edx-platform-custom,shubhdev/edx-platform,cselis86/edx-platform,xingyepei/edx-platform,DNFcode/edx-platform,appliedx/edx-platform,chauhanhardik/populo,antonve/s4-project-mooc,IndonesiaX/edx-platform,kmoocdev/edx-platform,ferabra/edx-platform,wwj718/ANALYSE,adoosii/edx-platform,tiagochiavericosta/edx-platform,J861449197/edx-platform,hkawasaki/kawasaki-aio8-2,appsembler/edx-platform,Shrhawk/edx-platform,pelikanchik/edx-platform,longmen21/edx-platform,bigdatauniversity/edx-platform,nttks/edx-platform,louyihua/edx-platform,ESOedX/edx-platform,morpheby/levelup-by,EduPepperPD/pepper2013,ferabra/edx-platform,IITBinterns13/edx-platform-dev,amir-qayyum-khan/edx-platform,xuxiao19910803/edx,raccoongang/edx-platform,xingyepei/edx-platform,AkA84/edx-platform,DefyVentures/edx-platform,motion2015/a3,halvertoluke/edx-platform,kxliugang/edx-platform,stvstnfrd/edx-platform,ahmadiga/min_edx,ESOedX/edx-platform,adoosii/edx-platform,lduarte1991/edx-platform,Edraak/circleci-edx-platform,xuxiao19910803/edx-platform,mjirayu/sit_academy,deepsrijit1105/edx-platform,Kalyzee/edx-platform,auferack08/edx-platform,polimediaupv/edx-platform,nttks/jenkins-test,xuxiao19910803/edx-platform,eduNEXT/edunext-platform,UOMx/edx-platform,msegado/edx-platform,zerobatu/edx-platform,benpatterson/edx-platform,xinjiguaike/edx-platform,bigdatauniversity/edx-platform,IONISx/edx-platform,zerobatu/edx-platform,SivilTaram/edx-platform,nikolas/edx-platform,Stanford-Online/edx-platform,4eek/edx-platform,rationalAgent/edx-platform-custom,etzhou/edx-platform,devs1991/test_edx_docmode,DNFcode/edx-platform,rationalAgent/edx-platform-custom,xuxiao19910803/edx,Kalyzee/edx-platform,RPI-OPENEDX/edx-platform,hastexo/edx-platform,miptliot/edx-platform,Livit/Livit.Learn.EdX,4eek/edx-platform,hamzehd/edx-platform,B-MOOC/edx-platform,CourseTalk/edx-platform,shubhdev/openedx,WatanabeYasumasa/edx-platform,OmarIthawi/edx-platform,jamesblunt/edx-platform,yokose-ks/edx-platform,zadgroup/edx-platform,beacloudgenius/edx-platform,DefyVentures/edx-platform,JCBarahona/edX,JCBarahona/edX,dkarakats/edx-platform,Edraak/circleci-edx-platform,alexthered/kienhoc-platform,mahendra-r/edx-platform,ovnicraft/edx-platform,kamalx/edx-platform,unicri/edx-platform,UXE/local-edx,waheedahmed/edx-platform,nttks/edx-platform,jonathan-beard/edx-platform,cselis86/edx-platform,abdoosh00/edraak,jbzdak/edx-platform,analyseuc3m/ANALYSE-v1,ahmedaljazzar/edx-platform,pelikanchik/edx-platform,ovnicraft/edx-platform,proversity-org/edx-platform,ampax/edx-platform,MakeHer/edx-platform,yokose-ks/edx-platform,bitifirefly/edx-platform,kmoocdev/edx-platform,Endika/edx-platform,RPI-OPENEDX/edx-platform,y12uc231/edx-platform,xinjiguaike/edx-platform,cecep-edu/edx-platform,philanthropy-u/edx-platform,pdehaye/theming-edx-platform,olexiim/edx-platform,longmen21/edx-platform,etzhou/edx-platform,nagyistoce/edx-platform,Edraak/edx-platform,analyseuc3m/ANALYSE-v1,defance/edx-platform,MakeHer/edx-platform,Ayub-Khan/edx-platform,ovnicraft/edx-platform,hmcmooc/muddx-platform,jamesblunt/edx-platform,bdero/edx-platform,OmarIthawi/edx-platform,torchingloom/edx-platform,Endika/edx-platform,syjeon/new_edx,olexiim/edx-platform,nttks/edx-platform,defance/edx-platform,etzhou/edx-platform,cpennington/edx-platform,kmoocdev/edx-platform,TeachAtTUM/edx-platform,J861449197/edx-platform,syjeon/new_edx,defance/edx-platform,kursitet/edx-platform,nanolearningllc/edx-platform-cypress,kamalx/edx-platform,knehez/edx-platform,utecuy/edx-platform,jelugbo/tundex,eemirtekin/edx-platform,jswope00/GAI,OmarIthawi/edx-platform,longmen21/edx-platform,beni55/edx-platform,solashirai/edx-platform,UXE/local-edx,marcore/edx-platform,vismartltd/edx-platform,praveen-pal/edx-platform,atsolakid/edx-platform,AkA84/edx-platform,pabloborrego93/edx-platform,fintech-circle/edx-platform,eemirtekin/edx-platform,y12uc231/edx-platform,hkawasaki/kawasaki-aio8-2,mtlchun/edx,zubair-arbi/edx-platform,zhenzhai/edx-platform,UXE/local-edx,msegado/edx-platform,MakeHer/edx-platform,xinjiguaike/edx-platform,edx/edx-platform,raccoongang/edx-platform,unicri/edx-platform,gymnasium/edx-platform,don-github/edx-platform,tiagochiavericosta/edx-platform,shashank971/edx-platform,proversity-org/edx-platform,valtech-mooc/edx-platform,hastexo/edx-platform,Softmotions/edx-platform,Softmotions/edx-platform,kalebhartje/schoolboost,Ayub-Khan/edx-platform,rhndg/openedx,IITBinterns13/edx-platform-dev,dsajkl/123,RPI-OPENEDX/edx-platform,jazkarta/edx-platform-for-isc,shashank971/edx-platform,caesar2164/edx-platform,martynovp/edx-platform,cpennington/edx-platform,pdehaye/theming-edx-platform,nanolearningllc/edx-platform-cypress,jazkarta/edx-platform-for-isc,ubc/edx-platform,shabab12/edx-platform,tanmaykm/edx-platform,EduPepperPDTesting/pepper2013-testing,chand3040/cloud_that,benpatterson/edx-platform,SravanthiSinha/edx-platform,caesar2164/edx-platform,romain-li/edx-platform,WatanabeYasumasa/edx-platform,dcosentino/edx-platform,vasyarv/edx-platform,prarthitm/edxplatform,alu042/edx-platform,teltek/edx-platform,kxliugang/edx-platform,kalebhartje/schoolboost,cyanna/edx-platform,nanolearningllc/edx-platform-cypress-2,waheedahmed/edx-platform,nanolearning/edx-platform,auferack08/edx-platform,EduPepperPD/pepper2013,mahendra-r/edx-platform,benpatterson/edx-platform,iivic/BoiseStateX,unicri/edx-platform,amir-qayyum-khan/edx-platform,miptliot/edx-platform,itsjeyd/edx-platform,mahendra-r/edx-platform,mbareta/edx-platform-ft,eduNEXT/edunext-platform,synergeticsedx/deployment-wipro,eduNEXT/edx-platform,ubc/edx-platform,jamiefolsom/edx-platform,longmen21/edx-platform,jamiefolsom/edx-platform,cognitiveclass/edx-platform,msegado/edx-platform,Kalyzee/edx-platform,defance/edx-platform,shashank971/edx-platform,OmarIthawi/edx-platform,openfun/edx-platform,zofuthan/edx-platform,zubair-arbi/edx-platform,hkawasaki/kawasaki-aio8-0,nanolearningllc/edx-platform-cypress,mjg2203/edx-platform-seas,ahmadio/edx-platform,chudaol/edx-platform,antoviaque/edx-platform,playm2mboy/edx-platform,jonathan-beard/edx-platform,stvstnfrd/edx-platform,hmcmooc/muddx-platform,abdoosh00/edraak,Lektorium-LLC/edx-platform,EDUlib/edx-platform,MakeHer/edx-platform,lduarte1991/edx-platform,morenopc/edx-platform,devs1991/test_edx_docmode,hkawasaki/kawasaki-aio8-1,ZLLab-Mooc/edx-platform,jswope00/griffinx,hkawasaki/kawasaki-aio8-2,xingyepei/edx-platform,simbs/edx-platform,10clouds/edx-platform,doganov/edx-platform,nikolas/edx-platform,Kalyzee/edx-platform,msegado/edx-platform,xuxiao19910803/edx,jazztpt/edx-platform,hkawasaki/kawasaki-aio8-0,romain-li/edx-platform,beacloudgenius/edx-platform,dcosentino/edx-platform,wwj718/edx-platform,edx/edx-platform,BehavioralInsightsTeam/edx-platform,tanmaykm/edx-platform,chauhanhardik/populo,naresh21/synergetics-edx-platform,beni55/edx-platform,martynovp/edx-platform,itsjeyd/edx-platform,nagyistoce/edx-platform,utecuy/edx-platform,simbs/edx-platform,pku9104038/edx-platform,amir-qayyum-khan/edx-platform,vismartltd/edx-platform,EduPepperPD/pepper2013,valtech-mooc/edx-platform,Semi-global/edx-platform,jolyonb/edx-platform,fly19890211/edx-platform,nttks/edx-platform,louyihua/edx-platform,ak2703/edx-platform,syjeon/new_edx,devs1991/test_edx_docmode,cecep-edu/edx-platform,hkawasaki/kawasaki-aio8-1,ferabra/edx-platform,ahmedaljazzar/edx-platform,IndonesiaX/edx-platform,IndonesiaX/edx-platform,bdero/edx-platform,proversity-org/edx-platform,mbareta/edx-platform-ft,IndonesiaX/edx-platform,IITBinterns13/edx-platform-dev,romain-li/edx-platform,jolyonb/edx-platform,abdoosh00/edraak,pelikanchik/edx-platform,chudaol/edx-platform,arifsetiawan/edx-platform,jruiperezv/ANALYSE,carsongee/edx-platform,jbassen/edx-platform,kursitet/edx-platform,ovnicraft/edx-platform,shurihell/testasia,bigdatauniversity/edx-platform,etzhou/edx-platform,JCBarahona/edX,adoosii/edx-platform,synergeticsedx/deployment-wipro,beacloudgenius/edx-platform,xuxiao19910803/edx-platform,jzoldak/edx-platform,ahmedaljazzar/edx-platform,wwj718/ANALYSE,louyihua/edx-platform,kmoocdev2/edx-platform,mushtaqak/edx-platform,eduNEXT/edunext-platform,jbzdak/edx-platform,mushtaqak/edx-platform,adoosii/edx-platform,SravanthiSinha/edx-platform,prarthitm/edxplatform,ZLLab-Mooc/edx-platform,caesar2164/edx-platform,jamesblunt/edx-platform,Endika/edx-platform,leansoft/edx-platform,BehavioralInsightsTeam/edx-platform,cyanna/edx-platform,dkarakats/edx-platform,ahmadio/edx-platform,B-MOOC/edx-platform,jazkarta/edx-platform-for-isc,MSOpenTech/edx-platform,gsehub/edx-platform,pdehaye/theming-edx-platform,alu042/edx-platform,y12uc231/edx-platform,olexiim/edx-platform,rismalrv/edx-platform,pomegranited/edx-platform,miptliot/edx-platform,eestay/edx-platform,shubhdev/edx-platform,IONISx/edx-platform,LICEF/edx-platform,edx-solutions/edx-platform,yokose-ks/edx-platform,beni55/edx-platform,mjirayu/sit_academy,ZLLab-Mooc/edx-platform,ESOedX/edx-platform,chand3040/cloud_that,mtlchun/edx,edx-solutions/edx-platform,torchingloom/edx-platform,jjmiranda/edx-platform,MSOpenTech/edx-platform,zofuthan/edx-platform,JCBarahona/edX,jazkarta/edx-platform,CredoReference/edx-platform,antonve/s4-project-mooc,edry/edx-platform,doismellburning/edx-platform,Stanford-Online/edx-platform,gsehub/edx-platform,CredoReference/edx-platform,mtlchun/edx,motion2015/a3,MakeHer/edx-platform,fly19890211/edx-platform,LICEF/edx-platform,zadgroup/edx-platform,chauhanhardik/populo_2,jbassen/edx-platform,hmcmooc/muddx-platform,LearnEra/LearnEraPlaftform,hmcmooc/muddx-platform,analyseuc3m/ANALYSE-v1,jazkarta/edx-platform,zubair-arbi/edx-platform,tanmaykm/edx-platform,Edraak/edx-platform,ak2703/edx-platform,mjirayu/sit_academy,JCBarahona/edX,lduarte1991/edx-platform,10clouds/edx-platform,waheedahmed/edx-platform,apigee/edx-platform,DefyVentures/edx-platform,Softmotions/edx-platform,a-parhom/edx-platform,teltek/edx-platform,J861449197/edx-platform,fintech-circle/edx-platform,EduPepperPDTesting/pepper2013-testing,prarthitm/edxplatform,mushtaqak/edx-platform,jswope00/GAI,edx/edx-platform,xinjiguaike/edx-platform,motion2015/a3,iivic/BoiseStateX,procangroup/edx-platform,solashirai/edx-platform,pku9104038/edx-platform,jazztpt/edx-platform,appsembler/edx-platform,hastexo/edx-platform,RPI-OPENEDX/edx-platform,olexiim/edx-platform,angelapper/edx-platform,apigee/edx-platform,vikas1885/test1,EDUlib/edx-platform,nanolearningllc/edx-platform-cypress-2,zadgroup/edx-platform,Edraak/circleci-edx-platform,mjg2203/edx-platform-seas,arbrandes/edx-platform,LICEF/edx-platform,nttks/edx-platform,morpheby/levelup-by,raccoongang/edx-platform,DNFcode/edx-platform,xuxiao19910803/edx,torchingloom/edx-platform,philanthropy-u/edx-platform,hamzehd/edx-platform,arbrandes/edx-platform,hamzehd/edx-platform,zofuthan/edx-platform,mjg2203/edx-platform-seas,peterm-itr/edx-platform,jswope00/griffinx,xingyepei/edx-platform,rismalrv/edx-platform,rue89-tech/edx-platform,shubhdev/edxOnBaadal,doismellburning/edx-platform,JioEducation/edx-platform,mcgachey/edx-platform,bitifirefly/edx-platform,doganov/edx-platform,bitifirefly/edx-platform,ZLLab-Mooc/edx-platform,morpheby/levelup-by,vismartltd/edx-platform,ahmadio/edx-platform,Kalyzee/edx-platform,PepperPD/edx-pepper-platform,inares/edx-platform,fly19890211/edx-platform,andyzsf/edx,deepsrijit1105/edx-platform,martynovp/edx-platform,mitocw/edx-platform,edry/edx-platform,mahendra-r/edx-platform,inares/edx-platform,nikolas/edx-platform,shurihell/testasia,shurihell/testasia,hkawasaki/kawasaki-aio8-1,rhndg/openedx,bigdatauniversity/edx-platform,benpatterson/edx-platform,kxliugang/edx-platform,knehez/edx-platform,jswope00/griffinx,4eek/edx-platform,Stanford-Online/edx-platform,vikas1885/test1,B-MOOC/edx-platform,ahmadiga/min_edx,torchingloom/edx-platform,nttks/jenkins-test,a-parhom/edx-platform,jzoldak/edx-platform,shubhdev/openedx,sudheerchintala/LearnEraPlatForm,morpheby/levelup-by,appliedx/edx-platform,jamiefolsom/edx-platform,tanmaykm/edx-platform,devs1991/test_edx_docmode,franosincic/edx-platform,IONISx/edx-platform,wwj718/edx-platform,nagyistoce/edx-platform,dcosentino/edx-platform,longmen21/edx-platform,valtech-mooc/edx-platform,Ayub-Khan/edx-platform,SivilTaram/edx-platform,xuxiao19910803/edx-platform,apigee/edx-platform,solashirai/edx-platform,Endika/edx-platform,kmoocdev/edx-platform,appsembler/edx-platform,jonathan-beard/edx-platform,wwj718/ANALYSE,jruiperezv/ANALYSE,pomegranited/edx-platform,unicri/edx-platform,Edraak/circleci-edx-platform,kamalx/edx-platform,ampax/edx-platform-backup,rhndg/openedx,chudaol/edx-platform,pku9104038/edx-platform,TsinghuaX/edx-platform,kmoocdev/edx-platform,mushtaqak/edx-platform,kmoocdev2/edx-platform,auferack08/edx-platform,eemirtekin/edx-platform,beni55/edx-platform,andyzsf/edx,CredoReference/edx-platform,nttks/jenkins-test,alu042/edx-platform,nanolearningllc/edx-platform-cypress-2,rationalAgent/edx-platform-custom,jazkarta/edx-platform,jbassen/edx-platform,zhenzhai/edx-platform,cpennington/edx-platform,jjmiranda/edx-platform,ahmedaljazzar/edx-platform,vasyarv/edx-platform,zadgroup/edx-platform,antonve/s4-project-mooc,mjg2203/edx-platform-seas,Edraak/edraak-platform,martynovp/edx-platform,rhndg/openedx,doismellburning/edx-platform,mtlchun/edx,JioEducation/edx-platform,beacloudgenius/edx-platform,nanolearning/edx-platform,kursitet/edx-platform,EDUlib/edx-platform,kamalx/edx-platform,jruiperezv/ANALYSE,eestay/edx-platform,jamesblunt/edx-platform,cecep-edu/edx-platform,knehez/edx-platform,CredoReference/edx-platform,AkA84/edx-platform,antonve/s4-project-mooc,AkA84/edx-platform,jazkarta/edx-platform-for-isc,jbzdak/edx-platform,ovnicraft/edx-platform,knehez/edx-platform,kmoocdev2/edx-platform,antoviaque/edx-platform,praveen-pal/edx-platform,dsajkl/reqiop,wwj718/ANALYSE
|
from lxml import etree
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
-
- import comment_client
import json
class DiscussionModule(XModule):
def get_html(self):
context = {
'discussion_id': self.discussion_id,
}
return self.system.render_template('discussion/_discussion_module.html', context)
def __init__(self, system, location, definition, descriptor, instance_state=None, shared_state=None, **kwargs):
XModule.__init__(self, system, location, definition, descriptor, instance_state, shared_state, **kwargs)
if isinstance(instance_state, str):
instance_state = json.loads(instance_state)
xml_data = etree.fromstring(definition['data'])
self.discussion_id = xml_data.attrib['id']
self.title = xml_data.attrib['for']
self.discussion_category = xml_data.attrib['discussion_category']
class DiscussionDescriptor(RawDescriptor):
module_class = DiscussionModule
|
Remove unnecessary import that was failing a test
|
## Code Before:
from lxml import etree
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
import comment_client
import json
class DiscussionModule(XModule):
def get_html(self):
context = {
'discussion_id': self.discussion_id,
}
return self.system.render_template('discussion/_discussion_module.html', context)
def __init__(self, system, location, definition, descriptor, instance_state=None, shared_state=None, **kwargs):
XModule.__init__(self, system, location, definition, descriptor, instance_state, shared_state, **kwargs)
if isinstance(instance_state, str):
instance_state = json.loads(instance_state)
xml_data = etree.fromstring(definition['data'])
self.discussion_id = xml_data.attrib['id']
self.title = xml_data.attrib['for']
self.discussion_category = xml_data.attrib['discussion_category']
class DiscussionDescriptor(RawDescriptor):
module_class = DiscussionModule
## Instruction:
Remove unnecessary import that was failing a test
## Code After:
from lxml import etree
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
import json
class DiscussionModule(XModule):
def get_html(self):
context = {
'discussion_id': self.discussion_id,
}
return self.system.render_template('discussion/_discussion_module.html', context)
def __init__(self, system, location, definition, descriptor, instance_state=None, shared_state=None, **kwargs):
XModule.__init__(self, system, location, definition, descriptor, instance_state, shared_state, **kwargs)
if isinstance(instance_state, str):
instance_state = json.loads(instance_state)
xml_data = etree.fromstring(definition['data'])
self.discussion_id = xml_data.attrib['id']
self.title = xml_data.attrib['for']
self.discussion_category = xml_data.attrib['discussion_category']
class DiscussionDescriptor(RawDescriptor):
module_class = DiscussionModule
|
...
from xmodule.raw_module import RawDescriptor
...
|
68bc2d2b50e754d50f1a2f85fa7dbde0ca8a6a12
|
qual/tests/test_iso.py
|
qual/tests/test_iso.py
|
import unittest
from hypothesis import given
from hypothesis.strategies import integers
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date, MINYEAR, MAXYEAR
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d.isocalendar()), d)
@given(integers(MINYEAR, MAXYEAR), integers(1, 52), integers(1, 7))
def test_round_trip_iso_date(self, year, week, day):
y, w, d = qual.iso_to_gregorian(year, week, day).isocalendar()
self.assertEqual(year, y)
self.assertEqual(week, w)
self.assertEqual(day, d)
@given(integers(MINYEAR, MAXYEAR), integers(54), integers(1, 7))
def test_weeks_greater_than_53_fail(self, year, week, day):
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
|
import unittest
from hypothesis import given
from hypothesis.strategies import integers
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date, MINYEAR, MAXYEAR
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d.isocalendar()), d)
@given(integers(MINYEAR, MAXYEAR), integers(1, 52), integers(1, 7))
def test_round_trip_iso_date(self, year, week, day):
y, w, d = qual.iso_to_gregorian(year, week, day).isocalendar()
self.assertEqual(year, y)
self.assertEqual(week, w)
self.assertEqual(day, d)
@given(integers(MINYEAR, MAXYEAR), integers(54), integers(1, 7))
def test_weeks_greater_than_53_fail(self, year, week, day):
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
@given(integers(MINYEAR, MAXYEAR), integers(None, 0), integers(1, 7))
def test_weeks_smaller_than_1_fail(self, year, week, day):
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
|
Add a new passing test for invalid week numbers.
|
Add a new passing test for invalid week numbers.
|
Python
|
apache-2.0
|
jwg4/calexicon,jwg4/qual
|
import unittest
from hypothesis import given
from hypothesis.strategies import integers
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date, MINYEAR, MAXYEAR
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d.isocalendar()), d)
@given(integers(MINYEAR, MAXYEAR), integers(1, 52), integers(1, 7))
def test_round_trip_iso_date(self, year, week, day):
y, w, d = qual.iso_to_gregorian(year, week, day).isocalendar()
self.assertEqual(year, y)
self.assertEqual(week, w)
self.assertEqual(day, d)
@given(integers(MINYEAR, MAXYEAR), integers(54), integers(1, 7))
def test_weeks_greater_than_53_fail(self, year, week, day):
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
+ @given(integers(MINYEAR, MAXYEAR), integers(None, 0), integers(1, 7))
+ def test_weeks_smaller_than_1_fail(self, year, week, day):
+ self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
+
+
|
Add a new passing test for invalid week numbers.
|
## Code Before:
import unittest
from hypothesis import given
from hypothesis.strategies import integers
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date, MINYEAR, MAXYEAR
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d.isocalendar()), d)
@given(integers(MINYEAR, MAXYEAR), integers(1, 52), integers(1, 7))
def test_round_trip_iso_date(self, year, week, day):
y, w, d = qual.iso_to_gregorian(year, week, day).isocalendar()
self.assertEqual(year, y)
self.assertEqual(week, w)
self.assertEqual(day, d)
@given(integers(MINYEAR, MAXYEAR), integers(54), integers(1, 7))
def test_weeks_greater_than_53_fail(self, year, week, day):
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
## Instruction:
Add a new passing test for invalid week numbers.
## Code After:
import unittest
from hypothesis import given
from hypothesis.strategies import integers
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date, MINYEAR, MAXYEAR
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d.isocalendar()), d)
@given(integers(MINYEAR, MAXYEAR), integers(1, 52), integers(1, 7))
def test_round_trip_iso_date(self, year, week, day):
y, w, d = qual.iso_to_gregorian(year, week, day).isocalendar()
self.assertEqual(year, y)
self.assertEqual(week, w)
self.assertEqual(day, d)
@given(integers(MINYEAR, MAXYEAR), integers(54), integers(1, 7))
def test_weeks_greater_than_53_fail(self, year, week, day):
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
@given(integers(MINYEAR, MAXYEAR), integers(None, 0), integers(1, 7))
def test_weeks_smaller_than_1_fail(self, year, week, day):
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
|
// ... existing code ...
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
@given(integers(MINYEAR, MAXYEAR), integers(None, 0), integers(1, 7))
def test_weeks_smaller_than_1_fail(self, year, week, day):
self.assertRaises(ValueError, lambda : qual.iso_to_gregorian(year, week, day))
// ... rest of the code ...
|
d97dd4a8f4c0581ce33ed5838dcc0329745041bf
|
pirate_add_shift_recurrence.py
|
pirate_add_shift_recurrence.py
|
import sys
import os
from tasklib.task import TaskWarrior
time_attributes = ('wait', 'scheduled')
def is_new_local_recurrence_child_task(task):
# Do not affect tasks not spun by recurrence
if not task['parent']:
return False
# Newly created recurrence tasks actually have
# modified field copied from the parent, thus
# older than entry field (until their ID is generated)
if (task['modified'] - task['entry']).total_seconds() < 0:
return True
tw = TaskWarrior(data_location=os.path.dirname(os.path.dirname(sys.argv[0])))
tw.config.update(dict(recurrence="no"))
def hook_shift_recurrence(task):
if is_new_local_recurrence_child_task(task):
parent = tw.tasks.get(uuid=task['parent'])
parent_due_shift = task['due'] - parent['due']
for attr in time_attributes:
if parent[attr]:
task[attr] = parent[attr] + parent_due_shift
|
import sys
import os
from tasklib import TaskWarrior
time_attributes = ('wait', 'scheduled')
def is_new_local_recurrence_child_task(task):
# Do not affect tasks not spun by recurrence
if not task['parent']:
return False
# Newly created recurrence tasks actually have
# modified field copied from the parent, thus
# older than entry field (until their ID is generated)
if (task['modified'] - task['entry']).total_seconds() < 0:
return True
tw = TaskWarrior(data_location=os.path.dirname(os.path.dirname(sys.argv[0])))
tw.overrides.update(dict(recurrence="no", hooks="no"))
def hook_shift_recurrence(task):
if is_new_local_recurrence_child_task(task):
parent = tw.tasks.get(uuid=task['parent'])
parent_due_shift = task['due'] - parent['due']
for attr in time_attributes:
if parent[attr]:
task[attr] = parent[attr] + parent_due_shift
|
Fix old style import and config overrides
|
Fix old style import and config overrides
|
Python
|
mit
|
tbabej/task.shift-recurrence
|
import sys
import os
- from tasklib.task import TaskWarrior
+ from tasklib import TaskWarrior
time_attributes = ('wait', 'scheduled')
def is_new_local_recurrence_child_task(task):
# Do not affect tasks not spun by recurrence
if not task['parent']:
return False
# Newly created recurrence tasks actually have
# modified field copied from the parent, thus
# older than entry field (until their ID is generated)
if (task['modified'] - task['entry']).total_seconds() < 0:
return True
tw = TaskWarrior(data_location=os.path.dirname(os.path.dirname(sys.argv[0])))
- tw.config.update(dict(recurrence="no"))
+ tw.overrides.update(dict(recurrence="no", hooks="no"))
def hook_shift_recurrence(task):
if is_new_local_recurrence_child_task(task):
parent = tw.tasks.get(uuid=task['parent'])
parent_due_shift = task['due'] - parent['due']
for attr in time_attributes:
if parent[attr]:
task[attr] = parent[attr] + parent_due_shift
|
Fix old style import and config overrides
|
## Code Before:
import sys
import os
from tasklib.task import TaskWarrior
time_attributes = ('wait', 'scheduled')
def is_new_local_recurrence_child_task(task):
# Do not affect tasks not spun by recurrence
if not task['parent']:
return False
# Newly created recurrence tasks actually have
# modified field copied from the parent, thus
# older than entry field (until their ID is generated)
if (task['modified'] - task['entry']).total_seconds() < 0:
return True
tw = TaskWarrior(data_location=os.path.dirname(os.path.dirname(sys.argv[0])))
tw.config.update(dict(recurrence="no"))
def hook_shift_recurrence(task):
if is_new_local_recurrence_child_task(task):
parent = tw.tasks.get(uuid=task['parent'])
parent_due_shift = task['due'] - parent['due']
for attr in time_attributes:
if parent[attr]:
task[attr] = parent[attr] + parent_due_shift
## Instruction:
Fix old style import and config overrides
## Code After:
import sys
import os
from tasklib import TaskWarrior
time_attributes = ('wait', 'scheduled')
def is_new_local_recurrence_child_task(task):
# Do not affect tasks not spun by recurrence
if not task['parent']:
return False
# Newly created recurrence tasks actually have
# modified field copied from the parent, thus
# older than entry field (until their ID is generated)
if (task['modified'] - task['entry']).total_seconds() < 0:
return True
tw = TaskWarrior(data_location=os.path.dirname(os.path.dirname(sys.argv[0])))
tw.overrides.update(dict(recurrence="no", hooks="no"))
def hook_shift_recurrence(task):
if is_new_local_recurrence_child_task(task):
parent = tw.tasks.get(uuid=task['parent'])
parent_due_shift = task['due'] - parent['due']
for attr in time_attributes:
if parent[attr]:
task[attr] = parent[attr] + parent_due_shift
|
// ... existing code ...
import os
from tasklib import TaskWarrior
// ... modified code ...
tw = TaskWarrior(data_location=os.path.dirname(os.path.dirname(sys.argv[0])))
tw.overrides.update(dict(recurrence="no", hooks="no"))
// ... rest of the code ...
|
5459dfc62e3a0d5b36b6d9405232382c1f8b663a
|
__init__.py
|
__init__.py
|
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from . import multiscanner, storage
common = multiscanner.common
multiscan = multiscanner.multiscan
parse_reports = multiscanner.parse_reports
config_init = multiscanner.config_init
|
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from . import multiscanner
common = multiscanner.common
multiscan = multiscanner.multiscan
parse_reports = multiscanner.parse_reports
config_init = multiscanner.config_init
|
Remove unused imports and sort
|
Remove unused imports and sort
|
Python
|
mpl-2.0
|
jmlong1027/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,MITRECND/multiscanner,mitre/multiscanner,MITRECND/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner
|
+ import os
import sys
- import os
+
sys.path.insert(0, os.path.dirname(__file__))
+
- from . import multiscanner, storage
+ from . import multiscanner
+
common = multiscanner.common
multiscan = multiscanner.multiscan
parse_reports = multiscanner.parse_reports
config_init = multiscanner.config_init
|
Remove unused imports and sort
|
## Code Before:
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from . import multiscanner, storage
common = multiscanner.common
multiscan = multiscanner.multiscan
parse_reports = multiscanner.parse_reports
config_init = multiscanner.config_init
## Instruction:
Remove unused imports and sort
## Code After:
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from . import multiscanner
common = multiscanner.common
multiscan = multiscanner.multiscan
parse_reports = multiscanner.parse_reports
config_init = multiscanner.config_init
|
...
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from . import multiscanner
common = multiscanner.common
...
|
1318d0bc658d23d22452b27004c5d670f4c80d17
|
spacy/tests/conftest.py
|
spacy/tests/conftest.py
|
import pytest
import os
import spacy
@pytest.fixture(scope="session")
def EN():
return spacy.load("en")
@pytest.fixture(scope="session")
def DE():
return spacy.load("de")
def pytest_addoption(parser):
parser.addoption("--models", action="store_true",
help="include tests that require full models")
parser.addoption("--vectors", action="store_true",
help="include word vectors tests")
parser.addoption("--slow", action="store_true",
help="include slow tests")
def pytest_runtest_setup(item):
for opt in ['models', 'vectors', 'slow']:
if opt in item.keywords and not item.config.getoption("--%s" % opt):
pytest.skip("need --%s option to run" % opt)
|
import pytest
import os
from ..en import English
from ..de import German
@pytest.fixture(scope="session")
def EN():
return English(path=None)
@pytest.fixture(scope="session")
def DE():
return German(path=None)
def pytest_addoption(parser):
parser.addoption("--models", action="store_true",
help="include tests that require full models")
parser.addoption("--vectors", action="store_true",
help="include word vectors tests")
parser.addoption("--slow", action="store_true",
help="include slow tests")
def pytest_runtest_setup(item):
for opt in ['models', 'vectors', 'slow']:
if opt in item.keywords and not item.config.getoption("--%s" % opt):
pytest.skip("need --%s option to run" % opt)
|
Test with the non-loaded versions of the English and German pipelines.
|
Test with the non-loaded versions of the English and German pipelines.
|
Python
|
mit
|
raphael0202/spaCy,honnibal/spaCy,banglakit/spaCy,aikramer2/spaCy,recognai/spaCy,raphael0202/spaCy,recognai/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,recognai/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,banglakit/spaCy,Gregory-Howard/spaCy,recognai/spaCy,explosion/spaCy,honnibal/spaCy,recognai/spaCy,recognai/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,banglakit/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,spacy-io/spaCy,banglakit/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,raphael0202/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,explosion/spaCy,aikramer2/spaCy,spacy-io/spaCy,banglakit/spaCy,banglakit/spaCy,honnibal/spaCy
|
import pytest
import os
- import spacy
+ from ..en import English
+ from ..de import German
@pytest.fixture(scope="session")
def EN():
- return spacy.load("en")
+ return English(path=None)
@pytest.fixture(scope="session")
def DE():
- return spacy.load("de")
+ return German(path=None)
def pytest_addoption(parser):
parser.addoption("--models", action="store_true",
help="include tests that require full models")
parser.addoption("--vectors", action="store_true",
help="include word vectors tests")
parser.addoption("--slow", action="store_true",
help="include slow tests")
def pytest_runtest_setup(item):
for opt in ['models', 'vectors', 'slow']:
if opt in item.keywords and not item.config.getoption("--%s" % opt):
pytest.skip("need --%s option to run" % opt)
|
Test with the non-loaded versions of the English and German pipelines.
|
## Code Before:
import pytest
import os
import spacy
@pytest.fixture(scope="session")
def EN():
return spacy.load("en")
@pytest.fixture(scope="session")
def DE():
return spacy.load("de")
def pytest_addoption(parser):
parser.addoption("--models", action="store_true",
help="include tests that require full models")
parser.addoption("--vectors", action="store_true",
help="include word vectors tests")
parser.addoption("--slow", action="store_true",
help="include slow tests")
def pytest_runtest_setup(item):
for opt in ['models', 'vectors', 'slow']:
if opt in item.keywords and not item.config.getoption("--%s" % opt):
pytest.skip("need --%s option to run" % opt)
## Instruction:
Test with the non-loaded versions of the English and German pipelines.
## Code After:
import pytest
import os
from ..en import English
from ..de import German
@pytest.fixture(scope="session")
def EN():
return English(path=None)
@pytest.fixture(scope="session")
def DE():
return German(path=None)
def pytest_addoption(parser):
parser.addoption("--models", action="store_true",
help="include tests that require full models")
parser.addoption("--vectors", action="store_true",
help="include word vectors tests")
parser.addoption("--slow", action="store_true",
help="include slow tests")
def pytest_runtest_setup(item):
for opt in ['models', 'vectors', 'slow']:
if opt in item.keywords and not item.config.getoption("--%s" % opt):
pytest.skip("need --%s option to run" % opt)
|
...
from ..en import English
from ..de import German
...
def EN():
return English(path=None)
...
def DE():
return German(path=None)
...
|
f0270de636bb84e89cbbb54896c6ed5037a48323
|
spiralgalaxygame/precondition.py
|
spiralgalaxygame/precondition.py
|
class PreconditionError (TypeError):
def __init__(self, callee, *args):
TypeError.__init__(self, '{0.__name__}{1!r}'.format(callee, args))
|
from types import FunctionType, MethodType
class PreconditionError (TypeError):
def __init__(self, callee, *args):
if isinstance(callee, MethodType):
name = '{0.im_class.__name__}.{0.im_func.__name__}'.format(callee)
elif isinstance(callee, type) or isinstance(callee, FunctionType):
name = callee.__name__
TypeError.__init__(self, '{}{!r}'.format(name, args))
|
Implement prettier method names in PreconditionErrors as per spec; not yet full branch coverage.
|
Implement prettier method names in PreconditionErrors as per spec; not yet full branch coverage.
|
Python
|
agpl-3.0
|
nejucomo/sgg,nejucomo/sgg,nejucomo/sgg
|
+ from types import FunctionType, MethodType
+
+
class PreconditionError (TypeError):
def __init__(self, callee, *args):
- TypeError.__init__(self, '{0.__name__}{1!r}'.format(callee, args))
+ if isinstance(callee, MethodType):
+ name = '{0.im_class.__name__}.{0.im_func.__name__}'.format(callee)
+ elif isinstance(callee, type) or isinstance(callee, FunctionType):
+ name = callee.__name__
+ TypeError.__init__(self, '{}{!r}'.format(name, args))
+
|
Implement prettier method names in PreconditionErrors as per spec; not yet full branch coverage.
|
## Code Before:
class PreconditionError (TypeError):
def __init__(self, callee, *args):
TypeError.__init__(self, '{0.__name__}{1!r}'.format(callee, args))
## Instruction:
Implement prettier method names in PreconditionErrors as per spec; not yet full branch coverage.
## Code After:
from types import FunctionType, MethodType
class PreconditionError (TypeError):
def __init__(self, callee, *args):
if isinstance(callee, MethodType):
name = '{0.im_class.__name__}.{0.im_func.__name__}'.format(callee)
elif isinstance(callee, type) or isinstance(callee, FunctionType):
name = callee.__name__
TypeError.__init__(self, '{}{!r}'.format(name, args))
|
...
from types import FunctionType, MethodType
class PreconditionError (TypeError):
...
def __init__(self, callee, *args):
if isinstance(callee, MethodType):
name = '{0.im_class.__name__}.{0.im_func.__name__}'.format(callee)
elif isinstance(callee, type) or isinstance(callee, FunctionType):
name = callee.__name__
TypeError.__init__(self, '{}{!r}'.format(name, args))
...
|
4aeb85126cf5f75d89cc466c3f7fea2f53702a13
|
bluebottle/votes/serializers.py
|
bluebottle/votes/serializers.py
|
from bluebottle.votes.models import Vote
from bluebottle.bb_accounts.serializers import UserPreviewSerializer
from rest_framework import serializers
class VoteSerializer(serializers.ModelSerializer):
voter = UserPreviewSerializer(read_only=True)
project = serializers.SlugRelatedField(source='project', slug_field='slug')
class Meta:
model = Vote
fields = ('id', 'voter', 'project')
|
from bluebottle.votes.models import Vote
from bluebottle.bb_accounts.serializers import UserPreviewSerializer
from rest_framework import serializers
class VoteSerializer(serializers.ModelSerializer):
voter = UserPreviewSerializer(read_only=True)
project = serializers.SlugRelatedField(source='project', slug_field='slug')
class Meta:
model = Vote
fields = ('id', 'voter', 'project', 'created')
|
Add created to votes api serializer
|
Add created to votes api serializer
|
Python
|
bsd-3-clause
|
onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle
|
from bluebottle.votes.models import Vote
from bluebottle.bb_accounts.serializers import UserPreviewSerializer
from rest_framework import serializers
class VoteSerializer(serializers.ModelSerializer):
voter = UserPreviewSerializer(read_only=True)
project = serializers.SlugRelatedField(source='project', slug_field='slug')
class Meta:
model = Vote
- fields = ('id', 'voter', 'project')
+ fields = ('id', 'voter', 'project', 'created')
|
Add created to votes api serializer
|
## Code Before:
from bluebottle.votes.models import Vote
from bluebottle.bb_accounts.serializers import UserPreviewSerializer
from rest_framework import serializers
class VoteSerializer(serializers.ModelSerializer):
voter = UserPreviewSerializer(read_only=True)
project = serializers.SlugRelatedField(source='project', slug_field='slug')
class Meta:
model = Vote
fields = ('id', 'voter', 'project')
## Instruction:
Add created to votes api serializer
## Code After:
from bluebottle.votes.models import Vote
from bluebottle.bb_accounts.serializers import UserPreviewSerializer
from rest_framework import serializers
class VoteSerializer(serializers.ModelSerializer):
voter = UserPreviewSerializer(read_only=True)
project = serializers.SlugRelatedField(source='project', slug_field='slug')
class Meta:
model = Vote
fields = ('id', 'voter', 'project', 'created')
|
# ... existing code ...
model = Vote
fields = ('id', 'voter', 'project', 'created')
# ... rest of the code ...
|
6d32f609379febe2fdad690adc75a90e26b8d416
|
backend/backend/serializers.py
|
backend/backend/serializers.py
|
from rest_framework import serializers
from .models import Animal
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = ('id', 'name', 'dob', 'gender', 'active', 'own', 'father', 'mother')
|
from rest_framework import serializers
from .models import Animal
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = ('id', 'name', 'dob', 'gender',
'active', 'own', 'father', 'mother')
def validate_father(self, father):
if (father.gender != Animal.MALE):
raise serializers.ValidationError('The father has to be male.')
def validate_mother(self, mother):
if (mother.gender != Animal.FEMALE):
raise serializers.ValidationError('The mother has to be female.')
def validate_dob(self, dob):
father_id = self.context['request'].data['father']
if (father_id):
father = Animal.objects.get(pk = father_id)
if (father and father.dob > dob):
raise serializers.ValidationError('Animal can\'t be older than it\'s father')
mother_id = self.context['request'].data['mother']
if (mother_id):
mother = Animal.objects.get(pk = mother_id)
if (mother and mother.dob > dob):
raise serializers.ValidationError('Animal can\'t be older than it\'s mother')
|
Add validator that selected father is male and mother is female. Validate that the animal is younger than it's parents.
|
Add validator that selected father is male and mother is female.
Validate that the animal is younger than it's parents.
|
Python
|
apache-2.0
|
mmlado/animal_pairing,mmlado/animal_pairing
|
from rest_framework import serializers
from .models import Animal
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
- fields = ('id', 'name', 'dob', 'gender', 'active', 'own', 'father', 'mother')
+ fields = ('id', 'name', 'dob', 'gender',
+ 'active', 'own', 'father', 'mother')
+
+ def validate_father(self, father):
+ if (father.gender != Animal.MALE):
+ raise serializers.ValidationError('The father has to be male.')
+
+ def validate_mother(self, mother):
+ if (mother.gender != Animal.FEMALE):
+ raise serializers.ValidationError('The mother has to be female.')
+
+ def validate_dob(self, dob):
+ father_id = self.context['request'].data['father']
+ if (father_id):
+ father = Animal.objects.get(pk = father_id)
+ if (father and father.dob > dob):
+ raise serializers.ValidationError('Animal can\'t be older than it\'s father')
+
+ mother_id = self.context['request'].data['mother']
+ if (mother_id):
+ mother = Animal.objects.get(pk = mother_id)
+ if (mother and mother.dob > dob):
+ raise serializers.ValidationError('Animal can\'t be older than it\'s mother')
+
|
Add validator that selected father is male and mother is female. Validate that the animal is younger than it's parents.
|
## Code Before:
from rest_framework import serializers
from .models import Animal
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = ('id', 'name', 'dob', 'gender', 'active', 'own', 'father', 'mother')
## Instruction:
Add validator that selected father is male and mother is female. Validate that the animal is younger than it's parents.
## Code After:
from rest_framework import serializers
from .models import Animal
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = ('id', 'name', 'dob', 'gender',
'active', 'own', 'father', 'mother')
def validate_father(self, father):
if (father.gender != Animal.MALE):
raise serializers.ValidationError('The father has to be male.')
def validate_mother(self, mother):
if (mother.gender != Animal.FEMALE):
raise serializers.ValidationError('The mother has to be female.')
def validate_dob(self, dob):
father_id = self.context['request'].data['father']
if (father_id):
father = Animal.objects.get(pk = father_id)
if (father and father.dob > dob):
raise serializers.ValidationError('Animal can\'t be older than it\'s father')
mother_id = self.context['request'].data['mother']
if (mother_id):
mother = Animal.objects.get(pk = mother_id)
if (mother and mother.dob > dob):
raise serializers.ValidationError('Animal can\'t be older than it\'s mother')
|
# ... existing code ...
model = Animal
fields = ('id', 'name', 'dob', 'gender',
'active', 'own', 'father', 'mother')
def validate_father(self, father):
if (father.gender != Animal.MALE):
raise serializers.ValidationError('The father has to be male.')
def validate_mother(self, mother):
if (mother.gender != Animal.FEMALE):
raise serializers.ValidationError('The mother has to be female.')
def validate_dob(self, dob):
father_id = self.context['request'].data['father']
if (father_id):
father = Animal.objects.get(pk = father_id)
if (father and father.dob > dob):
raise serializers.ValidationError('Animal can\'t be older than it\'s father')
mother_id = self.context['request'].data['mother']
if (mother_id):
mother = Animal.objects.get(pk = mother_id)
if (mother and mother.dob > dob):
raise serializers.ValidationError('Animal can\'t be older than it\'s mother')
# ... rest of the code ...
|
c6a65af70acfed68036914b983856e1cbe26a235
|
session2/translate_all.py
|
session2/translate_all.py
|
import argparse, logging, codecs
from translation_model import TranslationModel
def setup_args():
parser = argparse.ArgumentParser()
parser.add_argument('model', help='trained model')
parser.add_argument('input', help='input sentences')
parser.add_argument('out', help='translated sentences')
args = parser.parse_args()
return args
def main():
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
args = setup_args()
logging.info(args)
tm = TranslationModel(args.model)
fw_out = codecs.open(args.out, 'w', 'utf-8')
for input_line in codecs.open(args.input, 'r', 'utf-8'):
results = tm.translate(input_line.strip())
fw_out.write(results[0][1] + '\n')
fw_out.close()
if __name__ == '__main__':
main()
|
import argparse, logging, codecs
from translation_model import TranslationModel
from nltk.translate.bleu_score import sentence_bleu as bleu
def setup_args():
parser = argparse.ArgumentParser()
parser.add_argument('model', help='trained model')
parser.add_argument('input', help='input sentences')
parser.add_argument('out', help='translated sentences')
parser.add_argument('--all', dest='all', action='store_true', help='Check all translations')
args = parser.parse_args()
return args
def find_best_translation(input_line, results):
best_bleu_score = 0.0
best_index = 0
for index, result in enumerate(results):
if len(result.split()) == 0:
continue
bleu_score = bleu([input_line.split()], result.split(), weights=(1.0,))
if bleu_score > best_bleu_score:
best_bleu_score = bleu_score
best_index = index
return best_index
def main():
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
args = setup_args()
logging.info(args)
tm = TranslationModel(args.model)
fw_out = codecs.open(args.out, 'w', 'utf-8')
for input_line in codecs.open(args.input, 'r', 'utf-8'):
results = tm.translate(input_line.strip(), k = 20)
if args.all:
index = find_best_translation(input_line, results)
else:
index = 0
fw_out.write(results[0][index] + '\n')
fw_out.close()
if __name__ == '__main__':
main()
|
Add option to check among 20 translations
|
Add option to check among 20 translations
|
Python
|
bsd-3-clause
|
vineetm/dl4mt-material,vineetm/dl4mt-material,vineetm/dl4mt-material,vineetm/dl4mt-material,vineetm/dl4mt-material
|
import argparse, logging, codecs
from translation_model import TranslationModel
-
+ from nltk.translate.bleu_score import sentence_bleu as bleu
def setup_args():
parser = argparse.ArgumentParser()
parser.add_argument('model', help='trained model')
parser.add_argument('input', help='input sentences')
parser.add_argument('out', help='translated sentences')
+ parser.add_argument('--all', dest='all', action='store_true', help='Check all translations')
args = parser.parse_args()
return args
+
+
+ def find_best_translation(input_line, results):
+ best_bleu_score = 0.0
+ best_index = 0
+
+ for index, result in enumerate(results):
+ if len(result.split()) == 0:
+ continue
+ bleu_score = bleu([input_line.split()], result.split(), weights=(1.0,))
+ if bleu_score > best_bleu_score:
+ best_bleu_score = bleu_score
+ best_index = index
+
+ return best_index
def main():
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
args = setup_args()
logging.info(args)
tm = TranslationModel(args.model)
fw_out = codecs.open(args.out, 'w', 'utf-8')
for input_line in codecs.open(args.input, 'r', 'utf-8'):
- results = tm.translate(input_line.strip())
+ results = tm.translate(input_line.strip(), k = 20)
+ if args.all:
+ index = find_best_translation(input_line, results)
+ else:
+ index = 0
+
- fw_out.write(results[0][1] + '\n')
+ fw_out.write(results[0][index] + '\n')
fw_out.close()
if __name__ == '__main__':
main()
|
Add option to check among 20 translations
|
## Code Before:
import argparse, logging, codecs
from translation_model import TranslationModel
def setup_args():
parser = argparse.ArgumentParser()
parser.add_argument('model', help='trained model')
parser.add_argument('input', help='input sentences')
parser.add_argument('out', help='translated sentences')
args = parser.parse_args()
return args
def main():
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
args = setup_args()
logging.info(args)
tm = TranslationModel(args.model)
fw_out = codecs.open(args.out, 'w', 'utf-8')
for input_line in codecs.open(args.input, 'r', 'utf-8'):
results = tm.translate(input_line.strip())
fw_out.write(results[0][1] + '\n')
fw_out.close()
if __name__ == '__main__':
main()
## Instruction:
Add option to check among 20 translations
## Code After:
import argparse, logging, codecs
from translation_model import TranslationModel
from nltk.translate.bleu_score import sentence_bleu as bleu
def setup_args():
parser = argparse.ArgumentParser()
parser.add_argument('model', help='trained model')
parser.add_argument('input', help='input sentences')
parser.add_argument('out', help='translated sentences')
parser.add_argument('--all', dest='all', action='store_true', help='Check all translations')
args = parser.parse_args()
return args
def find_best_translation(input_line, results):
best_bleu_score = 0.0
best_index = 0
for index, result in enumerate(results):
if len(result.split()) == 0:
continue
bleu_score = bleu([input_line.split()], result.split(), weights=(1.0,))
if bleu_score > best_bleu_score:
best_bleu_score = bleu_score
best_index = index
return best_index
def main():
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
args = setup_args()
logging.info(args)
tm = TranslationModel(args.model)
fw_out = codecs.open(args.out, 'w', 'utf-8')
for input_line in codecs.open(args.input, 'r', 'utf-8'):
results = tm.translate(input_line.strip(), k = 20)
if args.all:
index = find_best_translation(input_line, results)
else:
index = 0
fw_out.write(results[0][index] + '\n')
fw_out.close()
if __name__ == '__main__':
main()
|
...
from translation_model import TranslationModel
from nltk.translate.bleu_score import sentence_bleu as bleu
...
parser.add_argument('out', help='translated sentences')
parser.add_argument('--all', dest='all', action='store_true', help='Check all translations')
args = parser.parse_args()
...
return args
def find_best_translation(input_line, results):
best_bleu_score = 0.0
best_index = 0
for index, result in enumerate(results):
if len(result.split()) == 0:
continue
bleu_score = bleu([input_line.split()], result.split(), weights=(1.0,))
if bleu_score > best_bleu_score:
best_bleu_score = bleu_score
best_index = index
return best_index
...
for input_line in codecs.open(args.input, 'r', 'utf-8'):
results = tm.translate(input_line.strip(), k = 20)
if args.all:
index = find_best_translation(input_line, results)
else:
index = 0
fw_out.write(results[0][index] + '\n')
...
|
1ffff2738c4ced2aedb8b63f5c729860aab1bac7
|
marshmallow_jsonapi/__init__.py
|
marshmallow_jsonapi/__init__.py
|
from .schema import Schema, SchemaOpts
__version__ = "0.21.2"
__author__ = "Steven Loria"
__license__ = "MIT"
__all__ = ("Schema", "SchemaOpts")
|
from .schema import Schema, SchemaOpts
__version__ = "0.21.2"
__all__ = ("Schema", "SchemaOpts")
|
Remove unnecessary `__author__` and `__license__`
|
Remove unnecessary `__author__` and `__license__`
|
Python
|
mit
|
marshmallow-code/marshmallow-jsonapi
|
from .schema import Schema, SchemaOpts
__version__ = "0.21.2"
- __author__ = "Steven Loria"
- __license__ = "MIT"
-
__all__ = ("Schema", "SchemaOpts")
|
Remove unnecessary `__author__` and `__license__`
|
## Code Before:
from .schema import Schema, SchemaOpts
__version__ = "0.21.2"
__author__ = "Steven Loria"
__license__ = "MIT"
__all__ = ("Schema", "SchemaOpts")
## Instruction:
Remove unnecessary `__author__` and `__license__`
## Code After:
from .schema import Schema, SchemaOpts
__version__ = "0.21.2"
__all__ = ("Schema", "SchemaOpts")
|
// ... existing code ...
__version__ = "0.21.2"
__all__ = ("Schema", "SchemaOpts")
// ... rest of the code ...
|
2179dee14cfbd58ab8d8779561ac3826fe8892dd
|
custom/enikshay/reports/views.py
|
custom/enikshay/reports/views.py
|
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.locations.models import SQLLocation
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext
class LocationsView(View):
@method_decorator(login_and_domain_required)
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
def _locations_query(self, domain, query_text):
if query_text:
return SQLLocation.active_objects.filter_path_by_user_input(
domain=domain, user_input=query_text)
else:
return SQLLocation.active_objects.filter(domain=domain)
def query(self, domain, query_context):
locations = self._locations_query(domain, query_context.query).order_by('name')
return [
{'id': loc.location_id, 'text': loc.display_name}
for loc in locations[query_context.offset:query_context.offset + query_context.limit]
]
def query_count(self, domain, query):
return self._locations_query(domain, query).count()
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
return JsonResponse(
{
'results': self.query(domain, query_context),
'total': self.query_count(domain, query_context)
}
)
|
from collections import namedtuple
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext, LocationChoiceProvider
Report = namedtuple('Report', 'domain')
class LocationsView(View):
@method_decorator(login_and_domain_required)
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
location_choice_provider = LocationChoiceProvider(Report(domain=domain), None)
location_choice_provider.configure({'include_descendants': True})
return JsonResponse(
{
'results': [
{'id': location.value, 'text': location.display}
for location in location_choice_provider.query(query_context)
],
'total': location_choice_provider.query_count(query_context)
}
)
|
Use LocationChoiceProvider in enikshay location view
|
Use LocationChoiceProvider in enikshay location view
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
|
+ from collections import namedtuple
+
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
- from corehq.apps.locations.models import SQLLocation
- from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext
+ from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext, LocationChoiceProvider
+
+
+ Report = namedtuple('Report', 'domain')
class LocationsView(View):
@method_decorator(login_and_domain_required)
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
- def _locations_query(self, domain, query_text):
- if query_text:
- return SQLLocation.active_objects.filter_path_by_user_input(
- domain=domain, user_input=query_text)
- else:
- return SQLLocation.active_objects.filter(domain=domain)
-
- def query(self, domain, query_context):
- locations = self._locations_query(domain, query_context.query).order_by('name')
-
- return [
- {'id': loc.location_id, 'text': loc.display_name}
- for loc in locations[query_context.offset:query_context.offset + query_context.limit]
- ]
-
- def query_count(self, domain, query):
- return self._locations_query(domain, query).count()
-
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
+ location_choice_provider = LocationChoiceProvider(Report(domain=domain), None)
+ location_choice_provider.configure({'include_descendants': True})
return JsonResponse(
{
- 'results': self.query(domain, query_context),
+ 'results': [
+ {'id': location.value, 'text': location.display}
+ for location in location_choice_provider.query(query_context)
+ ],
- 'total': self.query_count(domain, query_context)
+ 'total': location_choice_provider.query_count(query_context)
}
)
|
Use LocationChoiceProvider in enikshay location view
|
## Code Before:
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.locations.models import SQLLocation
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext
class LocationsView(View):
@method_decorator(login_and_domain_required)
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
def _locations_query(self, domain, query_text):
if query_text:
return SQLLocation.active_objects.filter_path_by_user_input(
domain=domain, user_input=query_text)
else:
return SQLLocation.active_objects.filter(domain=domain)
def query(self, domain, query_context):
locations = self._locations_query(domain, query_context.query).order_by('name')
return [
{'id': loc.location_id, 'text': loc.display_name}
for loc in locations[query_context.offset:query_context.offset + query_context.limit]
]
def query_count(self, domain, query):
return self._locations_query(domain, query).count()
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
return JsonResponse(
{
'results': self.query(domain, query_context),
'total': self.query_count(domain, query_context)
}
)
## Instruction:
Use LocationChoiceProvider in enikshay location view
## Code After:
from collections import namedtuple
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext, LocationChoiceProvider
Report = namedtuple('Report', 'domain')
class LocationsView(View):
@method_decorator(login_and_domain_required)
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
location_choice_provider = LocationChoiceProvider(Report(domain=domain), None)
location_choice_provider.configure({'include_descendants': True})
return JsonResponse(
{
'results': [
{'id': location.value, 'text': location.display}
for location in location_choice_provider.query(query_context)
],
'total': location_choice_provider.query_count(query_context)
}
)
|
// ... existing code ...
from collections import namedtuple
from django.http.response import JsonResponse
// ... modified code ...
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext, LocationChoiceProvider
Report = namedtuple('Report', 'domain')
...
def get(self, request, domain, *args, **kwargs):
...
)
location_choice_provider = LocationChoiceProvider(Report(domain=domain), None)
location_choice_provider.configure({'include_descendants': True})
return JsonResponse(
...
{
'results': [
{'id': location.value, 'text': location.display}
for location in location_choice_provider.query(query_context)
],
'total': location_choice_provider.query_count(query_context)
}
// ... rest of the code ...
|
64f2720507067d10f298aa50245fa3b7b57a5bd4
|
dabuildsys/srcname.py
|
dabuildsys/srcname.py
|
from common import BuildError
import apt
import config
import checkout
def expand_srcname_spec(spec):
"""Parse a list of source packages on which the operation is to be performed.
If some variant of 'all' is specified, comparison against packages currently
APT repository is made and packages which have older version in APT than in Git
are returned."""
if len(spec) > 1 or not spec[0].startswith('all'):
return [checkout.PackageCheckout(pkg) for pkg in spec], {}
else:
if spec[0] == 'all':
releases = config.releases
elif spec[0].startswith('all:'):
releases = [spec[0].split(':')[1]]
else:
raise BuildError("Invalid all-package qualifier specified")
cache = {}
packages = set()
repos = {}
for release in releases:
_, _, apt_repo = apt.get_release(release)
repos[release] = apt_repo
comparison = apt.compare_against_git(apt_repo, checkout_cache=cache)
packages |= set(checkout.lookup_by_package_name(pkg) for pkg, gitver, aptver in comparison if gitver)
return [cache[pkg] for pkg in packages], repos
|
from common import BuildError
import apt
import config
import checkout
def expand_srcname_spec(spec):
"""Parse a list of source packages on which the operation is to be performed.
If some variant of 'all' is specified, comparison against packages currently
APT repository is made and packages which have older version in APT than in Git
are returned."""
if len(spec) == 1 and spec[0] == '*':
checkouts = []
for pkg in config.package_map:
try:
checkouts.append(checkout.PackageCheckout(pkg))
except Exception as e:
pass
return checkouts, {}
elif len(spec) > 1 or not spec[0].startswith('all'):
return [checkout.PackageCheckout(pkg) for pkg in spec], {}
else:
if spec[0] == 'all':
releases = config.releases
elif spec[0].startswith('all:'):
releases = [spec[0].split(':')[1]]
else:
raise BuildError("Invalid all-package qualifier specified")
cache = {}
packages = set()
repos = {}
for release in releases:
_, _, apt_repo = apt.get_release(release)
repos[release] = apt_repo
comparison = apt.compare_against_git(apt_repo, checkout_cache=cache)
packages |= set(checkout.lookup_by_package_name(pkg) for pkg, gitver, aptver in comparison if gitver)
return [cache[pkg] for pkg in packages], repos
|
Implement '*' package for all packages in Git
|
Implement '*' package for all packages in Git
|
Python
|
mit
|
mit-athena/build-system
|
from common import BuildError
import apt
import config
import checkout
def expand_srcname_spec(spec):
"""Parse a list of source packages on which the operation is to be performed.
If some variant of 'all' is specified, comparison against packages currently
APT repository is made and packages which have older version in APT than in Git
are returned."""
+ if len(spec) == 1 and spec[0] == '*':
+ checkouts = []
+ for pkg in config.package_map:
+ try:
+ checkouts.append(checkout.PackageCheckout(pkg))
+ except Exception as e:
+ pass
+ return checkouts, {}
- if len(spec) > 1 or not spec[0].startswith('all'):
+ elif len(spec) > 1 or not spec[0].startswith('all'):
return [checkout.PackageCheckout(pkg) for pkg in spec], {}
else:
if spec[0] == 'all':
releases = config.releases
elif spec[0].startswith('all:'):
releases = [spec[0].split(':')[1]]
else:
raise BuildError("Invalid all-package qualifier specified")
cache = {}
packages = set()
repos = {}
for release in releases:
_, _, apt_repo = apt.get_release(release)
repos[release] = apt_repo
comparison = apt.compare_against_git(apt_repo, checkout_cache=cache)
packages |= set(checkout.lookup_by_package_name(pkg) for pkg, gitver, aptver in comparison if gitver)
return [cache[pkg] for pkg in packages], repos
|
Implement '*' package for all packages in Git
|
## Code Before:
from common import BuildError
import apt
import config
import checkout
def expand_srcname_spec(spec):
"""Parse a list of source packages on which the operation is to be performed.
If some variant of 'all' is specified, comparison against packages currently
APT repository is made and packages which have older version in APT than in Git
are returned."""
if len(spec) > 1 or not spec[0].startswith('all'):
return [checkout.PackageCheckout(pkg) for pkg in spec], {}
else:
if spec[0] == 'all':
releases = config.releases
elif spec[0].startswith('all:'):
releases = [spec[0].split(':')[1]]
else:
raise BuildError("Invalid all-package qualifier specified")
cache = {}
packages = set()
repos = {}
for release in releases:
_, _, apt_repo = apt.get_release(release)
repos[release] = apt_repo
comparison = apt.compare_against_git(apt_repo, checkout_cache=cache)
packages |= set(checkout.lookup_by_package_name(pkg) for pkg, gitver, aptver in comparison if gitver)
return [cache[pkg] for pkg in packages], repos
## Instruction:
Implement '*' package for all packages in Git
## Code After:
from common import BuildError
import apt
import config
import checkout
def expand_srcname_spec(spec):
"""Parse a list of source packages on which the operation is to be performed.
If some variant of 'all' is specified, comparison against packages currently
APT repository is made and packages which have older version in APT than in Git
are returned."""
if len(spec) == 1 and spec[0] == '*':
checkouts = []
for pkg in config.package_map:
try:
checkouts.append(checkout.PackageCheckout(pkg))
except Exception as e:
pass
return checkouts, {}
elif len(spec) > 1 or not spec[0].startswith('all'):
return [checkout.PackageCheckout(pkg) for pkg in spec], {}
else:
if spec[0] == 'all':
releases = config.releases
elif spec[0].startswith('all:'):
releases = [spec[0].split(':')[1]]
else:
raise BuildError("Invalid all-package qualifier specified")
cache = {}
packages = set()
repos = {}
for release in releases:
_, _, apt_repo = apt.get_release(release)
repos[release] = apt_repo
comparison = apt.compare_against_git(apt_repo, checkout_cache=cache)
packages |= set(checkout.lookup_by_package_name(pkg) for pkg, gitver, aptver in comparison if gitver)
return [cache[pkg] for pkg in packages], repos
|
# ... existing code ...
if len(spec) == 1 and spec[0] == '*':
checkouts = []
for pkg in config.package_map:
try:
checkouts.append(checkout.PackageCheckout(pkg))
except Exception as e:
pass
return checkouts, {}
elif len(spec) > 1 or not spec[0].startswith('all'):
return [checkout.PackageCheckout(pkg) for pkg in spec], {}
# ... rest of the code ...
|
18cd04d24965d173a98ebb4e7425344a1992bcce
|
tests/test_ecdsa.py
|
tests/test_ecdsa.py
|
import pytest
import unittest
from graphenebase.ecdsa import (
sign_message,
verify_message
)
wif = "5J4KCbg1G3my9b9hCaQXnHSm6vrwW9xQTJS6ZciW2Kek7cCkCEk"
class Testcases(unittest.TestCase):
# Ignore warning:
# https://www.reddit.com/r/joinmarket/comments/5crhfh/userwarning_implicit_cast_from_char_to_a/
@pytest.mark.filterwarnings()
def test_sign_message(self):
signature = sign_message("Foobar", wif)
self.assertTrue(verify_message("Foobar", signature))
if __name__ == '__main__':
unittest.main()
|
import pytest
import unittest
from binascii import hexlify, unhexlify
import graphenebase.ecdsa as ecdsa
from graphenebase.account import PrivateKey, PublicKey, Address
wif = "5J4KCbg1G3my9b9hCaQXnHSm6vrwW9xQTJS6ZciW2Kek7cCkCEk"
class Testcases(unittest.TestCase):
# Ignore warning:
# https://www.reddit.com/r/joinmarket/comments/5crhfh/userwarning_implicit_cast_from_char_to_a/
@pytest.mark.filterwarnings()
def test_sign_message(self):
pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
signature = ecdsa.sign_message("Foobar", wif)
pub_key_sig = ecdsa.verify_message("Foobar", signature)
self.assertEqual(hexlify(pub_key_sig), pub_key)
def test_sign_message_cryptography(self):
if not ecdsa.CRYPTOGRAPHY_AVAILABLE:
return
ecdsa.SECP256K1_MODULE = "cryptography"
pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
signature = ecdsa.sign_message("Foobar", wif)
pub_key_sig = ecdsa.verify_message("Foobar", signature)
self.assertEqual(hexlify(pub_key_sig), pub_key)
def test_sign_message_secp256k1(self):
if not ecdsa.SECP256K1_AVAILABLE:
return
ecdsa.SECP256K1_MODULE = "secp256k1"
pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
signature = ecdsa.sign_message("Foobar", wif)
pub_key_sig = ecdsa.verify_message("Foobar", signature)
self.assertEqual(hexlify(pub_key_sig), pub_key)
if __name__ == '__main__':
unittest.main()
|
Add unit test for cryptography and secp256k1
|
Add unit test for cryptography and secp256k1
|
Python
|
mit
|
xeroc/python-graphenelib
|
import pytest
import unittest
+ from binascii import hexlify, unhexlify
+ import graphenebase.ecdsa as ecdsa
+ from graphenebase.account import PrivateKey, PublicKey, Address
- from graphenebase.ecdsa import (
- sign_message,
- verify_message
- )
-
wif = "5J4KCbg1G3my9b9hCaQXnHSm6vrwW9xQTJS6ZciW2Kek7cCkCEk"
class Testcases(unittest.TestCase):
# Ignore warning:
# https://www.reddit.com/r/joinmarket/comments/5crhfh/userwarning_implicit_cast_from_char_to_a/
@pytest.mark.filterwarnings()
def test_sign_message(self):
+ pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
- signature = sign_message("Foobar", wif)
+ signature = ecdsa.sign_message("Foobar", wif)
- self.assertTrue(verify_message("Foobar", signature))
+ pub_key_sig = ecdsa.verify_message("Foobar", signature)
+ self.assertEqual(hexlify(pub_key_sig), pub_key)
+
+ def test_sign_message_cryptography(self):
+ if not ecdsa.CRYPTOGRAPHY_AVAILABLE:
+ return
+ ecdsa.SECP256K1_MODULE = "cryptography"
+ pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
+ signature = ecdsa.sign_message("Foobar", wif)
+ pub_key_sig = ecdsa.verify_message("Foobar", signature)
+ self.assertEqual(hexlify(pub_key_sig), pub_key)
+
+ def test_sign_message_secp256k1(self):
+ if not ecdsa.SECP256K1_AVAILABLE:
+ return
+ ecdsa.SECP256K1_MODULE = "secp256k1"
+ pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
+ signature = ecdsa.sign_message("Foobar", wif)
+ pub_key_sig = ecdsa.verify_message("Foobar", signature)
+ self.assertEqual(hexlify(pub_key_sig), pub_key)
if __name__ == '__main__':
unittest.main()
|
Add unit test for cryptography and secp256k1
|
## Code Before:
import pytest
import unittest
from graphenebase.ecdsa import (
sign_message,
verify_message
)
wif = "5J4KCbg1G3my9b9hCaQXnHSm6vrwW9xQTJS6ZciW2Kek7cCkCEk"
class Testcases(unittest.TestCase):
# Ignore warning:
# https://www.reddit.com/r/joinmarket/comments/5crhfh/userwarning_implicit_cast_from_char_to_a/
@pytest.mark.filterwarnings()
def test_sign_message(self):
signature = sign_message("Foobar", wif)
self.assertTrue(verify_message("Foobar", signature))
if __name__ == '__main__':
unittest.main()
## Instruction:
Add unit test for cryptography and secp256k1
## Code After:
import pytest
import unittest
from binascii import hexlify, unhexlify
import graphenebase.ecdsa as ecdsa
from graphenebase.account import PrivateKey, PublicKey, Address
wif = "5J4KCbg1G3my9b9hCaQXnHSm6vrwW9xQTJS6ZciW2Kek7cCkCEk"
class Testcases(unittest.TestCase):
# Ignore warning:
# https://www.reddit.com/r/joinmarket/comments/5crhfh/userwarning_implicit_cast_from_char_to_a/
@pytest.mark.filterwarnings()
def test_sign_message(self):
pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
signature = ecdsa.sign_message("Foobar", wif)
pub_key_sig = ecdsa.verify_message("Foobar", signature)
self.assertEqual(hexlify(pub_key_sig), pub_key)
def test_sign_message_cryptography(self):
if not ecdsa.CRYPTOGRAPHY_AVAILABLE:
return
ecdsa.SECP256K1_MODULE = "cryptography"
pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
signature = ecdsa.sign_message("Foobar", wif)
pub_key_sig = ecdsa.verify_message("Foobar", signature)
self.assertEqual(hexlify(pub_key_sig), pub_key)
def test_sign_message_secp256k1(self):
if not ecdsa.SECP256K1_AVAILABLE:
return
ecdsa.SECP256K1_MODULE = "secp256k1"
pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
signature = ecdsa.sign_message("Foobar", wif)
pub_key_sig = ecdsa.verify_message("Foobar", signature)
self.assertEqual(hexlify(pub_key_sig), pub_key)
if __name__ == '__main__':
unittest.main()
|
// ... existing code ...
import unittest
from binascii import hexlify, unhexlify
import graphenebase.ecdsa as ecdsa
from graphenebase.account import PrivateKey, PublicKey, Address
// ... modified code ...
def test_sign_message(self):
pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
signature = ecdsa.sign_message("Foobar", wif)
pub_key_sig = ecdsa.verify_message("Foobar", signature)
self.assertEqual(hexlify(pub_key_sig), pub_key)
def test_sign_message_cryptography(self):
if not ecdsa.CRYPTOGRAPHY_AVAILABLE:
return
ecdsa.SECP256K1_MODULE = "cryptography"
pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
signature = ecdsa.sign_message("Foobar", wif)
pub_key_sig = ecdsa.verify_message("Foobar", signature)
self.assertEqual(hexlify(pub_key_sig), pub_key)
def test_sign_message_secp256k1(self):
if not ecdsa.SECP256K1_AVAILABLE:
return
ecdsa.SECP256K1_MODULE = "secp256k1"
pub_key = bytes(repr(PrivateKey(wif).pubkey), "latin")
signature = ecdsa.sign_message("Foobar", wif)
pub_key_sig = ecdsa.verify_message("Foobar", signature)
self.assertEqual(hexlify(pub_key_sig), pub_key)
// ... rest of the code ...
|
358cdd4b89221cbb02e7b04fc83cebb06570b03a
|
mezzanine/twitter/defaults.py
|
mezzanine/twitter/defaults.py
|
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import register_setting
from mezzanine.twitter import QUERY_TYPE_CHOICES, QUERY_TYPE_SEARCH
register_setting(
name="TWITTER_DEFAULT_QUERY_TYPE",
label=_("Default Twitter Query Type"),
description=_("Type of query that will be used to retrieve tweets for "
"the default Twitter feed."),
editable=True,
default=QUERY_TYPE_SEARCH,
choices=QUERY_TYPE_CHOICES,
)
register_setting(
name="TWITTER_DEFAULT_QUERY",
label=_("Default Twitter Query"),
description=_("Twitter query to use for the default query type."),
editable=True,
default="#django",
)
register_setting(
name="TWITTER_DEFAULT_NUM_TWEETS",
label=_("Default Number of Tweets"),
description=_("Number of tweets to display in the default Twitter feed."),
editable=True,
default=3,
)
|
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import register_setting
from mezzanine.twitter import QUERY_TYPE_CHOICES, QUERY_TYPE_SEARCH
register_setting(
name="TWITTER_DEFAULT_QUERY_TYPE",
label=_("Default Twitter Query Type"),
description=_("Type of query that will be used to retrieve tweets for "
"the default Twitter feed."),
editable=True,
default=QUERY_TYPE_SEARCH,
choices=QUERY_TYPE_CHOICES,
)
register_setting(
name="TWITTER_DEFAULT_QUERY",
label=_("Default Twitter Query"),
description=_("Twitter query to use for the default query type."),
editable=True,
default="django mezzanine",
)
register_setting(
name="TWITTER_DEFAULT_NUM_TWEETS",
label=_("Default Number of Tweets"),
description=_("Number of tweets to display in the default Twitter feed."),
editable=True,
default=3,
)
|
Update the default twitter query since it's been flooded by movie tweets.
|
Update the default twitter query since it's been flooded by movie tweets.
|
Python
|
bsd-2-clause
|
readevalprint/mezzanine,theclanks/mezzanine,dovydas/mezzanine,scarcry/snm-mezzanine,industrydive/mezzanine,ryneeverett/mezzanine,mush42/mezzanine,AlexHill/mezzanine,industrydive/mezzanine,spookylukey/mezzanine,eino-makitalo/mezzanine,Cajoline/mezzanine,Cajoline/mezzanine,webounty/mezzanine,gradel/mezzanine,dekomote/mezzanine-modeltranslation-backport,spookylukey/mezzanine,sjuxax/mezzanine,douglaskastle/mezzanine,vladir/mezzanine,Cicero-Zhao/mezzanine,geodesign/mezzanine,fusionbox/mezzanine,stbarnabas/mezzanine,orlenko/sfpirg,frankier/mezzanine,douglaskastle/mezzanine,damnfine/mezzanine,PegasusWang/mezzanine,stephenmcd/mezzanine,eino-makitalo/mezzanine,spookylukey/mezzanine,wbtuomela/mezzanine,agepoly/mezzanine,molokov/mezzanine,sjdines/mezzanine,christianwgd/mezzanine,dsanders11/mezzanine,readevalprint/mezzanine,batpad/mezzanine,frankchin/mezzanine,AlexHill/mezzanine,frankier/mezzanine,damnfine/mezzanine,Cicero-Zhao/mezzanine,wbtuomela/mezzanine,industrydive/mezzanine,SoLoHiC/mezzanine,frankchin/mezzanine,jjz/mezzanine,Skytorn86/mezzanine,mush42/mezzanine,ZeroXn/mezzanine,biomassives/mezzanine,gradel/mezzanine,emile2016/mezzanine,scarcry/snm-mezzanine,geodesign/mezzanine,viaregio/mezzanine,fusionbox/mezzanine,christianwgd/mezzanine,webounty/mezzanine,ZeroXn/mezzanine,Kniyl/mezzanine,cccs-web/mezzanine,molokov/mezzanine,tuxinhang1989/mezzanine,saintbird/mezzanine,ryneeverett/mezzanine,frankier/mezzanine,adrian-the-git/mezzanine,dsanders11/mezzanine,wyzex/mezzanine,sjdines/mezzanine,Skytorn86/mezzanine,Kniyl/mezzanine,orlenko/sfpirg,theclanks/mezzanine,orlenko/plei,dustinrb/mezzanine,agepoly/mezzanine,eino-makitalo/mezzanine,dovydas/mezzanine,joshcartme/mezzanine,sjdines/mezzanine,promil23/mezzanine,Kniyl/mezzanine,jjz/mezzanine,nikolas/mezzanine,sjuxax/mezzanine,joshcartme/mezzanine,molokov/mezzanine,dustinrb/mezzanine,vladir/mezzanine,tuxinhang1989/mezzanine,nikolas/mezzanine,wrwrwr/mezzanine,wyzex/mezzanine,saintbird/mezzanine,orlenko/plei,scarcry/snm-mezzanine,dovydas/mezzanine,nikolas/mezzanine,stephenmcd/mezzanine,ZeroXn/mezzanine,joshcartme/mezzanine,tuxinhang1989/mezzanine,dekomote/mezzanine-modeltranslation-backport,theclanks/mezzanine,ryneeverett/mezzanine,PegasusWang/mezzanine,damnfine/mezzanine,vladir/mezzanine,biomassives/mezzanine,adrian-the-git/mezzanine,orlenko/sfpirg,promil23/mezzanine,jjz/mezzanine,dustinrb/mezzanine,douglaskastle/mezzanine,SoLoHiC/mezzanine,stbarnabas/mezzanine,agepoly/mezzanine,dsanders11/mezzanine,batpad/mezzanine,wyzex/mezzanine,frankchin/mezzanine,adrian-the-git/mezzanine,PegasusWang/mezzanine,orlenko/plei,jerivas/mezzanine,wrwrwr/mezzanine,christianwgd/mezzanine,cccs-web/mezzanine,saintbird/mezzanine,jerivas/mezzanine,mush42/mezzanine,viaregio/mezzanine,webounty/mezzanine,dekomote/mezzanine-modeltranslation-backport,stephenmcd/mezzanine,jerivas/mezzanine,wbtuomela/mezzanine,biomassives/mezzanine,sjuxax/mezzanine,viaregio/mezzanine,promil23/mezzanine,gradel/mezzanine,SoLoHiC/mezzanine,emile2016/mezzanine,geodesign/mezzanine,Cajoline/mezzanine,Skytorn86/mezzanine,readevalprint/mezzanine,emile2016/mezzanine
|
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import register_setting
from mezzanine.twitter import QUERY_TYPE_CHOICES, QUERY_TYPE_SEARCH
register_setting(
name="TWITTER_DEFAULT_QUERY_TYPE",
label=_("Default Twitter Query Type"),
description=_("Type of query that will be used to retrieve tweets for "
"the default Twitter feed."),
editable=True,
default=QUERY_TYPE_SEARCH,
choices=QUERY_TYPE_CHOICES,
)
register_setting(
name="TWITTER_DEFAULT_QUERY",
label=_("Default Twitter Query"),
description=_("Twitter query to use for the default query type."),
editable=True,
- default="#django",
+ default="django mezzanine",
)
register_setting(
name="TWITTER_DEFAULT_NUM_TWEETS",
label=_("Default Number of Tweets"),
description=_("Number of tweets to display in the default Twitter feed."),
editable=True,
default=3,
)
|
Update the default twitter query since it's been flooded by movie tweets.
|
## Code Before:
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import register_setting
from mezzanine.twitter import QUERY_TYPE_CHOICES, QUERY_TYPE_SEARCH
register_setting(
name="TWITTER_DEFAULT_QUERY_TYPE",
label=_("Default Twitter Query Type"),
description=_("Type of query that will be used to retrieve tweets for "
"the default Twitter feed."),
editable=True,
default=QUERY_TYPE_SEARCH,
choices=QUERY_TYPE_CHOICES,
)
register_setting(
name="TWITTER_DEFAULT_QUERY",
label=_("Default Twitter Query"),
description=_("Twitter query to use for the default query type."),
editable=True,
default="#django",
)
register_setting(
name="TWITTER_DEFAULT_NUM_TWEETS",
label=_("Default Number of Tweets"),
description=_("Number of tweets to display in the default Twitter feed."),
editable=True,
default=3,
)
## Instruction:
Update the default twitter query since it's been flooded by movie tweets.
## Code After:
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import register_setting
from mezzanine.twitter import QUERY_TYPE_CHOICES, QUERY_TYPE_SEARCH
register_setting(
name="TWITTER_DEFAULT_QUERY_TYPE",
label=_("Default Twitter Query Type"),
description=_("Type of query that will be used to retrieve tweets for "
"the default Twitter feed."),
editable=True,
default=QUERY_TYPE_SEARCH,
choices=QUERY_TYPE_CHOICES,
)
register_setting(
name="TWITTER_DEFAULT_QUERY",
label=_("Default Twitter Query"),
description=_("Twitter query to use for the default query type."),
editable=True,
default="django mezzanine",
)
register_setting(
name="TWITTER_DEFAULT_NUM_TWEETS",
label=_("Default Number of Tweets"),
description=_("Number of tweets to display in the default Twitter feed."),
editable=True,
default=3,
)
|
# ... existing code ...
editable=True,
default="django mezzanine",
)
# ... rest of the code ...
|
e7998648c42d5bcccec7239d13521a5b77a738af
|
src/utils/indices.py
|
src/utils/indices.py
|
import json
import os
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Index
from model import APIDoc
def exists():
return Index(APIDoc.Index.name).exists()
def setup():
"""
Setup Elasticsearch Index.
Primary index with dynamic template.
Secondary index with static mappings.
"""
_dirname = os.path.dirname(__file__)
with open(os.path.join(_dirname, 'mapping.json'), 'r') as file:
mapping = json.load(file)
if not exists():
APIDoc.init()
elastic = Elasticsearch()
elastic.indices.put_mapping(
index=APIDoc.Index.name,
body=mapping
)
def delete():
Index(APIDoc.Index.name).delete()
def reset():
if exists():
delete()
setup()
def refresh():
index = Index(APIDoc.Index.name)
index.refresh()
|
import json
import os
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Index
from model import APIDoc
def exists():
return Index(APIDoc.Index.name).exists()
def setup():
"""
Setup Elasticsearch Index with dynamic template.
Run it on an open index to update dynamic mapping.
"""
_dirname = os.path.dirname(__file__)
with open(os.path.join(_dirname, 'mapping.json'), 'r') as file:
mapping = json.load(file)
if not exists():
APIDoc.init()
elastic = Elasticsearch()
elastic.indices.put_mapping(
index=APIDoc.Index.name,
body=mapping
)
def delete():
Index(APIDoc.Index.name).delete()
def reset():
if exists():
delete()
setup()
def refresh():
index = Index(APIDoc.Index.name)
index.refresh()
|
Allow setup function to update dynamic mapping
|
Allow setup function to update dynamic mapping
|
Python
|
mit
|
Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI
|
import json
import os
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Index
from model import APIDoc
def exists():
return Index(APIDoc.Index.name).exists()
def setup():
"""
+ Setup Elasticsearch Index with dynamic template.
+ Run it on an open index to update dynamic mapping.
- Setup Elasticsearch Index.
- Primary index with dynamic template.
- Secondary index with static mappings.
"""
_dirname = os.path.dirname(__file__)
with open(os.path.join(_dirname, 'mapping.json'), 'r') as file:
mapping = json.load(file)
if not exists():
APIDoc.init()
+
- elastic = Elasticsearch()
+ elastic = Elasticsearch()
- elastic.indices.put_mapping(
+ elastic.indices.put_mapping(
- index=APIDoc.Index.name,
+ index=APIDoc.Index.name,
- body=mapping
+ body=mapping
- )
+ )
def delete():
Index(APIDoc.Index.name).delete()
def reset():
if exists():
delete()
setup()
def refresh():
index = Index(APIDoc.Index.name)
index.refresh()
|
Allow setup function to update dynamic mapping
|
## Code Before:
import json
import os
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Index
from model import APIDoc
def exists():
return Index(APIDoc.Index.name).exists()
def setup():
"""
Setup Elasticsearch Index.
Primary index with dynamic template.
Secondary index with static mappings.
"""
_dirname = os.path.dirname(__file__)
with open(os.path.join(_dirname, 'mapping.json'), 'r') as file:
mapping = json.load(file)
if not exists():
APIDoc.init()
elastic = Elasticsearch()
elastic.indices.put_mapping(
index=APIDoc.Index.name,
body=mapping
)
def delete():
Index(APIDoc.Index.name).delete()
def reset():
if exists():
delete()
setup()
def refresh():
index = Index(APIDoc.Index.name)
index.refresh()
## Instruction:
Allow setup function to update dynamic mapping
## Code After:
import json
import os
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Index
from model import APIDoc
def exists():
return Index(APIDoc.Index.name).exists()
def setup():
"""
Setup Elasticsearch Index with dynamic template.
Run it on an open index to update dynamic mapping.
"""
_dirname = os.path.dirname(__file__)
with open(os.path.join(_dirname, 'mapping.json'), 'r') as file:
mapping = json.load(file)
if not exists():
APIDoc.init()
elastic = Elasticsearch()
elastic.indices.put_mapping(
index=APIDoc.Index.name,
body=mapping
)
def delete():
Index(APIDoc.Index.name).delete()
def reset():
if exists():
delete()
setup()
def refresh():
index = Index(APIDoc.Index.name)
index.refresh()
|
// ... existing code ...
"""
Setup Elasticsearch Index with dynamic template.
Run it on an open index to update dynamic mapping.
"""
// ... modified code ...
APIDoc.init()
elastic = Elasticsearch()
elastic.indices.put_mapping(
index=APIDoc.Index.name,
body=mapping
)
// ... rest of the code ...
|
d96e52c346314622afc904a2917416028c6784e3
|
swampdragon_live/models.py
|
swampdragon_live/models.py
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import push_new_content
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
'instance_pk': instance.pk})
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import push_new_content
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
'instance_pk': instance.pk})
|
Fix initial migration until ContentType is available
|
Fix initial migration until ContentType is available
|
Python
|
mit
|
mback2k/swampdragon-live,mback2k/swampdragon-live
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import push_new_content
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
+ if ContentType.objects.exists():
- instance_type = ContentType.objects.get_for_model(instance.__class__)
+ instance_type = ContentType.objects.get_for_model(instance.__class__)
- push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
+ push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
- 'instance_pk': instance.pk})
+ 'instance_pk': instance.pk})
|
Fix initial migration until ContentType is available
|
## Code Before:
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import push_new_content
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
'instance_pk': instance.pk})
## Instruction:
Fix initial migration until ContentType is available
## Code After:
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import push_new_content
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
'instance_pk': instance.pk})
|
# ... existing code ...
def post_save_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
'instance_pk': instance.pk})
# ... rest of the code ...
|
326c249e41e431112ae213c20bf948a7ae351a31
|
visualisation_display.py
|
visualisation_display.py
|
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray')
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
|
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n, vmin=0.0, vmax=1.0, labels=None):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
plt.axis('off')
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray', vmin=vmin, vmax=vmax)
if labels:
plt.text(0, -2, str(labels[i]))
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
|
Add vmin, vmax and possible labels to display of images
|
Add vmin, vmax and possible labels to display of images
|
Python
|
mit
|
ivanyu/kaggle-digit-recognizer,ivanyu/kaggle-digit-recognizer,ivanyu/kaggle-digit-recognizer
|
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
- def display(images, row_n, col_n):
+ def display(images, row_n, col_n, vmin=0.0, vmax=1.0, labels=None):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
+ plt.axis('off')
pixels = meta.vector_to_imt(images[i, :])
- plt.imshow(pixels, cmap='gray')
+ plt.imshow(pixels, cmap='gray', vmin=vmin, vmax=vmax)
+ if labels:
+ plt.text(0, -2, str(labels[i]))
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
|
Add vmin, vmax and possible labels to display of images
|
## Code Before:
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray')
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
## Instruction:
Add vmin, vmax and possible labels to display of images
## Code After:
from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
import meta
from meta import data_filename
def display(images, row_n, col_n, vmin=0.0, vmax=1.0, labels=None):
for i in range(len(images)):
plt.subplot(row_n, col_n, i + 1)
plt.axis('off')
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray', vmin=vmin, vmax=vmax)
if labels:
plt.text(0, -2, str(labels[i]))
plt.show()
if __name__ == '__main__':
X_test = np.load(data_filename(meta.TEST_PIXELS_BIN_FILENAME))
display(X_test[0:100, :], 10, 10)
|
# ... existing code ...
def display(images, row_n, col_n, vmin=0.0, vmax=1.0, labels=None):
for i in range(len(images)):
# ... modified code ...
plt.subplot(row_n, col_n, i + 1)
plt.axis('off')
pixels = meta.vector_to_imt(images[i, :])
plt.imshow(pixels, cmap='gray', vmin=vmin, vmax=vmax)
if labels:
plt.text(0, -2, str(labels[i]))
plt.show()
# ... rest of the code ...
|
7fad37d5a1121fe87db8946645043cd31a78b093
|
pi_gpio/events.py
|
pi_gpio/events.py
|
from pi_gpio import socketio
from config.pins import PinManager
class PinEventManager(PinManager):
def __init__(self):
super(PinEventManager, self).__init__()
self.socketio = socketio
self.edge = {
'RISING': self.gpio.RISING,
'FALLING': self.gpio.FALLING,
'BOTH': self.gpio.BOTH
}
def build_event_callback(self, num, name, event):
def event_callback(num):
data = {
'num': num,
'name': name,
'event': event
}
self.socketio.emit('pin:event', data)
print(data)
return event_callback
def register_gpio_events(self):
for num, config in self.pins.items():
event = config.get('event', None)
name = config.get('name', '')
if event:
edge = self.edge[event]
bounce = config['bounce']
cb = self.build_event_callback(num, name, event)
self.gpio.add_event_detect(num, edge, callback=cb, bouncetime=bounce)
|
from pi_gpio import socketio
from config.pins import PinManager
class PinEventManager(PinManager):
def __init__(self):
super(PinEventManager, self).__init__()
self.socketio = socketio
self.edge = {
'RISING': self.gpio.RISING,
'FALLING': self.gpio.FALLING,
'BOTH': self.gpio.BOTH
}
def build_event_callback(self, num, name, event):
def event_callback(num):
data = {
'num': num,
'name': name,
'event': event
}
self.socketio.emit('pin:event', data)
print(data)
return event_callback
def register_gpio_events(self):
for num, config in self.pins.items():
event = config.get('event', None)
name = config.get('name', '')
if event:
edge = self.edge[event]
bounce = config.get('bounce', -666)
cb = self.build_event_callback(num, name, event)
self.gpio.add_event_detect(num, edge, callback=cb, bouncetime=bounce)
|
Set the default bouncetime value to -666
|
Set the default bouncetime value to -666
Set the default bouncetime to -666 (the default value -666 is in Rpi.GPIO source code).
As-Is: if the bouncetime is not set, your setting for event detecting is silently down. And there is no notification that bouncetime is required.
|
Python
|
mit
|
projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server
|
from pi_gpio import socketio
from config.pins import PinManager
class PinEventManager(PinManager):
def __init__(self):
super(PinEventManager, self).__init__()
self.socketio = socketio
self.edge = {
'RISING': self.gpio.RISING,
'FALLING': self.gpio.FALLING,
'BOTH': self.gpio.BOTH
}
def build_event_callback(self, num, name, event):
def event_callback(num):
data = {
'num': num,
'name': name,
'event': event
}
self.socketio.emit('pin:event', data)
print(data)
return event_callback
def register_gpio_events(self):
for num, config in self.pins.items():
event = config.get('event', None)
name = config.get('name', '')
if event:
edge = self.edge[event]
- bounce = config['bounce']
+ bounce = config.get('bounce', -666)
cb = self.build_event_callback(num, name, event)
self.gpio.add_event_detect(num, edge, callback=cb, bouncetime=bounce)
|
Set the default bouncetime value to -666
|
## Code Before:
from pi_gpio import socketio
from config.pins import PinManager
class PinEventManager(PinManager):
def __init__(self):
super(PinEventManager, self).__init__()
self.socketio = socketio
self.edge = {
'RISING': self.gpio.RISING,
'FALLING': self.gpio.FALLING,
'BOTH': self.gpio.BOTH
}
def build_event_callback(self, num, name, event):
def event_callback(num):
data = {
'num': num,
'name': name,
'event': event
}
self.socketio.emit('pin:event', data)
print(data)
return event_callback
def register_gpio_events(self):
for num, config in self.pins.items():
event = config.get('event', None)
name = config.get('name', '')
if event:
edge = self.edge[event]
bounce = config['bounce']
cb = self.build_event_callback(num, name, event)
self.gpio.add_event_detect(num, edge, callback=cb, bouncetime=bounce)
## Instruction:
Set the default bouncetime value to -666
## Code After:
from pi_gpio import socketio
from config.pins import PinManager
class PinEventManager(PinManager):
def __init__(self):
super(PinEventManager, self).__init__()
self.socketio = socketio
self.edge = {
'RISING': self.gpio.RISING,
'FALLING': self.gpio.FALLING,
'BOTH': self.gpio.BOTH
}
def build_event_callback(self, num, name, event):
def event_callback(num):
data = {
'num': num,
'name': name,
'event': event
}
self.socketio.emit('pin:event', data)
print(data)
return event_callback
def register_gpio_events(self):
for num, config in self.pins.items():
event = config.get('event', None)
name = config.get('name', '')
if event:
edge = self.edge[event]
bounce = config.get('bounce', -666)
cb = self.build_event_callback(num, name, event)
self.gpio.add_event_detect(num, edge, callback=cb, bouncetime=bounce)
|
...
edge = self.edge[event]
bounce = config.get('bounce', -666)
cb = self.build_event_callback(num, name, event)
...
|
1ceea35669fd8e6eff5252ef6607289619f0f3c2
|
certbot/tests/main_test.py
|
certbot/tests/main_test.py
|
"""Tests for certbot.main."""
import unittest
import mock
from certbot import cli
from certbot import configuration
from certbot.plugins import disco as plugins_disco
class ObtainCertTest(unittest.TestCase):
"""Tests for certbot.main.obtain_cert."""
def _call(self, args):
plugins = plugins_disco.PluginsRegistry.find_all()
config = configuration.NamespaceConfig(
cli.prepare_and_parse_args(plugins, args))
from certbot import main
with mock.patch('certbot.main._init_le_client') as mock_init:
main.obtain_cert(config, plugins)
return mock_init() # returns the client
@mock.patch('certbot.main._auth_from_domains')
def test_no_reinstall_text_pause(self, mock_auth):
mock_auth.return_value = (mock.ANY, 'reinstall')
# This hangs if the reinstallation notification pauses
self._call('certonly --webroot -d example.com -t'.split())
if __name__ == '__main__':
unittest.main() # pragma: no cover
|
"""Tests for certbot.main."""
import unittest
import mock
from certbot import cli
from certbot import configuration
from certbot.plugins import disco as plugins_disco
class ObtainCertTest(unittest.TestCase):
"""Tests for certbot.main.obtain_cert."""
def setUp(self):
self.get_utility_patch = mock.patch(
'certbot.main.zope.component.getUtility')
self.mock_get_utility = self.get_utility_patch.start()
def tearDown(self):
self.get_utility_patch.stop()
def _call(self, args):
plugins = plugins_disco.PluginsRegistry.find_all()
config = configuration.NamespaceConfig(
cli.prepare_and_parse_args(plugins, args))
from certbot import main
with mock.patch('certbot.main._init_le_client') as mock_init:
main.obtain_cert(config, plugins)
return mock_init() # returns the client
@mock.patch('certbot.main._auth_from_domains')
def test_no_reinstall_text_pause(self, mock_auth):
mock_notification = self.mock_get_utility().notification
mock_notification.side_effect = self._assert_no_pause
mock_auth.return_value = (mock.ANY, 'reinstall')
self._call('certonly --webroot -d example.com -t'.split())
def _assert_no_pause(self, message, height=42, pause=True):
# pylint: disable=unused-argument
self.assertFalse(pause)
if __name__ == '__main__':
unittest.main() # pragma: no cover
|
Improve obtain_cert no pause test
|
Improve obtain_cert no pause test
|
Python
|
apache-2.0
|
lmcro/letsencrypt,jsha/letsencrypt,dietsche/letsencrypt,letsencrypt/letsencrypt,stweil/letsencrypt,wteiken/letsencrypt,bsmr-misc-forks/letsencrypt,wteiken/letsencrypt,bsmr-misc-forks/letsencrypt,lmcro/letsencrypt,stweil/letsencrypt,jtl999/certbot,DavidGarciaCat/letsencrypt,letsencrypt/letsencrypt,DavidGarciaCat/letsencrypt,jsha/letsencrypt,jtl999/certbot,dietsche/letsencrypt
|
"""Tests for certbot.main."""
import unittest
import mock
from certbot import cli
from certbot import configuration
from certbot.plugins import disco as plugins_disco
class ObtainCertTest(unittest.TestCase):
"""Tests for certbot.main.obtain_cert."""
+ def setUp(self):
+ self.get_utility_patch = mock.patch(
+ 'certbot.main.zope.component.getUtility')
+ self.mock_get_utility = self.get_utility_patch.start()
+
+ def tearDown(self):
+ self.get_utility_patch.stop()
+
def _call(self, args):
plugins = plugins_disco.PluginsRegistry.find_all()
config = configuration.NamespaceConfig(
cli.prepare_and_parse_args(plugins, args))
from certbot import main
with mock.patch('certbot.main._init_le_client') as mock_init:
main.obtain_cert(config, plugins)
return mock_init() # returns the client
@mock.patch('certbot.main._auth_from_domains')
def test_no_reinstall_text_pause(self, mock_auth):
+ mock_notification = self.mock_get_utility().notification
+ mock_notification.side_effect = self._assert_no_pause
mock_auth.return_value = (mock.ANY, 'reinstall')
- # This hangs if the reinstallation notification pauses
self._call('certonly --webroot -d example.com -t'.split())
+
+ def _assert_no_pause(self, message, height=42, pause=True):
+ # pylint: disable=unused-argument
+ self.assertFalse(pause)
if __name__ == '__main__':
unittest.main() # pragma: no cover
|
Improve obtain_cert no pause test
|
## Code Before:
"""Tests for certbot.main."""
import unittest
import mock
from certbot import cli
from certbot import configuration
from certbot.plugins import disco as plugins_disco
class ObtainCertTest(unittest.TestCase):
"""Tests for certbot.main.obtain_cert."""
def _call(self, args):
plugins = plugins_disco.PluginsRegistry.find_all()
config = configuration.NamespaceConfig(
cli.prepare_and_parse_args(plugins, args))
from certbot import main
with mock.patch('certbot.main._init_le_client') as mock_init:
main.obtain_cert(config, plugins)
return mock_init() # returns the client
@mock.patch('certbot.main._auth_from_domains')
def test_no_reinstall_text_pause(self, mock_auth):
mock_auth.return_value = (mock.ANY, 'reinstall')
# This hangs if the reinstallation notification pauses
self._call('certonly --webroot -d example.com -t'.split())
if __name__ == '__main__':
unittest.main() # pragma: no cover
## Instruction:
Improve obtain_cert no pause test
## Code After:
"""Tests for certbot.main."""
import unittest
import mock
from certbot import cli
from certbot import configuration
from certbot.plugins import disco as plugins_disco
class ObtainCertTest(unittest.TestCase):
"""Tests for certbot.main.obtain_cert."""
def setUp(self):
self.get_utility_patch = mock.patch(
'certbot.main.zope.component.getUtility')
self.mock_get_utility = self.get_utility_patch.start()
def tearDown(self):
self.get_utility_patch.stop()
def _call(self, args):
plugins = plugins_disco.PluginsRegistry.find_all()
config = configuration.NamespaceConfig(
cli.prepare_and_parse_args(plugins, args))
from certbot import main
with mock.patch('certbot.main._init_le_client') as mock_init:
main.obtain_cert(config, plugins)
return mock_init() # returns the client
@mock.patch('certbot.main._auth_from_domains')
def test_no_reinstall_text_pause(self, mock_auth):
mock_notification = self.mock_get_utility().notification
mock_notification.side_effect = self._assert_no_pause
mock_auth.return_value = (mock.ANY, 'reinstall')
self._call('certonly --webroot -d example.com -t'.split())
def _assert_no_pause(self, message, height=42, pause=True):
# pylint: disable=unused-argument
self.assertFalse(pause)
if __name__ == '__main__':
unittest.main() # pragma: no cover
|
// ... existing code ...
def setUp(self):
self.get_utility_patch = mock.patch(
'certbot.main.zope.component.getUtility')
self.mock_get_utility = self.get_utility_patch.start()
def tearDown(self):
self.get_utility_patch.stop()
def _call(self, args):
// ... modified code ...
def test_no_reinstall_text_pause(self, mock_auth):
mock_notification = self.mock_get_utility().notification
mock_notification.side_effect = self._assert_no_pause
mock_auth.return_value = (mock.ANY, 'reinstall')
self._call('certonly --webroot -d example.com -t'.split())
def _assert_no_pause(self, message, height=42, pause=True):
# pylint: disable=unused-argument
self.assertFalse(pause)
// ... rest of the code ...
|
17015ecf48ec37909de6de2c299454fc89b592e9
|
tests/test_gmaps.py
|
tests/test_gmaps.py
|
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
|
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
def test_url_dict_no_zoom(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78)))
|
Add failing test for URL without zoom
|
Add failing test for URL without zoom
|
Python
|
mit
|
bfontaine/jinja2_maps
|
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
+ def test_url_dict_no_zoom(self):
+ url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z"
+ self.assertEquals(url,
+ gmaps_url(dict(latitude=12.34, longitude=56.78)))
+
|
Add failing test for URL without zoom
|
## Code Before:
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
## Instruction:
Add failing test for URL without zoom
## Code After:
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
def test_url_dict_no_zoom(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78)))
|
# ... existing code ...
def test_url_dict_no_zoom(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78)))
# ... rest of the code ...
|
c9284827eeec90a253157286214bc1d17771db24
|
neutron/tests/api/test_service_type_management.py
|
neutron/tests/api/test_service_type_management.py
|
from tempest_lib import decorators
from neutron.tests.api import base
from neutron.tests.tempest import test
class ServiceTypeManagementTestJSON(base.BaseNetworkTest):
@classmethod
def resource_setup(cls):
super(ServiceTypeManagementTestJSON, cls).resource_setup()
if not test.is_extension_enabled('service-type', 'network'):
msg = "Neutron Service Type Management not enabled."
raise cls.skipException(msg)
@decorators.skip_because(bug="1400370")
@test.attr(type='smoke')
@test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6')
def test_service_provider_list(self):
body = self.client.list_service_providers()
self.assertIsInstance(body['service_providers'], list)
|
from neutron.tests.api import base
from neutron.tests.tempest import test
class ServiceTypeManagementTest(base.BaseNetworkTest):
@classmethod
def resource_setup(cls):
super(ServiceTypeManagementTest, cls).resource_setup()
if not test.is_extension_enabled('service-type', 'network'):
msg = "Neutron Service Type Management not enabled."
raise cls.skipException(msg)
@test.attr(type='smoke')
@test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6')
def test_service_provider_list(self):
body = self.client.list_service_providers()
self.assertIsInstance(body['service_providers'], list)
|
Remove skip of service-type management API test
|
Remove skip of service-type management API test
Advanced services split is complete so remove the skip
for the service-type management API test.
(Yes, there is only one placeholder test. More tests
need to be developed.)
Also remove the obsolete 'JSON' suffix from the test
class.
Closes-bug: 1400370
Change-Id: I5b4b8a67b24595568ea13bc400c1f5fce6d40f28
|
Python
|
apache-2.0
|
NeCTAR-RC/neutron,apporc/neutron,takeshineshiro/neutron,mmnelemane/neutron,barnsnake351/neutron,glove747/liberty-neutron,sasukeh/neutron,SamYaple/neutron,dhanunjaya/neutron,swdream/neutron,noironetworks/neutron,bgxavier/neutron,chitr/neutron,eonpatapon/neutron,glove747/liberty-neutron,paninetworks/neutron,antonioUnina/neutron,wenhuizhang/neutron,klmitch/neutron,wolverineav/neutron,suneeth51/neutron,eayunstack/neutron,igor-toga/local-snat,shahbazn/neutron,jerryz1982/neutron,cloudbase/neutron,bigswitch/neutron,vivekanand1101/neutron,wolverineav/neutron,jumpojoy/neutron,JianyuWang/neutron,cisco-openstack/neutron,paninetworks/neutron,openstack/neutron,watonyweng/neutron,bigswitch/neutron,skyddv/neutron,mattt416/neutron,dims/neutron,neoareslinux/neutron,JianyuWang/neutron,huntxu/neutron,skyddv/neutron,yanheven/neutron,adelina-t/neutron,cisco-openstack/neutron,eonpatapon/neutron,SmartInfrastructures/neutron,igor-toga/local-snat,apporc/neutron,mandeepdhami/neutron,antonioUnina/neutron,SmartInfrastructures/neutron,sebrandon1/neutron,bgxavier/neutron,MaximNevrov/neutron,chitr/neutron,SamYaple/neutron,mahak/neutron,jumpojoy/neutron,shahbazn/neutron,asgard-lab/neutron,jacknjzhou/neutron,asgard-lab/neutron,mattt416/neutron,huntxu/neutron,takeshineshiro/neutron,silenci/neutron,JioCloud/neutron,mandeepdhami/neutron,javaos74/neutron,noironetworks/neutron,MaximNevrov/neutron,jerryz1982/neutron,adelina-t/neutron,swdream/neutron,silenci/neutron,barnsnake351/neutron,JioCloud/neutron,mahak/neutron,openstack/neutron,wenhuizhang/neutron,yanheven/neutron,dhanunjaya/neutron,eayunstack/neutron,mmnelemane/neutron,cloudbase/neutron,suneeth51/neutron,sasukeh/neutron,NeCTAR-RC/neutron,klmitch/neutron,vivekanand1101/neutron,jacknjzhou/neutron,watonyweng/neutron,mahak/neutron,sebrandon1/neutron,openstack/neutron,javaos74/neutron,neoareslinux/neutron,dims/neutron
|
-
- from tempest_lib import decorators
from neutron.tests.api import base
from neutron.tests.tempest import test
- class ServiceTypeManagementTestJSON(base.BaseNetworkTest):
+ class ServiceTypeManagementTest(base.BaseNetworkTest):
@classmethod
def resource_setup(cls):
- super(ServiceTypeManagementTestJSON, cls).resource_setup()
+ super(ServiceTypeManagementTest, cls).resource_setup()
if not test.is_extension_enabled('service-type', 'network'):
msg = "Neutron Service Type Management not enabled."
raise cls.skipException(msg)
- @decorators.skip_because(bug="1400370")
@test.attr(type='smoke')
@test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6')
def test_service_provider_list(self):
body = self.client.list_service_providers()
self.assertIsInstance(body['service_providers'], list)
|
Remove skip of service-type management API test
|
## Code Before:
from tempest_lib import decorators
from neutron.tests.api import base
from neutron.tests.tempest import test
class ServiceTypeManagementTestJSON(base.BaseNetworkTest):
@classmethod
def resource_setup(cls):
super(ServiceTypeManagementTestJSON, cls).resource_setup()
if not test.is_extension_enabled('service-type', 'network'):
msg = "Neutron Service Type Management not enabled."
raise cls.skipException(msg)
@decorators.skip_because(bug="1400370")
@test.attr(type='smoke')
@test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6')
def test_service_provider_list(self):
body = self.client.list_service_providers()
self.assertIsInstance(body['service_providers'], list)
## Instruction:
Remove skip of service-type management API test
## Code After:
from neutron.tests.api import base
from neutron.tests.tempest import test
class ServiceTypeManagementTest(base.BaseNetworkTest):
@classmethod
def resource_setup(cls):
super(ServiceTypeManagementTest, cls).resource_setup()
if not test.is_extension_enabled('service-type', 'network'):
msg = "Neutron Service Type Management not enabled."
raise cls.skipException(msg)
@test.attr(type='smoke')
@test.idempotent_id('2cbbeea9-f010-40f6-8df5-4eaa0c918ea6')
def test_service_provider_list(self):
body = self.client.list_service_providers()
self.assertIsInstance(body['service_providers'], list)
|
// ... existing code ...
// ... modified code ...
class ServiceTypeManagementTest(base.BaseNetworkTest):
...
def resource_setup(cls):
super(ServiceTypeManagementTest, cls).resource_setup()
if not test.is_extension_enabled('service-type', 'network'):
...
@test.attr(type='smoke')
// ... rest of the code ...
|
aaaab0d93723e880119afb52840718634b184054
|
falcom/logtree.py
|
falcom/logtree.py
|
class MutableTree:
value = None
def full_length (self):
return 0
def walk (self):
return iter(())
def __len__ (self):
return 0
def __iter__ (self):
return iter(())
def __getitem__ (self, index):
raise IndexError("tree index out of range")
def __repr__ (self):
return "<{}>".format(self.__class__.__name__)
|
class MutableTree:
def __init__ (self):
self.value = None
def full_length (self):
return 0
def walk (self):
return iter(())
def __len__ (self):
return 0
def __iter__ (self):
return iter(())
def __getitem__ (self, index):
raise IndexError("tree index out of range")
def __repr__ (self):
return "<{}>".format(self.__class__.__name__)
|
Set MutableTree.value on the object only
|
Set MutableTree.value on the object only
|
Python
|
bsd-3-clause
|
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
|
class MutableTree:
+ def __init__ (self):
- value = None
+ self.value = None
def full_length (self):
return 0
def walk (self):
return iter(())
def __len__ (self):
return 0
def __iter__ (self):
return iter(())
def __getitem__ (self, index):
raise IndexError("tree index out of range")
def __repr__ (self):
return "<{}>".format(self.__class__.__name__)
|
Set MutableTree.value on the object only
|
## Code Before:
class MutableTree:
value = None
def full_length (self):
return 0
def walk (self):
return iter(())
def __len__ (self):
return 0
def __iter__ (self):
return iter(())
def __getitem__ (self, index):
raise IndexError("tree index out of range")
def __repr__ (self):
return "<{}>".format(self.__class__.__name__)
## Instruction:
Set MutableTree.value on the object only
## Code After:
class MutableTree:
def __init__ (self):
self.value = None
def full_length (self):
return 0
def walk (self):
return iter(())
def __len__ (self):
return 0
def __iter__ (self):
return iter(())
def __getitem__ (self, index):
raise IndexError("tree index out of range")
def __repr__ (self):
return "<{}>".format(self.__class__.__name__)
|
...
def __init__ (self):
self.value = None
...
|
cddb0309eaa0c31569f791b8b9f2c8666b65b8b4
|
openrcv/test/test_models.py
|
openrcv/test/test_models.py
|
from openrcv.models import ContestInfo
from openrcv.utiltest.helpers import UnitCase
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
|
from textwrap import dedent
from openrcv.models import BallotsResource, BallotStreamResource, ContestInfo
from openrcv.utils import StringInfo
from openrcv.utiltest.helpers import UnitCase
class BallotsResourceTest(UnitCase):
def test(self):
ballots = [1, 3, 2]
ballot_resource = BallotsResource(ballots)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, [1, 3, 2])
class BallotStreamResourceTest(UnitCase):
def test(self):
ballot_info = StringInfo("2 1 2\n3 1\n")
ballot_resource = BallotStreamResource(ballot_info)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, ['2 1 2\n', '3 1\n'])
def test_parse_default(self):
ballot_info = StringInfo("2 1 2\n3 1\n")
parse = lambda line: line.strip()
ballot_resource = BallotStreamResource(ballot_info, parse=parse)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, ['2 1 2', '3 1'])
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
|
Add tests for ballots resource classes.
|
Add tests for ballots resource classes.
|
Python
|
mit
|
cjerdonek/open-rcv,cjerdonek/open-rcv
|
+ from textwrap import dedent
+
+ from openrcv.models import BallotsResource, BallotStreamResource, ContestInfo
- from openrcv.models import ContestInfo
+ from openrcv.utils import StringInfo
from openrcv.utiltest.helpers import UnitCase
+
+
+ class BallotsResourceTest(UnitCase):
+
+ def test(self):
+ ballots = [1, 3, 2]
+ ballot_resource = BallotsResource(ballots)
+ with ballot_resource() as ballots:
+ ballots = list(ballots)
+ self.assertEqual(ballots, [1, 3, 2])
+
+
+ class BallotStreamResourceTest(UnitCase):
+
+ def test(self):
+ ballot_info = StringInfo("2 1 2\n3 1\n")
+ ballot_resource = BallotStreamResource(ballot_info)
+ with ballot_resource() as ballots:
+ ballots = list(ballots)
+ self.assertEqual(ballots, ['2 1 2\n', '3 1\n'])
+
+ def test_parse_default(self):
+ ballot_info = StringInfo("2 1 2\n3 1\n")
+ parse = lambda line: line.strip()
+ ballot_resource = BallotStreamResource(ballot_info, parse=parse)
+ with ballot_resource() as ballots:
+ ballots = list(ballots)
+ self.assertEqual(ballots, ['2 1 2', '3 1'])
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
|
Add tests for ballots resource classes.
|
## Code Before:
from openrcv.models import ContestInfo
from openrcv.utiltest.helpers import UnitCase
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
## Instruction:
Add tests for ballots resource classes.
## Code After:
from textwrap import dedent
from openrcv.models import BallotsResource, BallotStreamResource, ContestInfo
from openrcv.utils import StringInfo
from openrcv.utiltest.helpers import UnitCase
class BallotsResourceTest(UnitCase):
def test(self):
ballots = [1, 3, 2]
ballot_resource = BallotsResource(ballots)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, [1, 3, 2])
class BallotStreamResourceTest(UnitCase):
def test(self):
ballot_info = StringInfo("2 1 2\n3 1\n")
ballot_resource = BallotStreamResource(ballot_info)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, ['2 1 2\n', '3 1\n'])
def test_parse_default(self):
ballot_info = StringInfo("2 1 2\n3 1\n")
parse = lambda line: line.strip()
ballot_resource = BallotStreamResource(ballot_info, parse=parse)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, ['2 1 2', '3 1'])
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
|
# ... existing code ...
from textwrap import dedent
from openrcv.models import BallotsResource, BallotStreamResource, ContestInfo
from openrcv.utils import StringInfo
from openrcv.utiltest.helpers import UnitCase
class BallotsResourceTest(UnitCase):
def test(self):
ballots = [1, 3, 2]
ballot_resource = BallotsResource(ballots)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, [1, 3, 2])
class BallotStreamResourceTest(UnitCase):
def test(self):
ballot_info = StringInfo("2 1 2\n3 1\n")
ballot_resource = BallotStreamResource(ballot_info)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, ['2 1 2\n', '3 1\n'])
def test_parse_default(self):
ballot_info = StringInfo("2 1 2\n3 1\n")
parse = lambda line: line.strip()
ballot_resource = BallotStreamResource(ballot_info, parse=parse)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, ['2 1 2', '3 1'])
# ... rest of the code ...
|
3830ef5200f3d1763be5d162f5123cd59ca1da0b
|
virtualenv/__init__.py
|
virtualenv/__init__.py
|
from __future__ import absolute_import, division, print_function
from virtualenv.__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
from virtualenv.core import create
def create_environment(
home_dir,
site_packages=False, clear=False,
unzip_setuptools=False,
prompt=None, search_dirs=None, never_download=False,
no_setuptools=False, no_pip=False, symlink=True
):
create(
home_dir,
system_site_packages=site_packages,
clear=clear,
prompt=prompt or "",
extra_search_dirs=search_dirs,
setuptools=not no_setuptools,
pip=not no_pip
)
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
"create",
]
|
from __future__ import absolute_import, division, print_function
from virtualenv.__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
# some support for old api in legacy virtualenv
from virtualenv.core import create
from virtualenv.__main__ import main # flake8: noqa
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
"create", "create_environment", "main",
]
def create_environment(
home_dir,
site_packages=False, clear=False,
unzip_setuptools=False,
prompt=None, search_dirs=None, never_download=False,
no_setuptools=False, no_pip=False, symlink=True
): # flake8: noqa
create(
home_dir,
system_site_packages=site_packages,
clear=clear,
prompt=prompt or "",
extra_search_dirs=search_dirs,
setuptools=not no_setuptools,
pip=not no_pip
)
|
Add a main function (more support for the api in the legacy virtualenv).
|
Add a main function (more support for the api in the legacy virtualenv).
|
Python
|
mit
|
ionelmc/virtualenv,ionelmc/virtualenv,ionelmc/virtualenv
|
from __future__ import absolute_import, division, print_function
from virtualenv.__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
+
+ # some support for old api in legacy virtualenv
from virtualenv.core import create
+ from virtualenv.__main__ import main # flake8: noqa
+
+ __all__ = [
+ "__title__", "__summary__", "__uri__", "__version__", "__author__",
+ "__email__", "__license__", "__copyright__",
+ "create", "create_environment", "main",
+ ]
def create_environment(
home_dir,
site_packages=False, clear=False,
unzip_setuptools=False,
prompt=None, search_dirs=None, never_download=False,
no_setuptools=False, no_pip=False, symlink=True
- ):
+ ): # flake8: noqa
create(
home_dir,
system_site_packages=site_packages,
clear=clear,
prompt=prompt or "",
extra_search_dirs=search_dirs,
setuptools=not no_setuptools,
pip=not no_pip
)
- __all__ = [
- "__title__", "__summary__", "__uri__", "__version__", "__author__",
- "__email__", "__license__", "__copyright__",
- "create",
- ]
-
|
Add a main function (more support for the api in the legacy virtualenv).
|
## Code Before:
from __future__ import absolute_import, division, print_function
from virtualenv.__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
from virtualenv.core import create
def create_environment(
home_dir,
site_packages=False, clear=False,
unzip_setuptools=False,
prompt=None, search_dirs=None, never_download=False,
no_setuptools=False, no_pip=False, symlink=True
):
create(
home_dir,
system_site_packages=site_packages,
clear=clear,
prompt=prompt or "",
extra_search_dirs=search_dirs,
setuptools=not no_setuptools,
pip=not no_pip
)
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
"create",
]
## Instruction:
Add a main function (more support for the api in the legacy virtualenv).
## Code After:
from __future__ import absolute_import, division, print_function
from virtualenv.__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
# some support for old api in legacy virtualenv
from virtualenv.core import create
from virtualenv.__main__ import main # flake8: noqa
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
"create", "create_environment", "main",
]
def create_environment(
home_dir,
site_packages=False, clear=False,
unzip_setuptools=False,
prompt=None, search_dirs=None, never_download=False,
no_setuptools=False, no_pip=False, symlink=True
): # flake8: noqa
create(
home_dir,
system_site_packages=site_packages,
clear=clear,
prompt=prompt or "",
extra_search_dirs=search_dirs,
setuptools=not no_setuptools,
pip=not no_pip
)
|
// ... existing code ...
)
# some support for old api in legacy virtualenv
from virtualenv.core import create
from virtualenv.__main__ import main # flake8: noqa
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
"create", "create_environment", "main",
]
// ... modified code ...
no_setuptools=False, no_pip=False, symlink=True
): # flake8: noqa
create(
...
)
// ... rest of the code ...
|
a8bb719061a68b5d322868768203476c4ee1e9b9
|
gnocchi/cli.py
|
gnocchi/cli.py
|
from oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
|
from oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
indexer.connect()
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
|
Connect to database before upgrading it
|
Connect to database before upgrading it
This change ensure we are connected to the database before
we upgrade it.
Change-Id: Ia0be33892a99897ff294d004f4d935f3753e6200
|
Python
|
apache-2.0
|
idegtiarov/gnocchi-rep,leandroreox/gnocchi,sileht/gnocchi,idegtiarov/gnocchi-rep,gnocchixyz/gnocchi,sileht/gnocchi,idegtiarov/gnocchi-rep,gnocchixyz/gnocchi,leandroreox/gnocchi
|
from oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
+ indexer.connect()
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
|
Connect to database before upgrading it
|
## Code Before:
from oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
## Instruction:
Connect to database before upgrading it
## Code After:
from oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
indexer.connect()
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
|
// ... existing code ...
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
indexer.connect()
indexer.upgrade()
// ... rest of the code ...
|
f6a382a9a52ef2321c18ba63a2ece6930dadcf62
|
src/pybel/manager/__init__.py
|
src/pybel/manager/__init__.py
|
from . import base_manager, cache_manager, citation_utils, database_io, make_json_serializable, models, query_manager
from .base_manager import *
from .cache_manager import *
from .database_io import *
from .models import *
from .query_manager import *
__all__ = (
base_manager.__all__ +
cache_manager.__all__ +
citation_utils.__all__ +
database_io.__all__ +
models.__all__ +
query_manager.__all__
)
|
from . import base_manager, cache_manager, citation_utils, database_io, make_json_serializable, models, query_manager
from .base_manager import *
from .cache_manager import *
from .citation_utils import *
from .database_io import *
from .models import *
from .query_manager import *
__all__ = (
base_manager.__all__ +
cache_manager.__all__ +
citation_utils.__all__ +
database_io.__all__ +
models.__all__ +
query_manager.__all__
)
|
Add citation utils to init
|
Add citation utils to init
|
Python
|
mit
|
pybel/pybel,pybel/pybel,pybel/pybel
|
from . import base_manager, cache_manager, citation_utils, database_io, make_json_serializable, models, query_manager
from .base_manager import *
from .cache_manager import *
+ from .citation_utils import *
from .database_io import *
from .models import *
from .query_manager import *
__all__ = (
base_manager.__all__ +
cache_manager.__all__ +
citation_utils.__all__ +
database_io.__all__ +
models.__all__ +
query_manager.__all__
)
|
Add citation utils to init
|
## Code Before:
from . import base_manager, cache_manager, citation_utils, database_io, make_json_serializable, models, query_manager
from .base_manager import *
from .cache_manager import *
from .database_io import *
from .models import *
from .query_manager import *
__all__ = (
base_manager.__all__ +
cache_manager.__all__ +
citation_utils.__all__ +
database_io.__all__ +
models.__all__ +
query_manager.__all__
)
## Instruction:
Add citation utils to init
## Code After:
from . import base_manager, cache_manager, citation_utils, database_io, make_json_serializable, models, query_manager
from .base_manager import *
from .cache_manager import *
from .citation_utils import *
from .database_io import *
from .models import *
from .query_manager import *
__all__ = (
base_manager.__all__ +
cache_manager.__all__ +
citation_utils.__all__ +
database_io.__all__ +
models.__all__ +
query_manager.__all__
)
|
...
from .cache_manager import *
from .citation_utils import *
from .database_io import *
...
|
153025aaa585e70d09509248ab18b214194759ae
|
tasks/static.py
|
tasks/static.py
|
import os.path
import shutil
import invoke
@invoke.task
def build():
# Build our CSS files
invoke.run("compass compile -c compass.rb --force")
@invoke.task
def watch():
try:
# Watch With Compass
invoke.run("compass watch -c compass.rb")
except KeyboardInterrupt:
pass
|
import os.path
import shutil
import invoke
@invoke.task
def build():
# Build our CSS files
invoke.run("compass compile -c config.rb --force")
@invoke.task
def watch():
try:
# Watch With Compass
invoke.run("compass watch -c config.rb")
except KeyboardInterrupt:
pass
|
Deal with the compass.rb -> config.rb change
|
Deal with the compass.rb -> config.rb change
|
Python
|
apache-2.0
|
techtonik/warehouse,techtonik/warehouse
|
import os.path
import shutil
import invoke
@invoke.task
def build():
# Build our CSS files
- invoke.run("compass compile -c compass.rb --force")
+ invoke.run("compass compile -c config.rb --force")
@invoke.task
def watch():
try:
# Watch With Compass
- invoke.run("compass watch -c compass.rb")
+ invoke.run("compass watch -c config.rb")
except KeyboardInterrupt:
pass
|
Deal with the compass.rb -> config.rb change
|
## Code Before:
import os.path
import shutil
import invoke
@invoke.task
def build():
# Build our CSS files
invoke.run("compass compile -c compass.rb --force")
@invoke.task
def watch():
try:
# Watch With Compass
invoke.run("compass watch -c compass.rb")
except KeyboardInterrupt:
pass
## Instruction:
Deal with the compass.rb -> config.rb change
## Code After:
import os.path
import shutil
import invoke
@invoke.task
def build():
# Build our CSS files
invoke.run("compass compile -c config.rb --force")
@invoke.task
def watch():
try:
# Watch With Compass
invoke.run("compass watch -c config.rb")
except KeyboardInterrupt:
pass
|
...
# Build our CSS files
invoke.run("compass compile -c config.rb --force")
...
# Watch With Compass
invoke.run("compass watch -c config.rb")
except KeyboardInterrupt:
...
|
1e8f9a95badc1e2b558bae7570ef9bc23f26a0df
|
pyhaystack/info.py
|
pyhaystack/info.py
|
__author__ = 'Christian Tremblay, @sjlongland, @sudo-Whateverman, Igor'
__author_email__ = '[email protected]'
__version__ = '0.71.1.8.2'
__license__ = 'LGPL'
|
__author__ = 'Christian Tremblay, Stuart J. Longland, @sudo-Whateverman, Igor'
__author_email__ = '[email protected]'
__version__ = '0.72'
__license__ = 'LGPL'
|
Modify version to 0.72 to mark change
|
Modify version to 0.72 to mark change
Signed-off-by: Christian Tremblay <[email protected]>
|
Python
|
apache-2.0
|
ChristianTremblay/pyhaystack,vrtsystems/pyhaystack,ChristianTremblay/pyhaystack
|
- __author__ = 'Christian Tremblay, @sjlongland, @sudo-Whateverman, Igor'
+ __author__ = 'Christian Tremblay, Stuart J. Longland, @sudo-Whateverman, Igor'
__author_email__ = '[email protected]'
- __version__ = '0.71.1.8.2'
+ __version__ = '0.72'
__license__ = 'LGPL'
|
Modify version to 0.72 to mark change
|
## Code Before:
__author__ = 'Christian Tremblay, @sjlongland, @sudo-Whateverman, Igor'
__author_email__ = '[email protected]'
__version__ = '0.71.1.8.2'
__license__ = 'LGPL'
## Instruction:
Modify version to 0.72 to mark change
## Code After:
__author__ = 'Christian Tremblay, Stuart J. Longland, @sudo-Whateverman, Igor'
__author_email__ = '[email protected]'
__version__ = '0.72'
__license__ = 'LGPL'
|
// ... existing code ...
__author__ = 'Christian Tremblay, Stuart J. Longland, @sudo-Whateverman, Igor'
__author_email__ = '[email protected]'
__version__ = '0.72'
__license__ = 'LGPL'
// ... rest of the code ...
|
cbb11e996381197d551425585fca225d630fa383
|
tests/test_simpleflow/utils/test_misc.py
|
tests/test_simpleflow/utils/test_misc.py
|
import unittest
from simpleflow.utils import format_exc
class MyTestCase(unittest.TestCase):
def test_format_final_exc_line(self):
line = None
try:
1/0
except Exception as e:
line = format_exc(e)
self.assertEqual("ZeroDivisionError: division by zero", line)
try:
{}[1]
except Exception as e:
line = format_exc(e)
self.assertEqual("KeyError: 1", line)
if __name__ == '__main__':
unittest.main()
|
import unittest
from simpleflow.utils import format_exc
class MyTestCase(unittest.TestCase):
def test_format_final_exc_line(self):
line = None
try:
{}[1]
except Exception as e:
line = format_exc(e)
self.assertEqual("KeyError: 1", line)
if __name__ == '__main__':
unittest.main()
|
Remove version-specific exception text test
|
Remove version-specific exception text test
Signed-off-by: Yves Bastide <[email protected]>
|
Python
|
mit
|
botify-labs/simpleflow,botify-labs/simpleflow
|
import unittest
from simpleflow.utils import format_exc
class MyTestCase(unittest.TestCase):
def test_format_final_exc_line(self):
line = None
- try:
- 1/0
- except Exception as e:
- line = format_exc(e)
- self.assertEqual("ZeroDivisionError: division by zero", line)
-
try:
{}[1]
except Exception as e:
line = format_exc(e)
self.assertEqual("KeyError: 1", line)
if __name__ == '__main__':
unittest.main()
|
Remove version-specific exception text test
|
## Code Before:
import unittest
from simpleflow.utils import format_exc
class MyTestCase(unittest.TestCase):
def test_format_final_exc_line(self):
line = None
try:
1/0
except Exception as e:
line = format_exc(e)
self.assertEqual("ZeroDivisionError: division by zero", line)
try:
{}[1]
except Exception as e:
line = format_exc(e)
self.assertEqual("KeyError: 1", line)
if __name__ == '__main__':
unittest.main()
## Instruction:
Remove version-specific exception text test
## Code After:
import unittest
from simpleflow.utils import format_exc
class MyTestCase(unittest.TestCase):
def test_format_final_exc_line(self):
line = None
try:
{}[1]
except Exception as e:
line = format_exc(e)
self.assertEqual("KeyError: 1", line)
if __name__ == '__main__':
unittest.main()
|
# ... existing code ...
try:
{}[1]
# ... rest of the code ...
|
5cf0b19d67a667d4e0d48a12f0ee94f3387cfa37
|
tests/test_helpers.py
|
tests/test_helpers.py
|
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
|
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
def test_return_function(self):
fn = helpers.import_function('os.path.join')
self.assertEqual(callable(fn), True)
|
Add test to ensure talons.helpers.import_function returns a callable
|
Add test to ensure talons.helpers.import_function returns a callable
|
Python
|
apache-2.0
|
talons/talons,jaypipes/talons
|
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
+ def test_return_function(self):
+ fn = helpers.import_function('os.path.join')
+ self.assertEqual(callable(fn), True)
+
|
Add test to ensure talons.helpers.import_function returns a callable
|
## Code Before:
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
## Instruction:
Add test to ensure talons.helpers.import_function returns a callable
## Code After:
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
def test_return_function(self):
fn = helpers.import_function('os.path.join')
self.assertEqual(callable(fn), True)
|
// ... existing code ...
helpers.import_function('sys.stdout')
def test_return_function(self):
fn = helpers.import_function('os.path.join')
self.assertEqual(callable(fn), True)
// ... rest of the code ...
|
f5e36391c253a52fe2bd434caf59c0f5c389cc64
|
tests/base.py
|
tests/base.py
|
import unittest
import os
os.environ['OGN_CONFIG_MODULE'] = 'config/test.py'
from ogn_python import db # noqa: E402
class TestBaseDB(unittest.TestCase):
@classmethod
def setUpClass(cls):
db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;')
db.session.commit()
db.create_all()
def setUp(self):
pass
def tearDown(self):
db.session.execute("""
DELETE FROM aircraft_beacons;
DELETE FROM receiver_beacons;
DELETE FROM takeoff_landings;
DELETE FROM logbook;
DELETE FROM receiver_coverages;
DELETE FROM device_stats;
DELETE FROM receiver_stats;
DELETE FROM receivers;
DELETE FROM devices;
""")
if __name__ == '__main__':
unittest.main()
|
import unittest
import os
os.environ['OGN_CONFIG_MODULE'] = 'config/test.py'
from ogn_python import db # noqa: E402
class TestBaseDB(unittest.TestCase):
@classmethod
def setUpClass(cls):
db.drop_all()
db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;')
db.session.commit()
db.create_all()
def setUp(self):
pass
def tearDown(self):
db.session.execute("""
DELETE FROM aircraft_beacons;
DELETE FROM receiver_beacons;
DELETE FROM takeoff_landings;
DELETE FROM logbook;
DELETE FROM receiver_coverages;
DELETE FROM device_stats;
DELETE FROM receiver_stats;
DELETE FROM receivers;
DELETE FROM devices;
""")
if __name__ == '__main__':
unittest.main()
|
Drop db before each test
|
Drop db before each test
|
Python
|
agpl-3.0
|
Meisterschueler/ogn-python,glidernet/ogn-python,glidernet/ogn-python,Meisterschueler/ogn-python,glidernet/ogn-python,glidernet/ogn-python,Meisterschueler/ogn-python,Meisterschueler/ogn-python
|
import unittest
import os
os.environ['OGN_CONFIG_MODULE'] = 'config/test.py'
from ogn_python import db # noqa: E402
class TestBaseDB(unittest.TestCase):
@classmethod
def setUpClass(cls):
+ db.drop_all()
db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;')
db.session.commit()
db.create_all()
def setUp(self):
pass
def tearDown(self):
db.session.execute("""
DELETE FROM aircraft_beacons;
DELETE FROM receiver_beacons;
DELETE FROM takeoff_landings;
DELETE FROM logbook;
DELETE FROM receiver_coverages;
DELETE FROM device_stats;
DELETE FROM receiver_stats;
DELETE FROM receivers;
DELETE FROM devices;
""")
if __name__ == '__main__':
unittest.main()
|
Drop db before each test
|
## Code Before:
import unittest
import os
os.environ['OGN_CONFIG_MODULE'] = 'config/test.py'
from ogn_python import db # noqa: E402
class TestBaseDB(unittest.TestCase):
@classmethod
def setUpClass(cls):
db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;')
db.session.commit()
db.create_all()
def setUp(self):
pass
def tearDown(self):
db.session.execute("""
DELETE FROM aircraft_beacons;
DELETE FROM receiver_beacons;
DELETE FROM takeoff_landings;
DELETE FROM logbook;
DELETE FROM receiver_coverages;
DELETE FROM device_stats;
DELETE FROM receiver_stats;
DELETE FROM receivers;
DELETE FROM devices;
""")
if __name__ == '__main__':
unittest.main()
## Instruction:
Drop db before each test
## Code After:
import unittest
import os
os.environ['OGN_CONFIG_MODULE'] = 'config/test.py'
from ogn_python import db # noqa: E402
class TestBaseDB(unittest.TestCase):
@classmethod
def setUpClass(cls):
db.drop_all()
db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;')
db.session.commit()
db.create_all()
def setUp(self):
pass
def tearDown(self):
db.session.execute("""
DELETE FROM aircraft_beacons;
DELETE FROM receiver_beacons;
DELETE FROM takeoff_landings;
DELETE FROM logbook;
DELETE FROM receiver_coverages;
DELETE FROM device_stats;
DELETE FROM receiver_stats;
DELETE FROM receivers;
DELETE FROM devices;
""")
if __name__ == '__main__':
unittest.main()
|
// ... existing code ...
def setUpClass(cls):
db.drop_all()
db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;')
// ... rest of the code ...
|
84f4626a623283c3c4d98d9be0ccd69fe837f772
|
download_data.py
|
download_data.py
|
from lbtoolbox.download import download
import os
import inspect
import tarfile
def here(f):
me = inspect.getsourcefile(here)
return os.path.join(os.path.dirname(os.path.abspath(me)), f)
def download_extract(url, into):
fname = download(url, into)
print("Extracting...")
with tarfile.open(fname) as f:
f.extractall(path=into)
if __name__ == '__main__':
baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/tosato/'
datadir = here('data')
# First, download the Tosato datasets.
download_extract(baseurl + 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
download_extract(baseurl + 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
download_extract(baseurl + 'HIIT6HeadPose.tar.bz2', into=datadir)
download_extract(baseurl + 'HOC.tar.bz2', into=datadir)
download_extract(baseurl + 'HOCoffee.tar.bz2', into=datadir)
download_extract(baseurl + 'IHDPHeadPose.tar.bz2', into=datadir)
download_extract(baseurl + 'QMULPoseHeads.tar.bz2', into=datadir)
|
from lbtoolbox.download import download
import os
import inspect
import tarfile
def here(f):
me = inspect.getsourcefile(here)
return os.path.join(os.path.dirname(os.path.abspath(me)), f)
def download_extract(urlbase, name, into):
print("Downloading " + name)
fname = download(os.path.join(urlbase, name), into)
print("Extracting...")
with tarfile.open(fname) as f:
f.extractall(path=into)
if __name__ == '__main__':
baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/BiternionNets/'
datadir = here('data')
# First, download the Tosato datasets.
download_extract(baseurl, 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
download_extract(baseurl, 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
download_extract(baseurl, 'HIIT6HeadPose.tar.bz2', into=datadir)
download_extract(baseurl, 'HOC.tar.bz2', into=datadir)
download_extract(baseurl, 'HOCoffee.tar.bz2', into=datadir)
download_extract(baseurl, 'IHDPHeadPose.tar.bz2', into=datadir)
download_extract(baseurl, 'QMULPoseHeads.tar.bz2', into=datadir)
print("Done.")
|
Update download URL and add more output to downloader.
|
Update download URL and add more output to downloader.
|
Python
|
mit
|
lucasb-eyer/BiternionNet
|
from lbtoolbox.download import download
import os
import inspect
import tarfile
def here(f):
me = inspect.getsourcefile(here)
return os.path.join(os.path.dirname(os.path.abspath(me)), f)
- def download_extract(url, into):
+ def download_extract(urlbase, name, into):
- fname = download(url, into)
+ print("Downloading " + name)
+ fname = download(os.path.join(urlbase, name), into)
print("Extracting...")
with tarfile.open(fname) as f:
f.extractall(path=into)
if __name__ == '__main__':
- baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/tosato/'
+ baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/BiternionNets/'
datadir = here('data')
# First, download the Tosato datasets.
- download_extract(baseurl + 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
+ download_extract(baseurl, 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
- download_extract(baseurl + 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
+ download_extract(baseurl, 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
- download_extract(baseurl + 'HIIT6HeadPose.tar.bz2', into=datadir)
+ download_extract(baseurl, 'HIIT6HeadPose.tar.bz2', into=datadir)
- download_extract(baseurl + 'HOC.tar.bz2', into=datadir)
+ download_extract(baseurl, 'HOC.tar.bz2', into=datadir)
- download_extract(baseurl + 'HOCoffee.tar.bz2', into=datadir)
+ download_extract(baseurl, 'HOCoffee.tar.bz2', into=datadir)
- download_extract(baseurl + 'IHDPHeadPose.tar.bz2', into=datadir)
+ download_extract(baseurl, 'IHDPHeadPose.tar.bz2', into=datadir)
- download_extract(baseurl + 'QMULPoseHeads.tar.bz2', into=datadir)
+ download_extract(baseurl, 'QMULPoseHeads.tar.bz2', into=datadir)
+ print("Done.")
+
|
Update download URL and add more output to downloader.
|
## Code Before:
from lbtoolbox.download import download
import os
import inspect
import tarfile
def here(f):
me = inspect.getsourcefile(here)
return os.path.join(os.path.dirname(os.path.abspath(me)), f)
def download_extract(url, into):
fname = download(url, into)
print("Extracting...")
with tarfile.open(fname) as f:
f.extractall(path=into)
if __name__ == '__main__':
baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/tosato/'
datadir = here('data')
# First, download the Tosato datasets.
download_extract(baseurl + 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
download_extract(baseurl + 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
download_extract(baseurl + 'HIIT6HeadPose.tar.bz2', into=datadir)
download_extract(baseurl + 'HOC.tar.bz2', into=datadir)
download_extract(baseurl + 'HOCoffee.tar.bz2', into=datadir)
download_extract(baseurl + 'IHDPHeadPose.tar.bz2', into=datadir)
download_extract(baseurl + 'QMULPoseHeads.tar.bz2', into=datadir)
## Instruction:
Update download URL and add more output to downloader.
## Code After:
from lbtoolbox.download import download
import os
import inspect
import tarfile
def here(f):
me = inspect.getsourcefile(here)
return os.path.join(os.path.dirname(os.path.abspath(me)), f)
def download_extract(urlbase, name, into):
print("Downloading " + name)
fname = download(os.path.join(urlbase, name), into)
print("Extracting...")
with tarfile.open(fname) as f:
f.extractall(path=into)
if __name__ == '__main__':
baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/BiternionNets/'
datadir = here('data')
# First, download the Tosato datasets.
download_extract(baseurl, 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
download_extract(baseurl, 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
download_extract(baseurl, 'HIIT6HeadPose.tar.bz2', into=datadir)
download_extract(baseurl, 'HOC.tar.bz2', into=datadir)
download_extract(baseurl, 'HOCoffee.tar.bz2', into=datadir)
download_extract(baseurl, 'IHDPHeadPose.tar.bz2', into=datadir)
download_extract(baseurl, 'QMULPoseHeads.tar.bz2', into=datadir)
print("Done.")
|
...
def download_extract(urlbase, name, into):
print("Downloading " + name)
fname = download(os.path.join(urlbase, name), into)
print("Extracting...")
...
if __name__ == '__main__':
baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/BiternionNets/'
datadir = here('data')
...
# First, download the Tosato datasets.
download_extract(baseurl, 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
download_extract(baseurl, 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
download_extract(baseurl, 'HIIT6HeadPose.tar.bz2', into=datadir)
download_extract(baseurl, 'HOC.tar.bz2', into=datadir)
download_extract(baseurl, 'HOCoffee.tar.bz2', into=datadir)
download_extract(baseurl, 'IHDPHeadPose.tar.bz2', into=datadir)
download_extract(baseurl, 'QMULPoseHeads.tar.bz2', into=datadir)
print("Done.")
...
|
92031812b77479fe9a3dbd3ca512ba97e700384e
|
fusion_index/test/test_lookup.py
|
fusion_index/test/test_lookup.py
|
from axiom.store import Store
from hypothesis import given
from hypothesis.strategies import binary, lists, text, tuples, characters
from testtools import TestCase
from testtools.matchers import Equals
from fusion_index.lookup import LookupEntry
def axiom_text():
return text(
alphabet=characters(
blacklist_categories={'Cs'},
blacklist_characters={u'\x00'}),
average_size=5)
class LookupTests(TestCase):
@given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary())))
def test_inserts(self, values):
"""
Test inserting and retrieving arbitrary entries.
"""
s = Store()
def _tx():
d = {}
for e, t, k, v in values:
LookupEntry.set(s, e, t, k, v)
d[(e, t, k)] = v
self.assertThat(LookupEntry.get(s, e, t, k), Equals(v))
for (e, t, k), v in d.iteritems():
self.assertThat(LookupEntry.get(s, e, t, k), Equals(v))
s.transact(_tx)
|
import string
from axiom.store import Store
from hypothesis import given
from hypothesis.strategies import binary, characters, lists, text, tuples
from testtools import TestCase
from testtools.matchers import Equals
from fusion_index.lookup import LookupEntry
def axiom_text():
return text(
alphabet=characters(
blacklist_categories={'Cs'},
blacklist_characters={u'\x00'}),
average_size=5)
_lower_table = dict(
zip(map(ord, string.uppercase.decode('ascii')),
map(ord, string.lowercase.decode('ascii'))))
def _lower(s):
"""
Lowercase only ASCII characters, like SQLite NOCASE.
"""
return s.translate(_lower_table)
class LookupTests(TestCase):
@given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary())))
def test_inserts(self, values):
"""
Test inserting and retrieving arbitrary entries.
"""
s = Store()
def _tx():
d = {}
for e, t, k, v in values:
LookupEntry.set(s, e, t, k, v)
d[(_lower(e), _lower(t), _lower(k))] = v
self.assertThat(LookupEntry.get(s, e, t, k), Equals(v))
for (e, t, k), v in d.iteritems():
self.assertThat(LookupEntry.get(s, e, t, k), Equals(v))
s.transact(_tx)
|
Fix test model to be case-insensitive.
|
Fix test model to be case-insensitive.
|
Python
|
mit
|
fusionapp/fusion-index
|
+ import string
+
from axiom.store import Store
from hypothesis import given
- from hypothesis.strategies import binary, lists, text, tuples, characters
+ from hypothesis.strategies import binary, characters, lists, text, tuples
from testtools import TestCase
from testtools.matchers import Equals
from fusion_index.lookup import LookupEntry
def axiom_text():
return text(
alphabet=characters(
blacklist_categories={'Cs'},
blacklist_characters={u'\x00'}),
average_size=5)
+ _lower_table = dict(
+ zip(map(ord, string.uppercase.decode('ascii')),
+ map(ord, string.lowercase.decode('ascii'))))
+
+
+ def _lower(s):
+ """
+ Lowercase only ASCII characters, like SQLite NOCASE.
+ """
+ return s.translate(_lower_table)
+
+
class LookupTests(TestCase):
@given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary())))
def test_inserts(self, values):
"""
Test inserting and retrieving arbitrary entries.
"""
s = Store()
def _tx():
d = {}
for e, t, k, v in values:
LookupEntry.set(s, e, t, k, v)
- d[(e, t, k)] = v
+ d[(_lower(e), _lower(t), _lower(k))] = v
self.assertThat(LookupEntry.get(s, e, t, k), Equals(v))
for (e, t, k), v in d.iteritems():
self.assertThat(LookupEntry.get(s, e, t, k), Equals(v))
s.transact(_tx)
|
Fix test model to be case-insensitive.
|
## Code Before:
from axiom.store import Store
from hypothesis import given
from hypothesis.strategies import binary, lists, text, tuples, characters
from testtools import TestCase
from testtools.matchers import Equals
from fusion_index.lookup import LookupEntry
def axiom_text():
return text(
alphabet=characters(
blacklist_categories={'Cs'},
blacklist_characters={u'\x00'}),
average_size=5)
class LookupTests(TestCase):
@given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary())))
def test_inserts(self, values):
"""
Test inserting and retrieving arbitrary entries.
"""
s = Store()
def _tx():
d = {}
for e, t, k, v in values:
LookupEntry.set(s, e, t, k, v)
d[(e, t, k)] = v
self.assertThat(LookupEntry.get(s, e, t, k), Equals(v))
for (e, t, k), v in d.iteritems():
self.assertThat(LookupEntry.get(s, e, t, k), Equals(v))
s.transact(_tx)
## Instruction:
Fix test model to be case-insensitive.
## Code After:
import string
from axiom.store import Store
from hypothesis import given
from hypothesis.strategies import binary, characters, lists, text, tuples
from testtools import TestCase
from testtools.matchers import Equals
from fusion_index.lookup import LookupEntry
def axiom_text():
return text(
alphabet=characters(
blacklist_categories={'Cs'},
blacklist_characters={u'\x00'}),
average_size=5)
_lower_table = dict(
zip(map(ord, string.uppercase.decode('ascii')),
map(ord, string.lowercase.decode('ascii'))))
def _lower(s):
"""
Lowercase only ASCII characters, like SQLite NOCASE.
"""
return s.translate(_lower_table)
class LookupTests(TestCase):
@given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary())))
def test_inserts(self, values):
"""
Test inserting and retrieving arbitrary entries.
"""
s = Store()
def _tx():
d = {}
for e, t, k, v in values:
LookupEntry.set(s, e, t, k, v)
d[(_lower(e), _lower(t), _lower(k))] = v
self.assertThat(LookupEntry.get(s, e, t, k), Equals(v))
for (e, t, k), v in d.iteritems():
self.assertThat(LookupEntry.get(s, e, t, k), Equals(v))
s.transact(_tx)
|
# ... existing code ...
import string
from axiom.store import Store
# ... modified code ...
from hypothesis import given
from hypothesis.strategies import binary, characters, lists, text, tuples
from testtools import TestCase
...
_lower_table = dict(
zip(map(ord, string.uppercase.decode('ascii')),
map(ord, string.lowercase.decode('ascii'))))
def _lower(s):
"""
Lowercase only ASCII characters, like SQLite NOCASE.
"""
return s.translate(_lower_table)
class LookupTests(TestCase):
...
LookupEntry.set(s, e, t, k, v)
d[(_lower(e), _lower(t), _lower(k))] = v
self.assertThat(LookupEntry.get(s, e, t, k), Equals(v))
# ... rest of the code ...
|
6104b111b4ceaec894018b77cbea4a0de31400d4
|
chainer/trainer/extensions/_snapshot.py
|
chainer/trainer/extensions/_snapshot.py
|
from chainer.serializers import npz
from chainer.trainer import extension
def snapshot(savefun=npz.save_npz,
filename='snapshot_iter_{.updater.iteration}'):
"""Return a trainer extension to take snapshots of the trainer.
This extension serializes the trainer object and saves it to the output
directory. It is used to support resuming the training loop from the saved
state.
This extension is called once for each epoch by default.
.. note::
This extension first writes the serialized object to a temporary file
and then rename it to the target file name. Thus, if the program stops
right before the renaming, the temporary file might be left in the
output directory.
Args:
savefun: Function to save the trainer. It takes two arguments: the
output file path and the trainer object.
filename (str): Name of the file into which the trainer is serialized.
It can be a format string, where the trainer object is passed to
the :meth:`str.format` method.
"""
@extension.make_extension(trigger=(1, 'epoch'))
def ext(trainer):
fname = filename.format(trainer)
fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out)
try:
savefun(tmppath, trainer)
finally:
os.close(fd)
os.rename(tmppath, os.path.join(trainer.out, fname))
return ext
|
from chainer.serializers import npz
from chainer.trainer import extension
def snapshot(savefun=npz.save_npz,
filename='snapshot_iter_{.updater.iteration}'):
"""Return a trainer extension to take snapshots of the trainer.
This extension serializes the trainer object and saves it to the output
directory. It is used to support resuming the training loop from the saved
state.
This extension is called once for each epoch by default.
.. note::
This extension first writes the serialized object to a temporary file
and then rename it to the target file name. Thus, if the program stops
right before the renaming, the temporary file might be left in the
output directory.
Args:
savefun: Function to save the trainer. It takes two arguments: the
output file path and the trainer object.
filename (str): Name of the file into which the trainer is serialized.
It can be a format string, where the trainer object is passed to
the :meth:`str.format` method.
"""
@extension.make_extension(name='snapshot', trigger=(1, 'epoch'))
def ext(trainer):
fname = filename.format(trainer)
fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out)
try:
savefun(tmppath, trainer)
finally:
os.close(fd)
os.rename(tmppath, os.path.join(trainer.out, fname))
return ext
|
Add name to the snapshot extension
|
Add name to the snapshot extension
|
Python
|
mit
|
hvy/chainer,jnishi/chainer,ktnyt/chainer,chainer/chainer,cupy/cupy,hvy/chainer,ktnyt/chainer,cupy/cupy,wkentaro/chainer,ysekky/chainer,kikusu/chainer,pfnet/chainer,jnishi/chainer,okuta/chainer,keisuke-umezawa/chainer,ktnyt/chainer,okuta/chainer,niboshi/chainer,niboshi/chainer,cupy/cupy,rezoo/chainer,chainer/chainer,hvy/chainer,delta2323/chainer,chainer/chainer,aonotas/chainer,wkentaro/chainer,keisuke-umezawa/chainer,tkerola/chainer,niboshi/chainer,niboshi/chainer,kashif/chainer,chainer/chainer,jnishi/chainer,keisuke-umezawa/chainer,kikusu/chainer,cupy/cupy,keisuke-umezawa/chainer,anaruse/chainer,okuta/chainer,wkentaro/chainer,jnishi/chainer,wkentaro/chainer,ronekko/chainer,ktnyt/chainer,kiyukuta/chainer,hvy/chainer,okuta/chainer
|
from chainer.serializers import npz
from chainer.trainer import extension
def snapshot(savefun=npz.save_npz,
filename='snapshot_iter_{.updater.iteration}'):
"""Return a trainer extension to take snapshots of the trainer.
This extension serializes the trainer object and saves it to the output
directory. It is used to support resuming the training loop from the saved
state.
This extension is called once for each epoch by default.
.. note::
This extension first writes the serialized object to a temporary file
and then rename it to the target file name. Thus, if the program stops
right before the renaming, the temporary file might be left in the
output directory.
Args:
savefun: Function to save the trainer. It takes two arguments: the
output file path and the trainer object.
filename (str): Name of the file into which the trainer is serialized.
It can be a format string, where the trainer object is passed to
the :meth:`str.format` method.
"""
- @extension.make_extension(trigger=(1, 'epoch'))
+ @extension.make_extension(name='snapshot', trigger=(1, 'epoch'))
def ext(trainer):
fname = filename.format(trainer)
fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out)
try:
savefun(tmppath, trainer)
finally:
os.close(fd)
os.rename(tmppath, os.path.join(trainer.out, fname))
return ext
|
Add name to the snapshot extension
|
## Code Before:
from chainer.serializers import npz
from chainer.trainer import extension
def snapshot(savefun=npz.save_npz,
filename='snapshot_iter_{.updater.iteration}'):
"""Return a trainer extension to take snapshots of the trainer.
This extension serializes the trainer object and saves it to the output
directory. It is used to support resuming the training loop from the saved
state.
This extension is called once for each epoch by default.
.. note::
This extension first writes the serialized object to a temporary file
and then rename it to the target file name. Thus, if the program stops
right before the renaming, the temporary file might be left in the
output directory.
Args:
savefun: Function to save the trainer. It takes two arguments: the
output file path and the trainer object.
filename (str): Name of the file into which the trainer is serialized.
It can be a format string, where the trainer object is passed to
the :meth:`str.format` method.
"""
@extension.make_extension(trigger=(1, 'epoch'))
def ext(trainer):
fname = filename.format(trainer)
fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out)
try:
savefun(tmppath, trainer)
finally:
os.close(fd)
os.rename(tmppath, os.path.join(trainer.out, fname))
return ext
## Instruction:
Add name to the snapshot extension
## Code After:
from chainer.serializers import npz
from chainer.trainer import extension
def snapshot(savefun=npz.save_npz,
filename='snapshot_iter_{.updater.iteration}'):
"""Return a trainer extension to take snapshots of the trainer.
This extension serializes the trainer object and saves it to the output
directory. It is used to support resuming the training loop from the saved
state.
This extension is called once for each epoch by default.
.. note::
This extension first writes the serialized object to a temporary file
and then rename it to the target file name. Thus, if the program stops
right before the renaming, the temporary file might be left in the
output directory.
Args:
savefun: Function to save the trainer. It takes two arguments: the
output file path and the trainer object.
filename (str): Name of the file into which the trainer is serialized.
It can be a format string, where the trainer object is passed to
the :meth:`str.format` method.
"""
@extension.make_extension(name='snapshot', trigger=(1, 'epoch'))
def ext(trainer):
fname = filename.format(trainer)
fd, tmppath = tempfile.mkstemp(prefix=fname, dir=trainer.out)
try:
savefun(tmppath, trainer)
finally:
os.close(fd)
os.rename(tmppath, os.path.join(trainer.out, fname))
return ext
|
...
"""
@extension.make_extension(name='snapshot', trigger=(1, 'epoch'))
def ext(trainer):
...
|
661baf5e280f64824bf983b710c54efccb93a41a
|
oscar/apps/wishlists/forms.py
|
oscar/apps/wishlists/forms.py
|
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(WishListForm, self).__init__(*args, **kwargs)
self.instance.owner = user
class Meta:
model = WishList
fields = ('name', )
LineFormset = inlineformset_factory(WishList, Line, fields=('quantity', ),
extra=0, can_delete=False)
|
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(WishListForm, self).__init__(*args, **kwargs)
self.instance.owner = user
class Meta:
model = WishList
fields = ('name', )
class WishListLineForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(WishListLineForm, self).__init__(*args, **kwargs)
self.fields['quantity'].widget.attrs['size'] = 2
LineFormset = inlineformset_factory(
WishList, Line, fields=('quantity', ), form=WishListLineForm,
extra=0, can_delete=False)
|
Set size on wishlist line quantity form field
|
Set size on wishlist line quantity form field
This doesn't actually work since there is an overriding CSS style. When
issue #851 is resolved, this should start working.
|
Python
|
bsd-3-clause
|
sasha0/django-oscar,nickpack/django-oscar,elliotthill/django-oscar,DrOctogon/unwash_ecom,josesanch/django-oscar,bnprk/django-oscar,kapari/django-oscar,marcoantoniooliveira/labweb,solarissmoke/django-oscar,kapt/django-oscar,nickpack/django-oscar,machtfit/django-oscar,jlmadurga/django-oscar,marcoantoniooliveira/labweb,Bogh/django-oscar,adamend/django-oscar,machtfit/django-oscar,WillisXChen/django-oscar,QLGu/django-oscar,itbabu/django-oscar,Bogh/django-oscar,anentropic/django-oscar,amirrpp/django-oscar,makielab/django-oscar,jinnykoo/wuyisj.com,faratro/django-oscar,pasqualguerrero/django-oscar,jmt4/django-oscar,DrOctogon/unwash_ecom,monikasulik/django-oscar,vovanbo/django-oscar,amirrpp/django-oscar,QLGu/django-oscar,WillisXChen/django-oscar,Jannes123/django-oscar,thechampanurag/django-oscar,jinnykoo/wuyisj,michaelkuty/django-oscar,bschuon/django-oscar,sonofatailor/django-oscar,QLGu/django-oscar,sasha0/django-oscar,josesanch/django-oscar,spartonia/django-oscar,amirrpp/django-oscar,django-oscar/django-oscar,bnprk/django-oscar,WillisXChen/django-oscar,sonofatailor/django-oscar,ahmetdaglarbas/e-commerce,binarydud/django-oscar,nickpack/django-oscar,MatthewWilkes/django-oscar,WadeYuChen/django-oscar,itbabu/django-oscar,faratro/django-oscar,itbabu/django-oscar,monikasulik/django-oscar,manevant/django-oscar,ahmetdaglarbas/e-commerce,django-oscar/django-oscar,kapt/django-oscar,jinnykoo/wuyisj.com,Idematica/django-oscar,mexeniz/django-oscar,WadeYuChen/django-oscar,anentropic/django-oscar,dongguangming/django-oscar,thechampanurag/django-oscar,rocopartners/django-oscar,pdonadeo/django-oscar,jlmadurga/django-oscar,mexeniz/django-oscar,manevant/django-oscar,solarissmoke/django-oscar,jmt4/django-oscar,solarissmoke/django-oscar,binarydud/django-oscar,michaelkuty/django-oscar,machtfit/django-oscar,vovanbo/django-oscar,ahmetdaglarbas/e-commerce,dongguangming/django-oscar,nickpack/django-oscar,solarissmoke/django-oscar,taedori81/django-oscar,manevant/django-oscar,monikasulik/django-oscar,okfish/django-oscar,saadatqadri/django-oscar,anentropic/django-oscar,eddiep1101/django-oscar,pasqualguerrero/django-oscar,itbabu/django-oscar,lijoantony/django-oscar,pdonadeo/django-oscar,binarydud/django-oscar,faratro/django-oscar,marcoantoniooliveira/labweb,lijoantony/django-oscar,taedori81/django-oscar,michaelkuty/django-oscar,nfletton/django-oscar,makielab/django-oscar,elliotthill/django-oscar,okfish/django-oscar,jinnykoo/wuyisj,WillisXChen/django-oscar,mexeniz/django-oscar,jlmadurga/django-oscar,ademuk/django-oscar,john-parton/django-oscar,michaelkuty/django-oscar,taedori81/django-oscar,kapari/django-oscar,django-oscar/django-oscar,pdonadeo/django-oscar,okfish/django-oscar,MatthewWilkes/django-oscar,jmt4/django-oscar,Jannes123/django-oscar,okfish/django-oscar,sonofatailor/django-oscar,jinnykoo/wuyisj.com,saadatqadri/django-oscar,lijoantony/django-oscar,pdonadeo/django-oscar,adamend/django-oscar,jinnykoo/christmas,rocopartners/django-oscar,makielab/django-oscar,rocopartners/django-oscar,QLGu/django-oscar,thechampanurag/django-oscar,kapari/django-oscar,ka7eh/django-oscar,pasqualguerrero/django-oscar,eddiep1101/django-oscar,monikasulik/django-oscar,MatthewWilkes/django-oscar,Idematica/django-oscar,django-oscar/django-oscar,nfletton/django-oscar,pasqualguerrero/django-oscar,ka7eh/django-oscar,lijoantony/django-oscar,sonofatailor/django-oscar,thechampanurag/django-oscar,bschuon/django-oscar,Jannes123/django-oscar,mexeniz/django-oscar,binarydud/django-oscar,vovanbo/django-oscar,marcoantoniooliveira/labweb,jlmadurga/django-oscar,jinnykoo/wuyisj,bschuon/django-oscar,ademuk/django-oscar,saadatqadri/django-oscar,eddiep1101/django-oscar,ademuk/django-oscar,Jannes123/django-oscar,nfletton/django-oscar,faratro/django-oscar,ka7eh/django-oscar,DrOctogon/unwash_ecom,vovanbo/django-oscar,WillisXChen/django-oscar,Bogh/django-oscar,taedori81/django-oscar,jinnykoo/wuyisj.com,john-parton/django-oscar,amirrpp/django-oscar,elliotthill/django-oscar,ka7eh/django-oscar,nfletton/django-oscar,Idematica/django-oscar,john-parton/django-oscar,josesanch/django-oscar,jmt4/django-oscar,jinnykoo/christmas,jinnykoo/wuyisj,WadeYuChen/django-oscar,Bogh/django-oscar,adamend/django-oscar,kapari/django-oscar,spartonia/django-oscar,kapt/django-oscar,rocopartners/django-oscar,dongguangming/django-oscar,eddiep1101/django-oscar,adamend/django-oscar,jinnykoo/christmas,bnprk/django-oscar,bschuon/django-oscar,bnprk/django-oscar,john-parton/django-oscar,sasha0/django-oscar,sasha0/django-oscar,makielab/django-oscar,ahmetdaglarbas/e-commerce,WillisXChen/django-oscar,spartonia/django-oscar,WadeYuChen/django-oscar,ademuk/django-oscar,saadatqadri/django-oscar,anentropic/django-oscar,MatthewWilkes/django-oscar,dongguangming/django-oscar,manevant/django-oscar,spartonia/django-oscar
|
from django import forms
from django.db.models import get_model
- from django.forms.models import inlineformset_factory
+ from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(WishListForm, self).__init__(*args, **kwargs)
self.instance.owner = user
class Meta:
model = WishList
fields = ('name', )
+ class WishListLineForm(forms.ModelForm):
- LineFormset = inlineformset_factory(WishList, Line, fields=('quantity', ),
- extra=0, can_delete=False)
+ def __init__(self, *args, **kwargs):
+ super(WishListLineForm, self).__init__(*args, **kwargs)
+ self.fields['quantity'].widget.attrs['size'] = 2
+
+
+ LineFormset = inlineformset_factory(
+ WishList, Line, fields=('quantity', ), form=WishListLineForm,
+ extra=0, can_delete=False)
+
|
Set size on wishlist line quantity form field
|
## Code Before:
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(WishListForm, self).__init__(*args, **kwargs)
self.instance.owner = user
class Meta:
model = WishList
fields = ('name', )
LineFormset = inlineformset_factory(WishList, Line, fields=('quantity', ),
extra=0, can_delete=False)
## Instruction:
Set size on wishlist line quantity form field
## Code After:
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(WishListForm, self).__init__(*args, **kwargs)
self.instance.owner = user
class Meta:
model = WishList
fields = ('name', )
class WishListLineForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(WishListLineForm, self).__init__(*args, **kwargs)
self.fields['quantity'].widget.attrs['size'] = 2
LineFormset = inlineformset_factory(
WishList, Line, fields=('quantity', ), form=WishListLineForm,
extra=0, can_delete=False)
|
# ... existing code ...
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
# ... modified code ...
class WishListLineForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(WishListLineForm, self).__init__(*args, **kwargs)
self.fields['quantity'].widget.attrs['size'] = 2
LineFormset = inlineformset_factory(
WishList, Line, fields=('quantity', ), form=WishListLineForm,
extra=0, can_delete=False)
# ... rest of the code ...
|
fc50467212347502792a54397ae6f5477136a32f
|
pombola/south_africa/urls.py
|
pombola/south_africa/urls.py
|
from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, \
SAOrganisationDetailView, SAPersonDetail, SANewsletterPage
from pombola.core.urls import organisation_patterns, person_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
# Override the person url so we can add some extra data
for index, pattern in enumerate(person_patterns):
if pattern.name == 'person':
person_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAPersonDetail.as_view(), name='person')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
url(r'^info/newsletter', SANewsletterPage.as_view(), {'slug': 'newsletter'}, name='info_page_newsletter'),
)
|
from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, \
SAOrganisationDetailView, SAPersonDetail, SANewsletterPage
from pombola.core.urls import organisation_patterns, person_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
# Override the person url so we can add some extra data
for index, pattern in enumerate(person_patterns):
if pattern.name == 'person':
person_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAPersonDetail.as_view(), name='person')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
# Catch the newsletter info page to change the template used so that the signup form is injected.
# NOTE - you still need to create an InfoPage with the slug 'newsletter' for this not to 404.
url(r'^info/newsletter', SANewsletterPage.as_view(), {'slug': 'newsletter'}, name='info_page_newsletter'),
)
|
Add note about needing to create the infopage
|
Add note about needing to create the infopage
|
Python
|
agpl-3.0
|
hzj123/56th,ken-muturi/pombola,hzj123/56th,geoffkilpin/pombola,patricmutwiri/pombola,patricmutwiri/pombola,hzj123/56th,ken-muturi/pombola,patricmutwiri/pombola,ken-muturi/pombola,ken-muturi/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,ken-muturi/pombola,mysociety/pombola,hzj123/56th,patricmutwiri/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,ken-muturi/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola
|
from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, \
SAOrganisationDetailView, SAPersonDetail, SANewsletterPage
from pombola.core.urls import organisation_patterns, person_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
# Override the person url so we can add some extra data
for index, pattern in enumerate(person_patterns):
if pattern.name == 'person':
person_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAPersonDetail.as_view(), name='person')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
+
+ # Catch the newsletter info page to change the template used so that the signup form is injected.
+ # NOTE - you still need to create an InfoPage with the slug 'newsletter' for this not to 404.
url(r'^info/newsletter', SANewsletterPage.as_view(), {'slug': 'newsletter'}, name='info_page_newsletter'),
)
|
Add note about needing to create the infopage
|
## Code Before:
from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, \
SAOrganisationDetailView, SAPersonDetail, SANewsletterPage
from pombola.core.urls import organisation_patterns, person_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
# Override the person url so we can add some extra data
for index, pattern in enumerate(person_patterns):
if pattern.name == 'person':
person_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAPersonDetail.as_view(), name='person')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
url(r'^info/newsletter', SANewsletterPage.as_view(), {'slug': 'newsletter'}, name='info_page_newsletter'),
)
## Instruction:
Add note about needing to create the infopage
## Code After:
from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, \
SAOrganisationDetailView, SAPersonDetail, SANewsletterPage
from pombola.core.urls import organisation_patterns, person_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
# Override the person url so we can add some extra data
for index, pattern in enumerate(person_patterns):
if pattern.name == 'person':
person_patterns[index] = url(r'^(?P<slug>[-\w]+)/$', SAPersonDetail.as_view(), name='person')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
# Catch the newsletter info page to change the template used so that the signup form is injected.
# NOTE - you still need to create an InfoPage with the slug 'newsletter' for this not to 404.
url(r'^info/newsletter', SANewsletterPage.as_view(), {'slug': 'newsletter'}, name='info_page_newsletter'),
)
|
// ... existing code ...
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
# Catch the newsletter info page to change the template used so that the signup form is injected.
# NOTE - you still need to create an InfoPage with the slug 'newsletter' for this not to 404.
url(r'^info/newsletter', SANewsletterPage.as_view(), {'slug': 'newsletter'}, name='info_page_newsletter'),
// ... rest of the code ...
|
b8839302c0a4d8ada99a695f8829027fa433e05e
|
zerver/migrations/0232_make_archive_transaction_field_not_nullable.py
|
zerver/migrations/0232_make_archive_transaction_field_not_nullable.py
|
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('zerver', '0231_add_archive_transaction_model'),
]
operations = [
migrations.RunSQL("DELETE FROM zerver_archivedusermessage"),
migrations.RunSQL("DELETE FROM zerver_archivedreaction"),
migrations.RunSQL("DELETE FROM zerver_archivedsubmessage"),
migrations.RunSQL("DELETE FROM zerver_archivedattachment"),
migrations.RunSQL("DELETE FROM zerver_archivedattachment_messages"),
migrations.RunSQL("DELETE FROM zerver_archivedmessage"),
migrations.RunSQL("DELETE FROM zerver_archivetransaction"),
migrations.AlterField(
model_name='archivedmessage',
name='archive_transaction',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
),
]
|
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
"""
Tables cannot have data deleted from them and be altered in a single transaction,
but we need the DELETEs to be atomic together. So we set atomic=False for the migration
in general, and run the DELETEs in one transaction, and AlterField in another.
"""
atomic = False
dependencies = [
('zerver', '0231_add_archive_transaction_model'),
]
operations = [
migrations.RunSQL("""
BEGIN;
DELETE FROM zerver_archivedusermessage;
DELETE FROM zerver_archivedreaction;
DELETE FROM zerver_archivedsubmessage;
DELETE FROM zerver_archivedattachment_messages;
DELETE FROM zerver_archivedattachment;
DELETE FROM zerver_archivedmessage;
DELETE FROM zerver_archivetransaction;
COMMIT;
"""),
migrations.AlterField(
model_name='archivedmessage',
name='archive_transaction',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
),
]
|
Fix migration making archive_transaction field not null.
|
retention: Fix migration making archive_transaction field not null.
DELETing from archive tables and ALTERing ArchivedMessage needs to be
split into separate transactions.
zerver_archivedattachment_messages needs to be cleared out before
zerver_archivedattachment.
|
Python
|
apache-2.0
|
eeshangarg/zulip,shubhamdhama/zulip,zulip/zulip,brainwane/zulip,synicalsyntax/zulip,eeshangarg/zulip,andersk/zulip,hackerkid/zulip,hackerkid/zulip,timabbott/zulip,zulip/zulip,timabbott/zulip,synicalsyntax/zulip,tommyip/zulip,tommyip/zulip,rht/zulip,andersk/zulip,rishig/zulip,rht/zulip,timabbott/zulip,brainwane/zulip,eeshangarg/zulip,showell/zulip,rht/zulip,showell/zulip,andersk/zulip,tommyip/zulip,showell/zulip,showell/zulip,synicalsyntax/zulip,hackerkid/zulip,punchagan/zulip,shubhamdhama/zulip,rishig/zulip,brainwane/zulip,andersk/zulip,rht/zulip,brainwane/zulip,brainwane/zulip,shubhamdhama/zulip,eeshangarg/zulip,timabbott/zulip,rishig/zulip,punchagan/zulip,zulip/zulip,zulip/zulip,showell/zulip,kou/zulip,synicalsyntax/zulip,showell/zulip,timabbott/zulip,andersk/zulip,rishig/zulip,timabbott/zulip,kou/zulip,kou/zulip,brainwane/zulip,rishig/zulip,kou/zulip,eeshangarg/zulip,tommyip/zulip,showell/zulip,tommyip/zulip,shubhamdhama/zulip,punchagan/zulip,synicalsyntax/zulip,rishig/zulip,shubhamdhama/zulip,zulip/zulip,kou/zulip,shubhamdhama/zulip,eeshangarg/zulip,andersk/zulip,andersk/zulip,synicalsyntax/zulip,tommyip/zulip,shubhamdhama/zulip,kou/zulip,punchagan/zulip,rishig/zulip,tommyip/zulip,kou/zulip,hackerkid/zulip,punchagan/zulip,rht/zulip,hackerkid/zulip,rht/zulip,timabbott/zulip,punchagan/zulip,rht/zulip,synicalsyntax/zulip,brainwane/zulip,punchagan/zulip,hackerkid/zulip,hackerkid/zulip,eeshangarg/zulip,zulip/zulip,zulip/zulip
|
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
-
class Migration(migrations.Migration):
+ """
+ Tables cannot have data deleted from them and be altered in a single transaction,
+ but we need the DELETEs to be atomic together. So we set atomic=False for the migration
+ in general, and run the DELETEs in one transaction, and AlterField in another.
+ """
+ atomic = False
dependencies = [
('zerver', '0231_add_archive_transaction_model'),
]
operations = [
+ migrations.RunSQL("""
+ BEGIN;
- migrations.RunSQL("DELETE FROM zerver_archivedusermessage"),
+ DELETE FROM zerver_archivedusermessage;
- migrations.RunSQL("DELETE FROM zerver_archivedreaction"),
+ DELETE FROM zerver_archivedreaction;
- migrations.RunSQL("DELETE FROM zerver_archivedsubmessage"),
+ DELETE FROM zerver_archivedsubmessage;
- migrations.RunSQL("DELETE FROM zerver_archivedattachment"),
- migrations.RunSQL("DELETE FROM zerver_archivedattachment_messages"),
+ DELETE FROM zerver_archivedattachment_messages;
+ DELETE FROM zerver_archivedattachment;
- migrations.RunSQL("DELETE FROM zerver_archivedmessage"),
+ DELETE FROM zerver_archivedmessage;
- migrations.RunSQL("DELETE FROM zerver_archivetransaction"),
+ DELETE FROM zerver_archivetransaction;
+ COMMIT;
+ """),
migrations.AlterField(
model_name='archivedmessage',
name='archive_transaction',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
),
]
|
Fix migration making archive_transaction field not null.
|
## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('zerver', '0231_add_archive_transaction_model'),
]
operations = [
migrations.RunSQL("DELETE FROM zerver_archivedusermessage"),
migrations.RunSQL("DELETE FROM zerver_archivedreaction"),
migrations.RunSQL("DELETE FROM zerver_archivedsubmessage"),
migrations.RunSQL("DELETE FROM zerver_archivedattachment"),
migrations.RunSQL("DELETE FROM zerver_archivedattachment_messages"),
migrations.RunSQL("DELETE FROM zerver_archivedmessage"),
migrations.RunSQL("DELETE FROM zerver_archivetransaction"),
migrations.AlterField(
model_name='archivedmessage',
name='archive_transaction',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
),
]
## Instruction:
Fix migration making archive_transaction field not null.
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
"""
Tables cannot have data deleted from them and be altered in a single transaction,
but we need the DELETEs to be atomic together. So we set atomic=False for the migration
in general, and run the DELETEs in one transaction, and AlterField in another.
"""
atomic = False
dependencies = [
('zerver', '0231_add_archive_transaction_model'),
]
operations = [
migrations.RunSQL("""
BEGIN;
DELETE FROM zerver_archivedusermessage;
DELETE FROM zerver_archivedreaction;
DELETE FROM zerver_archivedsubmessage;
DELETE FROM zerver_archivedattachment_messages;
DELETE FROM zerver_archivedattachment;
DELETE FROM zerver_archivedmessage;
DELETE FROM zerver_archivetransaction;
COMMIT;
"""),
migrations.AlterField(
model_name='archivedmessage',
name='archive_transaction',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
),
]
|
# ... existing code ...
class Migration(migrations.Migration):
"""
Tables cannot have data deleted from them and be altered in a single transaction,
but we need the DELETEs to be atomic together. So we set atomic=False for the migration
in general, and run the DELETEs in one transaction, and AlterField in another.
"""
atomic = False
# ... modified code ...
operations = [
migrations.RunSQL("""
BEGIN;
DELETE FROM zerver_archivedusermessage;
DELETE FROM zerver_archivedreaction;
DELETE FROM zerver_archivedsubmessage;
DELETE FROM zerver_archivedattachment_messages;
DELETE FROM zerver_archivedattachment;
DELETE FROM zerver_archivedmessage;
DELETE FROM zerver_archivetransaction;
COMMIT;
"""),
migrations.AlterField(
# ... rest of the code ...
|
bd4e1c3f511ac1163e39d99fdc8e70f261023c44
|
setup/create_player_seasons.py
|
setup/create_player_seasons.py
|
import concurrent.futures
from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever
def create_player_seasons(simulation=False):
data_retriever = PlayerDataRetriever()
with session_scope() as session:
players = session.query(Player).all()[:25]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
future_tasks = {
threads.submit(
data_retriever.retrieve_player_seasons,
player.player_id, simulation
): player for player in players
}
for future in concurrent.futures.as_completed(future_tasks):
try:
plr_seasons = future.result()
print(len(plr_seasons))
except Exception as e:
print("Concurrent task generated an exception: %s" % e)
|
import concurrent.futures
from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever
def create_player_seasons(simulation=False):
data_retriever = PlayerDataRetriever()
with session_scope() as session:
players = session.query(Player).all()[:]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
future_tasks = {
threads.submit(
data_retriever.retrieve_player_seasons,
player.player_id, simulation
): player for player in players
}
for future in concurrent.futures.as_completed(future_tasks):
try:
plr_seasons = future.result()
except Exception as e:
print("Concurrent task generated an exception: %s" % e)
|
Update player season retrieval function
|
Update player season retrieval function
|
Python
|
mit
|
leaffan/pynhldb
|
import concurrent.futures
from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever
def create_player_seasons(simulation=False):
data_retriever = PlayerDataRetriever()
with session_scope() as session:
- players = session.query(Player).all()[:25]
+ players = session.query(Player).all()[:]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
future_tasks = {
threads.submit(
data_retriever.retrieve_player_seasons,
player.player_id, simulation
): player for player in players
}
for future in concurrent.futures.as_completed(future_tasks):
try:
plr_seasons = future.result()
- print(len(plr_seasons))
except Exception as e:
print("Concurrent task generated an exception: %s" % e)
|
Update player season retrieval function
|
## Code Before:
import concurrent.futures
from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever
def create_player_seasons(simulation=False):
data_retriever = PlayerDataRetriever()
with session_scope() as session:
players = session.query(Player).all()[:25]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
future_tasks = {
threads.submit(
data_retriever.retrieve_player_seasons,
player.player_id, simulation
): player for player in players
}
for future in concurrent.futures.as_completed(future_tasks):
try:
plr_seasons = future.result()
print(len(plr_seasons))
except Exception as e:
print("Concurrent task generated an exception: %s" % e)
## Instruction:
Update player season retrieval function
## Code After:
import concurrent.futures
from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever
def create_player_seasons(simulation=False):
data_retriever = PlayerDataRetriever()
with session_scope() as session:
players = session.query(Player).all()[:]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
future_tasks = {
threads.submit(
data_retriever.retrieve_player_seasons,
player.player_id, simulation
): player for player in players
}
for future in concurrent.futures.as_completed(future_tasks):
try:
plr_seasons = future.result()
except Exception as e:
print("Concurrent task generated an exception: %s" % e)
|
// ... existing code ...
players = session.query(Player).all()[:]
// ... modified code ...
plr_seasons = future.result()
except Exception as e:
// ... rest of the code ...
|
df4967b5e71e32f70e97d52a320d9b32d70095b7
|
main.py
|
main.py
|
import sys
from appscript import *
from termcolor import colored, cprint
def open(itunes):
return itunes.activate()
def close(itunes):
return itunes.quit()
def now_playing(itunes):
track = itunes.current_track.get()
return print('{} - {}\n{}'.format(colored(track.name(), attrs=['bold']),
track.artist(),
track.album()))
def play(itunes):
itunes.play()
return now_playing(itunes)
def stop(itunes):
return itunes.stop()
def main():
cmd, is_open, itunes = None if len(sys.argv) == 1 else sys.argv[1], \
app('System Events').processes[its.name == 'iTunes'].count(), \
app('iTunes')
if not is_open == 1:
open(itunes)
cmds = {
'np': now_playing,
'play': play,
'show': open,
'stop': stop,
'close': close
}
cmd = cmds[cmd] if cmd in cmds else now_playing
return cmd(itunes)
if __name__ == '__main__':
main()
|
import sys
from appscript import *
from termcolor import colored, cprint
def open(itunes):
return itunes.activate()
def close(itunes):
return itunes.quit()
def is_playing(itunes):
return itunes.player_state.get() == k.playing
def now_playing(itunes):
if not is_playing(itunes):
return play(itunes)
track = itunes.current_track.get()
return print('{} - {}\n{}'.format(colored(track.name(), attrs=['bold']),
track.artist(),
track.album()))
def play(itunes):
if is_playing(itunes):
return play_next(itunes)
itunes.play()
return now_playing(itunes)
def stop(itunes):
return itunes.stop()
def main():
cmd, is_open, itunes = None if len(sys.argv) == 1 else sys.argv[1], \
app('System Events').processes[its.name == 'iTunes'].count(), \
app('iTunes')
if not is_open == 1:
open(itunes)
cmds = {
'np': now_playing,
'play': play,
'show': open,
'stop': stop,
'close': close
}
cmd = cmds[cmd] if cmd in cmds else now_playing
return cmd(itunes)
if __name__ == '__main__':
main()
|
Check if song is_playing before play
|
Check if song is_playing before play
|
Python
|
mit
|
kshvmdn/nowplaying
|
import sys
from appscript import *
from termcolor import colored, cprint
def open(itunes):
return itunes.activate()
def close(itunes):
return itunes.quit()
+ def is_playing(itunes):
+ return itunes.player_state.get() == k.playing
+
+
def now_playing(itunes):
+ if not is_playing(itunes):
+ return play(itunes)
track = itunes.current_track.get()
return print('{} - {}\n{}'.format(colored(track.name(), attrs=['bold']),
track.artist(),
track.album()))
def play(itunes):
+ if is_playing(itunes):
+ return play_next(itunes)
itunes.play()
return now_playing(itunes)
def stop(itunes):
return itunes.stop()
def main():
cmd, is_open, itunes = None if len(sys.argv) == 1 else sys.argv[1], \
app('System Events').processes[its.name == 'iTunes'].count(), \
app('iTunes')
if not is_open == 1:
open(itunes)
cmds = {
'np': now_playing,
'play': play,
'show': open,
'stop': stop,
'close': close
}
cmd = cmds[cmd] if cmd in cmds else now_playing
return cmd(itunes)
if __name__ == '__main__':
main()
|
Check if song is_playing before play
|
## Code Before:
import sys
from appscript import *
from termcolor import colored, cprint
def open(itunes):
return itunes.activate()
def close(itunes):
return itunes.quit()
def now_playing(itunes):
track = itunes.current_track.get()
return print('{} - {}\n{}'.format(colored(track.name(), attrs=['bold']),
track.artist(),
track.album()))
def play(itunes):
itunes.play()
return now_playing(itunes)
def stop(itunes):
return itunes.stop()
def main():
cmd, is_open, itunes = None if len(sys.argv) == 1 else sys.argv[1], \
app('System Events').processes[its.name == 'iTunes'].count(), \
app('iTunes')
if not is_open == 1:
open(itunes)
cmds = {
'np': now_playing,
'play': play,
'show': open,
'stop': stop,
'close': close
}
cmd = cmds[cmd] if cmd in cmds else now_playing
return cmd(itunes)
if __name__ == '__main__':
main()
## Instruction:
Check if song is_playing before play
## Code After:
import sys
from appscript import *
from termcolor import colored, cprint
def open(itunes):
return itunes.activate()
def close(itunes):
return itunes.quit()
def is_playing(itunes):
return itunes.player_state.get() == k.playing
def now_playing(itunes):
if not is_playing(itunes):
return play(itunes)
track = itunes.current_track.get()
return print('{} - {}\n{}'.format(colored(track.name(), attrs=['bold']),
track.artist(),
track.album()))
def play(itunes):
if is_playing(itunes):
return play_next(itunes)
itunes.play()
return now_playing(itunes)
def stop(itunes):
return itunes.stop()
def main():
cmd, is_open, itunes = None if len(sys.argv) == 1 else sys.argv[1], \
app('System Events').processes[its.name == 'iTunes'].count(), \
app('iTunes')
if not is_open == 1:
open(itunes)
cmds = {
'np': now_playing,
'play': play,
'show': open,
'stop': stop,
'close': close
}
cmd = cmds[cmd] if cmd in cmds else now_playing
return cmd(itunes)
if __name__ == '__main__':
main()
|
// ... existing code ...
def is_playing(itunes):
return itunes.player_state.get() == k.playing
def now_playing(itunes):
if not is_playing(itunes):
return play(itunes)
track = itunes.current_track.get()
// ... modified code ...
def play(itunes):
if is_playing(itunes):
return play_next(itunes)
itunes.play()
// ... rest of the code ...
|
b9d1dcf614faa949975bc5296be451abd2594835
|
repository/presenter.py
|
repository/presenter.py
|
import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n if argv.top_n > 0 else None
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
|
import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n
if top_n < 0 or top_n > len(counter):
top_n = len(counter)
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
|
Fix small issue with `--top-n` command switch
|
Fix small issue with `--top-n` command switch
|
Python
|
mit
|
moacirosa/git-current-contributors,moacirosa/git-current-contributors
|
import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
- top_n = argv.top_n if argv.top_n > 0 else None
+ top_n = argv.top_n
+
+ if top_n < 0 or top_n > len(counter):
+ top_n = len(counter)
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
|
Fix small issue with `--top-n` command switch
|
## Code Before:
import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n if argv.top_n > 0 else None
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
## Instruction:
Fix small issue with `--top-n` command switch
## Code After:
import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n
if top_n < 0 or top_n > len(counter):
top_n = len(counter)
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
|
// ... existing code ...
top_n = argv.top_n
if top_n < 0 or top_n > len(counter):
top_n = len(counter)
// ... rest of the code ...
|
1c9f3b95cca8439ec8c4a5a5cb1959e8b2edaff2
|
osmaxx-py/excerptconverter/converter_helper.py
|
osmaxx-py/excerptconverter/converter_helper.py
|
from django.contrib import messages
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
import stored_messages
from osmaxx.excerptexport import models
class ConverterHelper:
def __init__(self, extraction_order):
self.extraction_order = extraction_order
self.user = extraction_order.orderer
def file_conversion_finished(self):
if self.extraction_order.output_files.count() >= len(self.extraction_order.extraction_formats):
self.inform_user(
messages.SUCCESS,
_('The extraction of the order "%(order_id)s" has been finished.') % {
'order_id': self.extraction_order.id
},
email=True
)
self.extraction_order.state = models.ExtractionOrderState.FINISHED
self.extraction_order.save()
def inform_user(self, message_type, message_text, email=True):
stored_messages.api.add_message_for(
users=[self.user],
level=message_type,
message_text=message_text
)
if email:
if hasattr(self.user, 'email'):
send_mail(
'[OSMAXX] '+message_text,
message_text,
'[email protected]',
[self.user.email]
)
else:
self.inform_user(
messages.WARNING,
_("There is no email address assigned to your account. "
"You won't be notified by email on process finish!"),
email=False
)
|
from django.contrib import messages
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
import stored_messages
from osmaxx.excerptexport import models
# functions using database (extraction_order) must be instance methods of a class
# -> free functions will not work: database connection error
class ConverterHelper:
def __init__(self, extraction_order):
self.extraction_order = extraction_order
self.user = extraction_order.orderer
def file_conversion_finished(self):
if self.extraction_order.output_files.count() >= len(self.extraction_order.extraction_formats):
self.inform_user(
messages.SUCCESS,
_('The extraction of the order "%(order_id)s" has been finished.') % {
'order_id': self.extraction_order.id
},
email=True
)
self.extraction_order.state = models.ExtractionOrderState.FINISHED
self.extraction_order.save()
def inform_user(self, message_type, message_text, email=True):
stored_messages.api.add_message_for(
users=[self.user],
level=message_type,
message_text=message_text
)
if email:
if hasattr(self.user, 'email'):
send_mail(
'[OSMAXX] '+message_text,
message_text,
'[email protected]',
[self.user.email]
)
else:
self.inform_user(
messages.WARNING,
_("There is no email address assigned to your account. "
"You won't be notified by email on process finish!"),
email=False
)
|
Document reason for class instead of free function
|
Document reason for class instead of free function
|
Python
|
isc
|
geometalab/drf-utm-zone-info,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx
|
from django.contrib import messages
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
import stored_messages
from osmaxx.excerptexport import models
+ # functions using database (extraction_order) must be instance methods of a class
+ # -> free functions will not work: database connection error
class ConverterHelper:
def __init__(self, extraction_order):
self.extraction_order = extraction_order
self.user = extraction_order.orderer
def file_conversion_finished(self):
if self.extraction_order.output_files.count() >= len(self.extraction_order.extraction_formats):
self.inform_user(
messages.SUCCESS,
_('The extraction of the order "%(order_id)s" has been finished.') % {
'order_id': self.extraction_order.id
},
email=True
)
self.extraction_order.state = models.ExtractionOrderState.FINISHED
self.extraction_order.save()
def inform_user(self, message_type, message_text, email=True):
stored_messages.api.add_message_for(
users=[self.user],
level=message_type,
message_text=message_text
)
if email:
if hasattr(self.user, 'email'):
send_mail(
'[OSMAXX] '+message_text,
message_text,
'[email protected]',
[self.user.email]
)
else:
self.inform_user(
messages.WARNING,
_("There is no email address assigned to your account. "
"You won't be notified by email on process finish!"),
email=False
)
|
Document reason for class instead of free function
|
## Code Before:
from django.contrib import messages
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
import stored_messages
from osmaxx.excerptexport import models
class ConverterHelper:
def __init__(self, extraction_order):
self.extraction_order = extraction_order
self.user = extraction_order.orderer
def file_conversion_finished(self):
if self.extraction_order.output_files.count() >= len(self.extraction_order.extraction_formats):
self.inform_user(
messages.SUCCESS,
_('The extraction of the order "%(order_id)s" has been finished.') % {
'order_id': self.extraction_order.id
},
email=True
)
self.extraction_order.state = models.ExtractionOrderState.FINISHED
self.extraction_order.save()
def inform_user(self, message_type, message_text, email=True):
stored_messages.api.add_message_for(
users=[self.user],
level=message_type,
message_text=message_text
)
if email:
if hasattr(self.user, 'email'):
send_mail(
'[OSMAXX] '+message_text,
message_text,
'[email protected]',
[self.user.email]
)
else:
self.inform_user(
messages.WARNING,
_("There is no email address assigned to your account. "
"You won't be notified by email on process finish!"),
email=False
)
## Instruction:
Document reason for class instead of free function
## Code After:
from django.contrib import messages
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
import stored_messages
from osmaxx.excerptexport import models
# functions using database (extraction_order) must be instance methods of a class
# -> free functions will not work: database connection error
class ConverterHelper:
def __init__(self, extraction_order):
self.extraction_order = extraction_order
self.user = extraction_order.orderer
def file_conversion_finished(self):
if self.extraction_order.output_files.count() >= len(self.extraction_order.extraction_formats):
self.inform_user(
messages.SUCCESS,
_('The extraction of the order "%(order_id)s" has been finished.') % {
'order_id': self.extraction_order.id
},
email=True
)
self.extraction_order.state = models.ExtractionOrderState.FINISHED
self.extraction_order.save()
def inform_user(self, message_type, message_text, email=True):
stored_messages.api.add_message_for(
users=[self.user],
level=message_type,
message_text=message_text
)
if email:
if hasattr(self.user, 'email'):
send_mail(
'[OSMAXX] '+message_text,
message_text,
'[email protected]',
[self.user.email]
)
else:
self.inform_user(
messages.WARNING,
_("There is no email address assigned to your account. "
"You won't be notified by email on process finish!"),
email=False
)
|
# ... existing code ...
# functions using database (extraction_order) must be instance methods of a class
# -> free functions will not work: database connection error
class ConverterHelper:
# ... rest of the code ...
|
fee78440de784bee91669e6c4f1d2c301202e29d
|
apps/blogs/serializers.py
|
apps/blogs/serializers.py
|
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField
from django.contrib.auth.models import User
from fluent_contents.rendering import render_placeholder
from rest_framework import serializers
from .models import BlogPost
class BlogPostContentsField(serializers.Field):
def to_native(self, obj):
request = self.context.get('request', None)
contents_html = render_placeholder(request, obj)
return contents_html
class BlogPostAuthorSerializer(serializers.ModelSerializer):
picture = SorlImageField('userprofile.picture', '90x90', crop='center')
class Meta:
model = User
fields = ('first_name', 'last_name', 'picture')
class BlogPostDetailSerializer(serializers.ModelSerializer):
contents = BlogPostContentsField('contents')
author = BlogPostAuthorSerializer()
url = SlugHyperlinkedIdentityField(view_name='blogpost-instance')
class Meta:
model = BlogPost
exclude = ('id',)
class BlogPostPreviewSerializer(BlogPostDetailSerializer):
class Meta:
model = BlogPost
exclude = ('id',)
|
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField
from django.contrib.auth.models import User
from fluent_contents.rendering import render_placeholder
from rest_framework import serializers
from .models import BlogPost
class BlogPostContentsField(serializers.Field):
def to_native(self, obj):
request = self.context.get('request', None)
contents_html = render_placeholder(request, obj)
return contents_html
class BlogPostAuthorSerializer(serializers.ModelSerializer):
picture = SorlImageField('userprofile.picture', '90x90', crop='center')
class Meta:
model = User
fields = ('first_name', 'last_name', 'picture')
class BlogPostDetailSerializer(serializers.ModelSerializer):
contents = BlogPostContentsField(source='contents')
author = BlogPostAuthorSerializer()
url = SlugHyperlinkedIdentityField(view_name='blogpost-instance')
main_image = SorlImageField('main_image', '300x200', crop='center')
class Meta:
model = BlogPost
exclude = ('id',)
class BlogPostPreviewSerializer(BlogPostDetailSerializer):
class Meta:
model = BlogPost
exclude = ('id',)
|
Add main_image to BlogPost API response.
|
Add main_image to BlogPost API response.
|
Python
|
bsd-3-clause
|
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
|
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField
from django.contrib.auth.models import User
from fluent_contents.rendering import render_placeholder
from rest_framework import serializers
from .models import BlogPost
class BlogPostContentsField(serializers.Field):
def to_native(self, obj):
request = self.context.get('request', None)
contents_html = render_placeholder(request, obj)
return contents_html
class BlogPostAuthorSerializer(serializers.ModelSerializer):
picture = SorlImageField('userprofile.picture', '90x90', crop='center')
class Meta:
model = User
fields = ('first_name', 'last_name', 'picture')
class BlogPostDetailSerializer(serializers.ModelSerializer):
- contents = BlogPostContentsField('contents')
+ contents = BlogPostContentsField(source='contents')
author = BlogPostAuthorSerializer()
url = SlugHyperlinkedIdentityField(view_name='blogpost-instance')
+ main_image = SorlImageField('main_image', '300x200', crop='center')
class Meta:
model = BlogPost
exclude = ('id',)
class BlogPostPreviewSerializer(BlogPostDetailSerializer):
class Meta:
model = BlogPost
exclude = ('id',)
|
Add main_image to BlogPost API response.
|
## Code Before:
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField
from django.contrib.auth.models import User
from fluent_contents.rendering import render_placeholder
from rest_framework import serializers
from .models import BlogPost
class BlogPostContentsField(serializers.Field):
def to_native(self, obj):
request = self.context.get('request', None)
contents_html = render_placeholder(request, obj)
return contents_html
class BlogPostAuthorSerializer(serializers.ModelSerializer):
picture = SorlImageField('userprofile.picture', '90x90', crop='center')
class Meta:
model = User
fields = ('first_name', 'last_name', 'picture')
class BlogPostDetailSerializer(serializers.ModelSerializer):
contents = BlogPostContentsField('contents')
author = BlogPostAuthorSerializer()
url = SlugHyperlinkedIdentityField(view_name='blogpost-instance')
class Meta:
model = BlogPost
exclude = ('id',)
class BlogPostPreviewSerializer(BlogPostDetailSerializer):
class Meta:
model = BlogPost
exclude = ('id',)
## Instruction:
Add main_image to BlogPost API response.
## Code After:
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField
from django.contrib.auth.models import User
from fluent_contents.rendering import render_placeholder
from rest_framework import serializers
from .models import BlogPost
class BlogPostContentsField(serializers.Field):
def to_native(self, obj):
request = self.context.get('request', None)
contents_html = render_placeholder(request, obj)
return contents_html
class BlogPostAuthorSerializer(serializers.ModelSerializer):
picture = SorlImageField('userprofile.picture', '90x90', crop='center')
class Meta:
model = User
fields = ('first_name', 'last_name', 'picture')
class BlogPostDetailSerializer(serializers.ModelSerializer):
contents = BlogPostContentsField(source='contents')
author = BlogPostAuthorSerializer()
url = SlugHyperlinkedIdentityField(view_name='blogpost-instance')
main_image = SorlImageField('main_image', '300x200', crop='center')
class Meta:
model = BlogPost
exclude = ('id',)
class BlogPostPreviewSerializer(BlogPostDetailSerializer):
class Meta:
model = BlogPost
exclude = ('id',)
|
# ... existing code ...
class BlogPostDetailSerializer(serializers.ModelSerializer):
contents = BlogPostContentsField(source='contents')
author = BlogPostAuthorSerializer()
# ... modified code ...
url = SlugHyperlinkedIdentityField(view_name='blogpost-instance')
main_image = SorlImageField('main_image', '300x200', crop='center')
# ... rest of the code ...
|
06d9171b2244e4dd9d5e1883101d7ec3e05be4b2
|
bitfield/apps.py
|
bitfield/apps.py
|
from django.apps import AppConfig
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
|
import django
from django.apps import AppConfig
django.setup()
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
|
Add django.setup to the AppConfig
|
Add django.setup to the AppConfig
|
Python
|
apache-2.0
|
Elec/django-bitfield,disqus/django-bitfield,joshowen/django-bitfield
|
+ import django
from django.apps import AppConfig
+
+
+ django.setup()
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
|
Add django.setup to the AppConfig
|
## Code Before:
from django.apps import AppConfig
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
## Instruction:
Add django.setup to the AppConfig
## Code After:
import django
from django.apps import AppConfig
django.setup()
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
|
// ... existing code ...
import django
from django.apps import AppConfig
django.setup()
// ... rest of the code ...
|
0177066012b3373753cba8baf86f00a365d7147b
|
findaconf/tests/config.py
|
findaconf/tests/config.py
|
from decouple import config
from findaconf.tests.fake_data import fake_conference, seed
def set_app(app, db=False):
unset_app(db)
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
if db:
app.config['SQLALCHEMY_DATABASE_URI'] = config(
'DATABASE_URL_TEST',
default='sqlite:///' + app.config['BASEDIR'].child('findaconf',
'tests',
'tests.db')
)
test_app = app.test_client()
if db:
db.create_all()
seed(app, db)
[db.session.add(fake_conference(db)) for i in range(1, 43)]
db.session.commit()
return test_app
def unset_app(db=False):
if db:
db.session.remove()
db.drop_all()
|
from decouple import config
from findaconf.tests.fake_data import fake_conference, seed
def set_app(app, db=False):
# set test vars
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
# set test db
if db:
app.config['SQLALCHEMY_DATABASE_URI'] = config(
'DATABASE_URL_TEST',
default='sqlite:///' + app.config['BASEDIR'].child('findaconf',
'tests',
'tests.db')
)
# create test app
test_app = app.test_client()
# create and feed db tables
if db:
# start from a clean db
db.session.remove()
db.drop_all()
# create tables and feed them
db.create_all()
seed(app, db)
[db.session.add(fake_conference(db)) for i in range(1, 43)]
db.session.commit()
# return test app
return test_app
def unset_app(db=False):
if db:
db.session.remove()
db.drop_all()
|
Fix bug that used dev db instead of test db
|
Fix bug that used dev db instead of test db
|
Python
|
mit
|
cuducos/findaconf,koorukuroo/findaconf,cuducos/findaconf,koorukuroo/findaconf,koorukuroo/findaconf,cuducos/findaconf
|
from decouple import config
from findaconf.tests.fake_data import fake_conference, seed
def set_app(app, db=False):
- unset_app(db)
+
+ # set test vars
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
+
+ # set test db
if db:
app.config['SQLALCHEMY_DATABASE_URI'] = config(
'DATABASE_URL_TEST',
default='sqlite:///' + app.config['BASEDIR'].child('findaconf',
'tests',
'tests.db')
)
+
+ # create test app
test_app = app.test_client()
+
+ # create and feed db tables
if db:
+
+ # start from a clean db
+ db.session.remove()
+ db.drop_all()
+
+ # create tables and feed them
db.create_all()
seed(app, db)
[db.session.add(fake_conference(db)) for i in range(1, 43)]
db.session.commit()
+
+ # return test app
return test_app
def unset_app(db=False):
if db:
db.session.remove()
db.drop_all()
|
Fix bug that used dev db instead of test db
|
## Code Before:
from decouple import config
from findaconf.tests.fake_data import fake_conference, seed
def set_app(app, db=False):
unset_app(db)
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
if db:
app.config['SQLALCHEMY_DATABASE_URI'] = config(
'DATABASE_URL_TEST',
default='sqlite:///' + app.config['BASEDIR'].child('findaconf',
'tests',
'tests.db')
)
test_app = app.test_client()
if db:
db.create_all()
seed(app, db)
[db.session.add(fake_conference(db)) for i in range(1, 43)]
db.session.commit()
return test_app
def unset_app(db=False):
if db:
db.session.remove()
db.drop_all()
## Instruction:
Fix bug that used dev db instead of test db
## Code After:
from decouple import config
from findaconf.tests.fake_data import fake_conference, seed
def set_app(app, db=False):
# set test vars
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
# set test db
if db:
app.config['SQLALCHEMY_DATABASE_URI'] = config(
'DATABASE_URL_TEST',
default='sqlite:///' + app.config['BASEDIR'].child('findaconf',
'tests',
'tests.db')
)
# create test app
test_app = app.test_client()
# create and feed db tables
if db:
# start from a clean db
db.session.remove()
db.drop_all()
# create tables and feed them
db.create_all()
seed(app, db)
[db.session.add(fake_conference(db)) for i in range(1, 43)]
db.session.commit()
# return test app
return test_app
def unset_app(db=False):
if db:
db.session.remove()
db.drop_all()
|
# ... existing code ...
def set_app(app, db=False):
# set test vars
app.config['TESTING'] = True
# ... modified code ...
app.config['WTF_CSRF_ENABLED'] = False
# set test db
if db:
...
)
# create test app
test_app = app.test_client()
# create and feed db tables
if db:
# start from a clean db
db.session.remove()
db.drop_all()
# create tables and feed them
db.create_all()
...
db.session.commit()
# return test app
return test_app
# ... rest of the code ...
|
1d4ac6431e91b04a5a11bd7add78c512e3fe68d8
|
aiodocker/jsonstream.py
|
aiodocker/jsonstream.py
|
import asyncio
import json
import logging
import aiohttp.errors
log = logging.getLogger(__name__)
class JsonStreamResult:
def __init__(self, response, transform=None):
self.response = response
self.transform = transform or (lambda x: x)
async def fetch(self):
while True:
try:
data = await self.response.content.readline()
if not data:
break
except (aiohttp.errors.ClientDisconnectedError,
aiohttp.errors.ServerDisconnectedError):
break
yield self.transform(json.loads(data.decode('utf8')))
async def close(self):
await self.response.release()
async def json_stream_result(response, transform=None, stream=True):
json_stream = JsonStreamResult(response, transform)
if stream:
return json_stream
data = []
async for obj in json_stream.fetch():
data.append(obj)
return data
|
import asyncio
import json
import logging
import aiohttp.errors
log = logging.getLogger(__name__)
class JsonStreamResult:
def __init__(self, response, transform=None):
self.response = response
self.transform = transform or (lambda x: x)
async def fetch(self):
while True:
try:
data = await self.response.content.readline()
if not data:
break
except (aiohttp.errors.ClientDisconnectedError,
aiohttp.errors.ServerDisconnectedError):
break
yield self.transform(json.loads(data.decode('utf8')))
async def close(self):
# response.release() indefinitely hangs because the server is sending
# an infinite stream of messages.
# (see https://github.com/KeepSafe/aiohttp/issues/739)
await self.response.close()
async def json_stream_result(response, transform=None, stream=True):
json_stream = JsonStreamResult(response, transform)
if stream:
return json_stream
data = []
async for obj in json_stream.fetch():
data.append(obj)
return data
|
Fix indefinite hangs when closing streaming results.
|
Fix indefinite hangs when closing streaming results.
* See https://github.com/KeepSafe/aiohttp/issues/739
|
Python
|
mit
|
paultag/aiodocker,gaopeiliang/aiodocker,barrachri/aiodocker,gaopeiliang/aiodocker,barrachri/aiodocker,gaopeiliang/aiodocker,barrachri/aiodocker
|
import asyncio
import json
import logging
import aiohttp.errors
log = logging.getLogger(__name__)
class JsonStreamResult:
def __init__(self, response, transform=None):
self.response = response
self.transform = transform or (lambda x: x)
async def fetch(self):
while True:
try:
data = await self.response.content.readline()
if not data:
break
except (aiohttp.errors.ClientDisconnectedError,
aiohttp.errors.ServerDisconnectedError):
break
yield self.transform(json.loads(data.decode('utf8')))
async def close(self):
+ # response.release() indefinitely hangs because the server is sending
+ # an infinite stream of messages.
+ # (see https://github.com/KeepSafe/aiohttp/issues/739)
- await self.response.release()
+ await self.response.close()
async def json_stream_result(response, transform=None, stream=True):
json_stream = JsonStreamResult(response, transform)
if stream:
return json_stream
data = []
async for obj in json_stream.fetch():
data.append(obj)
return data
|
Fix indefinite hangs when closing streaming results.
|
## Code Before:
import asyncio
import json
import logging
import aiohttp.errors
log = logging.getLogger(__name__)
class JsonStreamResult:
def __init__(self, response, transform=None):
self.response = response
self.transform = transform or (lambda x: x)
async def fetch(self):
while True:
try:
data = await self.response.content.readline()
if not data:
break
except (aiohttp.errors.ClientDisconnectedError,
aiohttp.errors.ServerDisconnectedError):
break
yield self.transform(json.loads(data.decode('utf8')))
async def close(self):
await self.response.release()
async def json_stream_result(response, transform=None, stream=True):
json_stream = JsonStreamResult(response, transform)
if stream:
return json_stream
data = []
async for obj in json_stream.fetch():
data.append(obj)
return data
## Instruction:
Fix indefinite hangs when closing streaming results.
## Code After:
import asyncio
import json
import logging
import aiohttp.errors
log = logging.getLogger(__name__)
class JsonStreamResult:
def __init__(self, response, transform=None):
self.response = response
self.transform = transform or (lambda x: x)
async def fetch(self):
while True:
try:
data = await self.response.content.readline()
if not data:
break
except (aiohttp.errors.ClientDisconnectedError,
aiohttp.errors.ServerDisconnectedError):
break
yield self.transform(json.loads(data.decode('utf8')))
async def close(self):
# response.release() indefinitely hangs because the server is sending
# an infinite stream of messages.
# (see https://github.com/KeepSafe/aiohttp/issues/739)
await self.response.close()
async def json_stream_result(response, transform=None, stream=True):
json_stream = JsonStreamResult(response, transform)
if stream:
return json_stream
data = []
async for obj in json_stream.fetch():
data.append(obj)
return data
|
# ... existing code ...
async def close(self):
# response.release() indefinitely hangs because the server is sending
# an infinite stream of messages.
# (see https://github.com/KeepSafe/aiohttp/issues/739)
await self.response.close()
# ... rest of the code ...
|
9fb8b0a72740ba155c76a5812706612b656980f4
|
openprocurement/auctions/flash/constants.py
|
openprocurement/auctions/flash/constants.py
|
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
"openprocurement.auctions.core.plugins",
]
|
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
]
|
Add view_locations for plugins in core
|
Add view_locations for plugins in core
|
Python
|
apache-2.0
|
openprocurement/openprocurement.auctions.flash
|
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
- "openprocurement.auctions.core.plugins",
]
|
Add view_locations for plugins in core
|
## Code Before:
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
"openprocurement.auctions.core.plugins",
]
## Instruction:
Add view_locations for plugins in core
## Code After:
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
]
|
# ... existing code ...
"openprocurement.auctions.flash.views",
]
# ... rest of the code ...
|
424980a48e451d1b99397843001bd75fa58e474e
|
tests/test_fullqualname.py
|
tests/test_fullqualname.py
|
"""Tests for fullqualname."""
import nose
import sys
from fullqualname import fullqualname
def test_builtin_function():
# Test built-in function object.
obj = len
# Type is 'builtin_function_or_method'.
assert type(obj).__name__ == 'builtin_function_or_method'
# Object is a function.
assert 'built-in function' in repr(obj)
if sys.version_info >= (3, ):
expected = 'builtins.len'
else:
expected = '__builtin__.len'
nose.tools.assert_equals(fullqualname(obj), expected)
|
"""Tests for fullqualname."""
import inspect
import nose
import sys
from fullqualname import fullqualname
def test_builtin_function():
# Test built-in function object.
obj = len
# Type is 'builtin_function_or_method'.
assert type(obj).__name__ == 'builtin_function_or_method'
# Object is a function.
assert 'built-in function' in repr(obj)
if sys.version_info >= (3, ):
expected = 'builtins.len'
else:
expected = '__builtin__.len'
nose.tools.assert_equals(fullqualname(obj), expected)
def test_builtin_method():
# Test built-in method object.
obj = [1, 2, 3].append
# Object type is 'builtin_function_or_method'.
assert type(obj).__name__ == 'builtin_function_or_method'
# Object is a method.
assert 'built-in method' in repr(obj)
# Object __self__ attribute is not a class.
assert not inspect.isclass(obj.__self__)
if sys.version_info >= (3, ):
expected = 'builtins.list.append'
else:
expected = '__builtin__.list.append'
nose.tools.assert_equals(fullqualname(obj), expected)
|
Add built-in method object test
|
Add built-in method object test
|
Python
|
bsd-3-clause
|
etgalloway/fullqualname
|
"""Tests for fullqualname."""
+ import inspect
import nose
import sys
from fullqualname import fullqualname
def test_builtin_function():
# Test built-in function object.
obj = len
# Type is 'builtin_function_or_method'.
assert type(obj).__name__ == 'builtin_function_or_method'
# Object is a function.
assert 'built-in function' in repr(obj)
if sys.version_info >= (3, ):
expected = 'builtins.len'
else:
expected = '__builtin__.len'
nose.tools.assert_equals(fullqualname(obj), expected)
+
+ def test_builtin_method():
+ # Test built-in method object.
+
+ obj = [1, 2, 3].append
+
+ # Object type is 'builtin_function_or_method'.
+ assert type(obj).__name__ == 'builtin_function_or_method'
+
+ # Object is a method.
+ assert 'built-in method' in repr(obj)
+
+ # Object __self__ attribute is not a class.
+ assert not inspect.isclass(obj.__self__)
+
+ if sys.version_info >= (3, ):
+ expected = 'builtins.list.append'
+ else:
+ expected = '__builtin__.list.append'
+
+ nose.tools.assert_equals(fullqualname(obj), expected)
+
|
Add built-in method object test
|
## Code Before:
"""Tests for fullqualname."""
import nose
import sys
from fullqualname import fullqualname
def test_builtin_function():
# Test built-in function object.
obj = len
# Type is 'builtin_function_or_method'.
assert type(obj).__name__ == 'builtin_function_or_method'
# Object is a function.
assert 'built-in function' in repr(obj)
if sys.version_info >= (3, ):
expected = 'builtins.len'
else:
expected = '__builtin__.len'
nose.tools.assert_equals(fullqualname(obj), expected)
## Instruction:
Add built-in method object test
## Code After:
"""Tests for fullqualname."""
import inspect
import nose
import sys
from fullqualname import fullqualname
def test_builtin_function():
# Test built-in function object.
obj = len
# Type is 'builtin_function_or_method'.
assert type(obj).__name__ == 'builtin_function_or_method'
# Object is a function.
assert 'built-in function' in repr(obj)
if sys.version_info >= (3, ):
expected = 'builtins.len'
else:
expected = '__builtin__.len'
nose.tools.assert_equals(fullqualname(obj), expected)
def test_builtin_method():
# Test built-in method object.
obj = [1, 2, 3].append
# Object type is 'builtin_function_or_method'.
assert type(obj).__name__ == 'builtin_function_or_method'
# Object is a method.
assert 'built-in method' in repr(obj)
# Object __self__ attribute is not a class.
assert not inspect.isclass(obj.__self__)
if sys.version_info >= (3, ):
expected = 'builtins.list.append'
else:
expected = '__builtin__.list.append'
nose.tools.assert_equals(fullqualname(obj), expected)
|
// ... existing code ...
import inspect
import nose
// ... modified code ...
nose.tools.assert_equals(fullqualname(obj), expected)
def test_builtin_method():
# Test built-in method object.
obj = [1, 2, 3].append
# Object type is 'builtin_function_or_method'.
assert type(obj).__name__ == 'builtin_function_or_method'
# Object is a method.
assert 'built-in method' in repr(obj)
# Object __self__ attribute is not a class.
assert not inspect.isclass(obj.__self__)
if sys.version_info >= (3, ):
expected = 'builtins.list.append'
else:
expected = '__builtin__.list.append'
nose.tools.assert_equals(fullqualname(obj), expected)
// ... rest of the code ...
|
c6cdf543f6bfd0049594eeb530551371bf21bae4
|
test/test_scraping.py
|
test/test_scraping.py
|
from datetime import datetime
import sys
import unittest
import btceapi
class TestScraping(unittest.TestCase):
def test_scrape_main_page(self):
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
self.assertIs(type(time), datetime)
if sys.version_info[0] == 2:
# python2.x
assert type(msgId) in (str, unicode)
assert type(user) in (str, unicode)
assert type(text) in (str, unicode)
else:
# python3.x
self.assertIs(type(msgId), str)
self.assertIs(type(user), str)
self.assertIs(type(text), str)
if __name__ == '__main__':
unittest.main()
|
from datetime import datetime
import sys
import unittest
import btceapi
class TestScraping(unittest.TestCase):
def test_scrape_main_page(self):
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
assert type(time) is datetime
if sys.version_info[0] == 2:
# python2.x
assert type(msgId) in (str, unicode)
assert type(user) in (str, unicode)
assert type(text) in (str, unicode)
else:
# python3.x
self.assertIs(type(msgId), str)
self.assertIs(type(user), str)
self.assertIs(type(text), str)
if __name__ == '__main__':
unittest.main()
|
Fix for assertIs method not being present in Python 2.6.
|
Fix for assertIs method not being present in Python 2.6.
|
Python
|
mit
|
lromanov/tidex-api,CodeReclaimers/btce-api,alanmcintyre/btce-api
|
from datetime import datetime
import sys
import unittest
import btceapi
class TestScraping(unittest.TestCase):
def test_scrape_main_page(self):
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
- self.assertIs(type(time), datetime)
+ assert type(time) is datetime
if sys.version_info[0] == 2:
# python2.x
assert type(msgId) in (str, unicode)
assert type(user) in (str, unicode)
assert type(text) in (str, unicode)
else:
# python3.x
self.assertIs(type(msgId), str)
self.assertIs(type(user), str)
self.assertIs(type(text), str)
if __name__ == '__main__':
unittest.main()
|
Fix for assertIs method not being present in Python 2.6.
|
## Code Before:
from datetime import datetime
import sys
import unittest
import btceapi
class TestScraping(unittest.TestCase):
def test_scrape_main_page(self):
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
self.assertIs(type(time), datetime)
if sys.version_info[0] == 2:
# python2.x
assert type(msgId) in (str, unicode)
assert type(user) in (str, unicode)
assert type(text) in (str, unicode)
else:
# python3.x
self.assertIs(type(msgId), str)
self.assertIs(type(user), str)
self.assertIs(type(text), str)
if __name__ == '__main__':
unittest.main()
## Instruction:
Fix for assertIs method not being present in Python 2.6.
## Code After:
from datetime import datetime
import sys
import unittest
import btceapi
class TestScraping(unittest.TestCase):
def test_scrape_main_page(self):
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
assert type(time) is datetime
if sys.version_info[0] == 2:
# python2.x
assert type(msgId) in (str, unicode)
assert type(user) in (str, unicode)
assert type(text) in (str, unicode)
else:
# python3.x
self.assertIs(type(msgId), str)
self.assertIs(type(user), str)
self.assertIs(type(text), str)
if __name__ == '__main__':
unittest.main()
|
# ... existing code ...
msgId, user, time, text = message
assert type(time) is datetime
if sys.version_info[0] == 2:
# ... rest of the code ...
|
bc411a7069386196abc6de6ae2314182efbda048
|
avalonstar/apps/subscribers/admin.py
|
avalonstar/apps/subscribers/admin.py
|
from django.contrib import admin
from .models import Ticket
class TicketAdmin(admin.ModelAdmin):
list_display = ['name', 'display_name', 'created', 'updated', 'is_active', 'is_paid', 'twid']
list_editable = ['created', 'updated', 'is_active', 'is_paid']
ordering = ['-updated']
admin.site.register(Ticket, TicketAdmin)
|
from django.contrib import admin
from .models import Ticket
class TicketAdmin(admin.ModelAdmin):
list_display = ['name', 'display_name', 'created', 'updated', 'streak', 'is_active', 'is_paid', 'twid']
list_editable = ['is_active', 'is_paid']
ordering = ['-updated']
admin.site.register(Ticket, TicketAdmin)
|
Add streak to list_display, remove created and updated from list_editable.
|
Add streak to list_display, remove created and updated from list_editable.
|
Python
|
apache-2.0
|
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
|
from django.contrib import admin
from .models import Ticket
class TicketAdmin(admin.ModelAdmin):
- list_display = ['name', 'display_name', 'created', 'updated', 'is_active', 'is_paid', 'twid']
+ list_display = ['name', 'display_name', 'created', 'updated', 'streak', 'is_active', 'is_paid', 'twid']
- list_editable = ['created', 'updated', 'is_active', 'is_paid']
+ list_editable = ['is_active', 'is_paid']
ordering = ['-updated']
admin.site.register(Ticket, TicketAdmin)
|
Add streak to list_display, remove created and updated from list_editable.
|
## Code Before:
from django.contrib import admin
from .models import Ticket
class TicketAdmin(admin.ModelAdmin):
list_display = ['name', 'display_name', 'created', 'updated', 'is_active', 'is_paid', 'twid']
list_editable = ['created', 'updated', 'is_active', 'is_paid']
ordering = ['-updated']
admin.site.register(Ticket, TicketAdmin)
## Instruction:
Add streak to list_display, remove created and updated from list_editable.
## Code After:
from django.contrib import admin
from .models import Ticket
class TicketAdmin(admin.ModelAdmin):
list_display = ['name', 'display_name', 'created', 'updated', 'streak', 'is_active', 'is_paid', 'twid']
list_editable = ['is_active', 'is_paid']
ordering = ['-updated']
admin.site.register(Ticket, TicketAdmin)
|
# ... existing code ...
class TicketAdmin(admin.ModelAdmin):
list_display = ['name', 'display_name', 'created', 'updated', 'streak', 'is_active', 'is_paid', 'twid']
list_editable = ['is_active', 'is_paid']
ordering = ['-updated']
# ... rest of the code ...
|
d6f6d41665f58e68833b57d8b0d04d113f2c86a9
|
ideascube/conf/idb_jor_zaatari.py
|
ideascube/conf/idb_jor_zaatari.py
|
"""Ideaxbox for Zaatari, Jordan"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['SY', 'JO']
TIME_ZONE = 'Asia/Amman'
LANGUAGE_CODE = 'ar'
LOAN_DURATION = 14
MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender']
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['short_name', 'full_name', 'birth_year', 'gender', 'id_card_number']), # noqa
(_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa
(_('In the town'), ['current_occupation', 'school_level']),
(_('Language skills'), ['en_level']),
)
|
"""Ideaxbox for Zaatari, Jordan"""
from .idb_jor_azraq import * # noqa
ENTRY_ACTIVITY_CHOICES = []
|
Make zaatari import from azraq
|
Make zaatari import from azraq
|
Python
|
agpl-3.0
|
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
|
"""Ideaxbox for Zaatari, Jordan"""
- from .idb import * # noqa
+ from .idb_jor_azraq import * # noqa
- from django.utils.translation import ugettext_lazy as _
+ ENTRY_ACTIVITY_CHOICES = []
- IDEASCUBE_PLACE_NAME = _("city")
- COUNTRIES_FIRST = ['SY', 'JO']
- TIME_ZONE = 'Asia/Amman'
- LANGUAGE_CODE = 'ar'
- LOAN_DURATION = 14
- MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender']
- USER_FORM_FIELDS = (
- ('Ideasbox', ['serial', 'box_awareness']),
- (_('Personal informations'), ['short_name', 'full_name', 'birth_year', 'gender', 'id_card_number']), # noqa
- (_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa
- (_('In the town'), ['current_occupation', 'school_level']),
- (_('Language skills'), ['en_level']),
- )
|
Make zaatari import from azraq
|
## Code Before:
"""Ideaxbox for Zaatari, Jordan"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['SY', 'JO']
TIME_ZONE = 'Asia/Amman'
LANGUAGE_CODE = 'ar'
LOAN_DURATION = 14
MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender']
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['short_name', 'full_name', 'birth_year', 'gender', 'id_card_number']), # noqa
(_('Family'), ['marital_status', 'family_status', 'children_under_12', 'children_under_18', 'children_above_18']), # noqa
(_('In the town'), ['current_occupation', 'school_level']),
(_('Language skills'), ['en_level']),
)
## Instruction:
Make zaatari import from azraq
## Code After:
"""Ideaxbox for Zaatari, Jordan"""
from .idb_jor_azraq import * # noqa
ENTRY_ACTIVITY_CHOICES = []
|
// ... existing code ...
"""Ideaxbox for Zaatari, Jordan"""
from .idb_jor_azraq import * # noqa
ENTRY_ACTIVITY_CHOICES = []
// ... rest of the code ...
|
ea73a999ffbc936f7e072a310f05ee2cb26b6c21
|
openprocurement/tender/limited/adapters.py
|
openprocurement/tender/limited/adapters.py
|
from openprocurement.tender.core.adapters import TenderConfigurator
from openprocurement.tender.limited.models import (
ReportingTender, NegotiationTender, NegotiationQuickTender
)
class TenderReportingConfigurator(TenderConfigurator):
""" Reporting Tender configuration adapter """
name = "Reporting Tender configurator"
model = ReportingTender
@property
def edit_accreditation(self):
raise NotImplemented
class TenderNegotiationConfigurator(TenderConfigurator):
""" Negotiation Tender configuration adapter """
name = "Negotiation Tender configurator"
model = NegotiationTender
@property
def edit_accreditation(self):
raise NotImplemented
class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator):
""" Negotiation Quick Tender configuration adapter """
name = "Negotiation Quick Tender configurator"
model = NegotiationQuickTender
|
from openprocurement.tender.core.adapters import TenderConfigurator
from openprocurement.tender.openua.constants import STATUS4ROLE
from openprocurement.tender.limited.models import (
ReportingTender, NegotiationTender, NegotiationQuickTender
)
class TenderReportingConfigurator(TenderConfigurator):
""" Reporting Tender configuration adapter """
name = "Reporting Tender configurator"
model = ReportingTender
# Dictionary with allowed complaint statuses for operations for each role
allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE
@property
def edit_accreditation(self):
raise NotImplemented
class TenderNegotiationConfigurator(TenderConfigurator):
""" Negotiation Tender configuration adapter """
name = "Negotiation Tender configurator"
model = NegotiationTender
# Dictionary with allowed complaint statuses for operations for each role
allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE
@property
def edit_accreditation(self):
raise NotImplemented
class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator):
""" Negotiation Quick Tender configuration adapter """
name = "Negotiation Quick Tender configurator"
model = NegotiationQuickTender
|
Add import and constant in adapter
|
Add import and constant in adapter
|
Python
|
apache-2.0
|
openprocurement/openprocurement.tender.limited
|
from openprocurement.tender.core.adapters import TenderConfigurator
+ from openprocurement.tender.openua.constants import STATUS4ROLE
from openprocurement.tender.limited.models import (
ReportingTender, NegotiationTender, NegotiationQuickTender
)
class TenderReportingConfigurator(TenderConfigurator):
""" Reporting Tender configuration adapter """
name = "Reporting Tender configurator"
model = ReportingTender
+
+ # Dictionary with allowed complaint statuses for operations for each role
+ allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE
@property
def edit_accreditation(self):
raise NotImplemented
class TenderNegotiationConfigurator(TenderConfigurator):
""" Negotiation Tender configuration adapter """
name = "Negotiation Tender configurator"
model = NegotiationTender
+ # Dictionary with allowed complaint statuses for operations for each role
+ allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE
+
@property
def edit_accreditation(self):
raise NotImplemented
class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator):
""" Negotiation Quick Tender configuration adapter """
name = "Negotiation Quick Tender configurator"
model = NegotiationQuickTender
|
Add import and constant in adapter
|
## Code Before:
from openprocurement.tender.core.adapters import TenderConfigurator
from openprocurement.tender.limited.models import (
ReportingTender, NegotiationTender, NegotiationQuickTender
)
class TenderReportingConfigurator(TenderConfigurator):
""" Reporting Tender configuration adapter """
name = "Reporting Tender configurator"
model = ReportingTender
@property
def edit_accreditation(self):
raise NotImplemented
class TenderNegotiationConfigurator(TenderConfigurator):
""" Negotiation Tender configuration adapter """
name = "Negotiation Tender configurator"
model = NegotiationTender
@property
def edit_accreditation(self):
raise NotImplemented
class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator):
""" Negotiation Quick Tender configuration adapter """
name = "Negotiation Quick Tender configurator"
model = NegotiationQuickTender
## Instruction:
Add import and constant in adapter
## Code After:
from openprocurement.tender.core.adapters import TenderConfigurator
from openprocurement.tender.openua.constants import STATUS4ROLE
from openprocurement.tender.limited.models import (
ReportingTender, NegotiationTender, NegotiationQuickTender
)
class TenderReportingConfigurator(TenderConfigurator):
""" Reporting Tender configuration adapter """
name = "Reporting Tender configurator"
model = ReportingTender
# Dictionary with allowed complaint statuses for operations for each role
allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE
@property
def edit_accreditation(self):
raise NotImplemented
class TenderNegotiationConfigurator(TenderConfigurator):
""" Negotiation Tender configuration adapter """
name = "Negotiation Tender configurator"
model = NegotiationTender
# Dictionary with allowed complaint statuses for operations for each role
allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE
@property
def edit_accreditation(self):
raise NotImplemented
class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator):
""" Negotiation Quick Tender configuration adapter """
name = "Negotiation Quick Tender configurator"
model = NegotiationQuickTender
|
# ... existing code ...
from openprocurement.tender.core.adapters import TenderConfigurator
from openprocurement.tender.openua.constants import STATUS4ROLE
from openprocurement.tender.limited.models import (
# ... modified code ...
model = ReportingTender
# Dictionary with allowed complaint statuses for operations for each role
allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE
...
# Dictionary with allowed complaint statuses for operations for each role
allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE
@property
# ... rest of the code ...
|
805e86c0cd69f49863d2ca4c37e094a344d79c64
|
lib/jasy/core/MetaData.py
|
lib/jasy/core/MetaData.py
|
class MetaData:
"""
Data structure to hold all dependency information
Hint: Must be a clean data class without links to other
systems for optiomal cachability using Pickle
"""
def __init__(self, tree):
self.provides = set()
self.requires = set()
self.optionals = set()
self.breaks = set()
self.assets = set()
self.__inspect(tree)
def __inspect(self, node):
""" The internal inspection routine """
# Parse comments
try:
comments = node.comments
except AttributeError:
comments = None
if comments:
for comment in comments:
commentTags = comment.getTags()
if commentTags:
if "provide" in commentTags:
self.provides.update(set(commentTags["provide"]))
if "require" in commentTags:
self.requires.update(set(commentTags["require"]))
if "optional" in commentTags:
self.optionals.update(set(commentTags["optional"]))
if "break" in commentTags:
self.breaks.update(set(commentTags["break"]))
if "asset" in commentTags:
self.assets.update(set(commentTags["asset"]))
# Process children
for child in node:
self.__inspect(child)
|
class MetaData:
"""
Data structure to hold all dependency information
Hint: Must be a clean data class without links to other
systems for optiomal cachability using Pickle
"""
__slots__ = ["provides", "requires", "optionals", "breaks", "assets"]
def __init__(self, tree):
self.provides = set()
self.requires = set()
self.optionals = set()
self.breaks = set()
self.assets = set()
self.__inspect(tree)
def __inspect(self, node):
""" The internal inspection routine """
# Parse comments
try:
comments = node.comments
except AttributeError:
comments = None
if comments:
for comment in comments:
commentTags = comment.getTags()
if commentTags:
if "provide" in commentTags:
self.provides.update(set(commentTags["provide"]))
if "require" in commentTags:
self.requires.update(set(commentTags["require"]))
if "optional" in commentTags:
self.optionals.update(set(commentTags["optional"]))
if "break" in commentTags:
self.breaks.update(set(commentTags["break"]))
if "asset" in commentTags:
self.assets.update(set(commentTags["asset"]))
# Process children
for child in node:
self.__inspect(child)
|
Make use of slots to reduce in-memory size
|
Make use of slots to reduce in-memory size
|
Python
|
mit
|
zynga/jasy,zynga/jasy,sebastian-software/jasy,sebastian-software/jasy
|
class MetaData:
"""
Data structure to hold all dependency information
Hint: Must be a clean data class without links to other
systems for optiomal cachability using Pickle
"""
+
+ __slots__ = ["provides", "requires", "optionals", "breaks", "assets"]
def __init__(self, tree):
self.provides = set()
self.requires = set()
self.optionals = set()
self.breaks = set()
self.assets = set()
self.__inspect(tree)
def __inspect(self, node):
""" The internal inspection routine """
# Parse comments
try:
comments = node.comments
except AttributeError:
comments = None
if comments:
for comment in comments:
commentTags = comment.getTags()
if commentTags:
if "provide" in commentTags:
self.provides.update(set(commentTags["provide"]))
if "require" in commentTags:
self.requires.update(set(commentTags["require"]))
if "optional" in commentTags:
self.optionals.update(set(commentTags["optional"]))
if "break" in commentTags:
self.breaks.update(set(commentTags["break"]))
if "asset" in commentTags:
self.assets.update(set(commentTags["asset"]))
# Process children
for child in node:
self.__inspect(child)
|
Make use of slots to reduce in-memory size
|
## Code Before:
class MetaData:
"""
Data structure to hold all dependency information
Hint: Must be a clean data class without links to other
systems for optiomal cachability using Pickle
"""
def __init__(self, tree):
self.provides = set()
self.requires = set()
self.optionals = set()
self.breaks = set()
self.assets = set()
self.__inspect(tree)
def __inspect(self, node):
""" The internal inspection routine """
# Parse comments
try:
comments = node.comments
except AttributeError:
comments = None
if comments:
for comment in comments:
commentTags = comment.getTags()
if commentTags:
if "provide" in commentTags:
self.provides.update(set(commentTags["provide"]))
if "require" in commentTags:
self.requires.update(set(commentTags["require"]))
if "optional" in commentTags:
self.optionals.update(set(commentTags["optional"]))
if "break" in commentTags:
self.breaks.update(set(commentTags["break"]))
if "asset" in commentTags:
self.assets.update(set(commentTags["asset"]))
# Process children
for child in node:
self.__inspect(child)
## Instruction:
Make use of slots to reduce in-memory size
## Code After:
class MetaData:
"""
Data structure to hold all dependency information
Hint: Must be a clean data class without links to other
systems for optiomal cachability using Pickle
"""
__slots__ = ["provides", "requires", "optionals", "breaks", "assets"]
def __init__(self, tree):
self.provides = set()
self.requires = set()
self.optionals = set()
self.breaks = set()
self.assets = set()
self.__inspect(tree)
def __inspect(self, node):
""" The internal inspection routine """
# Parse comments
try:
comments = node.comments
except AttributeError:
comments = None
if comments:
for comment in comments:
commentTags = comment.getTags()
if commentTags:
if "provide" in commentTags:
self.provides.update(set(commentTags["provide"]))
if "require" in commentTags:
self.requires.update(set(commentTags["require"]))
if "optional" in commentTags:
self.optionals.update(set(commentTags["optional"]))
if "break" in commentTags:
self.breaks.update(set(commentTags["break"]))
if "asset" in commentTags:
self.assets.update(set(commentTags["asset"]))
# Process children
for child in node:
self.__inspect(child)
|
...
"""
__slots__ = ["provides", "requires", "optionals", "breaks", "assets"]
...
|
8b1818aefd6180548cf3b9770eb7a4d93e827fd7
|
alignak_app/__init__.py
|
alignak_app/__init__.py
|
# Specific Application
from alignak_app import alignak_data, application, launch
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
|
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
|
Remove import of all Class app
|
Remove import of all Class app
|
Python
|
agpl-3.0
|
Alignak-monitoring-contrib/alignak-app,Alignak-monitoring-contrib/alignak-app
|
-
- # Specific Application
- from alignak_app import alignak_data, application, launch
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
|
Remove import of all Class app
|
## Code Before:
# Specific Application
from alignak_app import alignak_data, application, launch
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
## Instruction:
Remove import of all Class app
## Code After:
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__author__ = u"Estrada Matthieu"
__copyright__ = u"2015-2016 - %s" % __author__
__license__ = u"GNU Affero General Public License, version 3"
__description__ = u"Alignak monitoring application AppIndicator"
__releasenotes__ = u"""Alignak monitoring application AppIndicator"""
__doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-app"
# Application Manifest
manifest = {
'name': __application__,
'version': __version__,
'author': __author__,
'description': __description__,
'copyright': __copyright__,
'license': __license__,
'release': __releasenotes__,
'doc': __doc_url__
}
|
...
...
|
4e28e43fea2eaa08006eeb4d70159c8ebd3c83b4
|
flask_uploads/__init__.py
|
flask_uploads/__init__.py
|
import loaders
loader = loaders.Lazy(
'%s.models' % __name__,
('Upload',)
)
import extensions
from .functions import (
delete,
save,
save_file,
save_images,
)
from .models import Upload
def init(db, Storage, resizer=None):
extensions.db = db
extensions.resizer = resizer
extensions.Storage = Storage
loader.ready()
__all__ = (
delete,
init,
save,
save_file,
save_images,
Upload,
)
|
import loaders
loader = loaders.Lazy(
'%s.models' % __name__,
('Upload',)
)
import extensions
from .functions import (
delete,
save,
save_file,
save_images,
)
from .models import Upload
def init(db, Storage, resizer=None):
if 'upload' in db.metadata.tables:
return # Already registered the model.
extensions.db = db
extensions.resizer = resizer
extensions.Storage = Storage
loader.ready()
__all__ = (
delete,
init,
save,
save_file,
save_images,
Upload,
)
|
Make sure model isn't added several times.
|
Make sure model isn't added several times.
|
Python
|
mit
|
FelixLoether/flask-uploads,FelixLoether/flask-image-upload-thing
|
import loaders
loader = loaders.Lazy(
'%s.models' % __name__,
('Upload',)
)
import extensions
from .functions import (
delete,
save,
save_file,
save_images,
)
from .models import Upload
def init(db, Storage, resizer=None):
+ if 'upload' in db.metadata.tables:
+ return # Already registered the model.
+
extensions.db = db
extensions.resizer = resizer
extensions.Storage = Storage
loader.ready()
__all__ = (
delete,
init,
save,
save_file,
save_images,
Upload,
)
|
Make sure model isn't added several times.
|
## Code Before:
import loaders
loader = loaders.Lazy(
'%s.models' % __name__,
('Upload',)
)
import extensions
from .functions import (
delete,
save,
save_file,
save_images,
)
from .models import Upload
def init(db, Storage, resizer=None):
extensions.db = db
extensions.resizer = resizer
extensions.Storage = Storage
loader.ready()
__all__ = (
delete,
init,
save,
save_file,
save_images,
Upload,
)
## Instruction:
Make sure model isn't added several times.
## Code After:
import loaders
loader = loaders.Lazy(
'%s.models' % __name__,
('Upload',)
)
import extensions
from .functions import (
delete,
save,
save_file,
save_images,
)
from .models import Upload
def init(db, Storage, resizer=None):
if 'upload' in db.metadata.tables:
return # Already registered the model.
extensions.db = db
extensions.resizer = resizer
extensions.Storage = Storage
loader.ready()
__all__ = (
delete,
init,
save,
save_file,
save_images,
Upload,
)
|
// ... existing code ...
def init(db, Storage, resizer=None):
if 'upload' in db.metadata.tables:
return # Already registered the model.
extensions.db = db
// ... rest of the code ...
|
233ce96d96caff3070f24d9d3dff3ed85be81fee
|
halaqat/settings/shaha.py
|
halaqat/settings/shaha.py
|
from .base_settings import *
import dj_database_url
import os
ALLOWED_HOSTS = ['0.0.0.0']
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
|
from .base_settings import *
import dj_database_url
import os
ALLOWED_HOSTS = ['0.0.0.0']
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
|
Fix The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
|
Fix The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
|
Python
|
mit
|
EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat
|
from .base_settings import *
import dj_database_url
import os
ALLOWED_HOSTS = ['0.0.0.0']
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
- # Extra places for collectstatic to find static files.
- STATICFILES_DIRS = (
- os.path.join(PROJECT_ROOT, 'static'),
- )
-
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
|
Fix The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
|
## Code Before:
from .base_settings import *
import dj_database_url
import os
ALLOWED_HOSTS = ['0.0.0.0']
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
## Instruction:
Fix The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
## Code After:
from .base_settings import *
import dj_database_url
import os
ALLOWED_HOSTS = ['0.0.0.0']
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
|
# ... existing code ...
# Simplified static file serving.
# ... rest of the code ...
|
7ec5786efbdb20b9cbcdf0b4f1b583a7e07e0644
|
comrade/core/tests.py
|
comrade/core/tests.py
|
from nose.tools import ok_, eq_
import unittest
import models
class SimpleModel(models.ComradeBaseModel):
def __unicode__(self):
return u'This is a unicode string'
class TestBaseModel(unittest.TestCase):
def setUp(self):
super(TestBaseModel, self).setUp()
self.obj = SimpleModel()
def test_repr(self):
ok_(isinstance(self.obj.__repr__(), str))
def test_str(self):
ok_(isinstance(self.obj.__str__(), str))
def test_unicode(self):
ok_(isinstance(self.obj.__unicode__(), unicode))
|
from nose.tools import ok_, eq_
import unittest
import models
def check_direct_to_template(prefix, pattern):
from django import test
from django.core.urlresolvers import reverse
client = test.Client()
response = client.get(reverse(prefix + ':' + pattern.name))
template_name = pattern.default_args['template']
template_names = [t.name for t in test.testcases.to_list(response.template)]
ok_(template_names)
ok_(template_name in template_names,
"Template '%s' was not a template used to render"
" the response. Actual template(s) used: %s" %
(template_name, u', '.join(template_names)))
class SimpleModel(models.ComradeBaseModel):
def __unicode__(self):
return u'This is a unicode string'
class TestBaseModel(unittest.TestCase):
def setUp(self):
super(TestBaseModel, self).setUp()
self.obj = SimpleModel()
def test_repr(self):
ok_(isinstance(self.obj.__repr__(), str))
def test_str(self):
ok_(isinstance(self.obj.__str__(), str))
def test_unicode(self):
ok_(isinstance(self.obj.__unicode__(), unicode))
|
Add test helper method for checking direct_to_template views.
|
Add test helper method for checking direct_to_template views.
|
Python
|
mit
|
bueda/django-comrade
|
from nose.tools import ok_, eq_
import unittest
import models
+
+ def check_direct_to_template(prefix, pattern):
+ from django import test
+ from django.core.urlresolvers import reverse
+ client = test.Client()
+ response = client.get(reverse(prefix + ':' + pattern.name))
+ template_name = pattern.default_args['template']
+ template_names = [t.name for t in test.testcases.to_list(response.template)]
+ ok_(template_names)
+ ok_(template_name in template_names,
+ "Template '%s' was not a template used to render"
+ " the response. Actual template(s) used: %s" %
+ (template_name, u', '.join(template_names)))
class SimpleModel(models.ComradeBaseModel):
def __unicode__(self):
return u'This is a unicode string'
class TestBaseModel(unittest.TestCase):
def setUp(self):
super(TestBaseModel, self).setUp()
self.obj = SimpleModel()
def test_repr(self):
ok_(isinstance(self.obj.__repr__(), str))
def test_str(self):
ok_(isinstance(self.obj.__str__(), str))
def test_unicode(self):
ok_(isinstance(self.obj.__unicode__(), unicode))
-
|
Add test helper method for checking direct_to_template views.
|
## Code Before:
from nose.tools import ok_, eq_
import unittest
import models
class SimpleModel(models.ComradeBaseModel):
def __unicode__(self):
return u'This is a unicode string'
class TestBaseModel(unittest.TestCase):
def setUp(self):
super(TestBaseModel, self).setUp()
self.obj = SimpleModel()
def test_repr(self):
ok_(isinstance(self.obj.__repr__(), str))
def test_str(self):
ok_(isinstance(self.obj.__str__(), str))
def test_unicode(self):
ok_(isinstance(self.obj.__unicode__(), unicode))
## Instruction:
Add test helper method for checking direct_to_template views.
## Code After:
from nose.tools import ok_, eq_
import unittest
import models
def check_direct_to_template(prefix, pattern):
from django import test
from django.core.urlresolvers import reverse
client = test.Client()
response = client.get(reverse(prefix + ':' + pattern.name))
template_name = pattern.default_args['template']
template_names = [t.name for t in test.testcases.to_list(response.template)]
ok_(template_names)
ok_(template_name in template_names,
"Template '%s' was not a template used to render"
" the response. Actual template(s) used: %s" %
(template_name, u', '.join(template_names)))
class SimpleModel(models.ComradeBaseModel):
def __unicode__(self):
return u'This is a unicode string'
class TestBaseModel(unittest.TestCase):
def setUp(self):
super(TestBaseModel, self).setUp()
self.obj = SimpleModel()
def test_repr(self):
ok_(isinstance(self.obj.__repr__(), str))
def test_str(self):
ok_(isinstance(self.obj.__str__(), str))
def test_unicode(self):
ok_(isinstance(self.obj.__unicode__(), unicode))
|
# ... existing code ...
import models
def check_direct_to_template(prefix, pattern):
from django import test
from django.core.urlresolvers import reverse
client = test.Client()
response = client.get(reverse(prefix + ':' + pattern.name))
template_name = pattern.default_args['template']
template_names = [t.name for t in test.testcases.to_list(response.template)]
ok_(template_names)
ok_(template_name in template_names,
"Template '%s' was not a template used to render"
" the response. Actual template(s) used: %s" %
(template_name, u', '.join(template_names)))
# ... modified code ...
ok_(isinstance(self.obj.__unicode__(), unicode))
# ... rest of the code ...
|
56471d264671b652b4b40619f709dc6b8e02eac1
|
dragonflow/db/models/host_route.py
|
dragonflow/db/models/host_route.py
|
import dragonflow.db.field_types as df_fields
import dragonflow.db.model_framework as mf
@mf.construct_nb_db_model
class HostRoute(mf.ModelBase):
id = None
destination = df_fields.IpNetworkField(required=True)
nexthop = df_fields.IpAddressField(required=True)
|
from jsonmodels import models
import dragonflow.db.field_types as df_fields
class HostRoute(models.Base):
destination = df_fields.IpNetworkField(required=True)
nexthop = df_fields.IpAddressField(required=True)
|
Change HostRoute to a plain model
|
Change HostRoute to a plain model
Since HostRoute doesn't have id, store it as a plain db model.
Change-Id: I3dbb9e5ffa42bf48f47b7010ee6baf470b55e85e
Partially-Implements: bp refactor-nb-api
|
Python
|
apache-2.0
|
openstack/dragonflow,openstack/dragonflow,openstack/dragonflow
|
+
+ from jsonmodels import models
import dragonflow.db.field_types as df_fields
- import dragonflow.db.model_framework as mf
- @mf.construct_nb_db_model
- class HostRoute(mf.ModelBase):
+ class HostRoute(models.Base):
- id = None
destination = df_fields.IpNetworkField(required=True)
nexthop = df_fields.IpAddressField(required=True)
|
Change HostRoute to a plain model
|
## Code Before:
import dragonflow.db.field_types as df_fields
import dragonflow.db.model_framework as mf
@mf.construct_nb_db_model
class HostRoute(mf.ModelBase):
id = None
destination = df_fields.IpNetworkField(required=True)
nexthop = df_fields.IpAddressField(required=True)
## Instruction:
Change HostRoute to a plain model
## Code After:
from jsonmodels import models
import dragonflow.db.field_types as df_fields
class HostRoute(models.Base):
destination = df_fields.IpNetworkField(required=True)
nexthop = df_fields.IpAddressField(required=True)
|
...
from jsonmodels import models
...
import dragonflow.db.field_types as df_fields
...
class HostRoute(models.Base):
destination = df_fields.IpNetworkField(required=True)
...
|
5ea25bc6c72e5c934e56a90c44f8019ad176bb27
|
comet/utility/test/test_spawn.py
|
comet/utility/test/test_spawn.py
|
import sys
from twisted.trial import unittest
from twisted.python import failure
from ..spawn import SpawnCommand
class DummyEvent(object):
text = ""
class SpawnCommandProtocolTestCase(unittest.TestCase):
def test_good_process(self):
spawn = SpawnCommand(sys.executable)
d = spawn(DummyEvent())
d.addCallback(self.assertEqual, True)
return d
def test_bad_process(self):
spawn = SpawnCommand("/not/a/real/executable")
d = spawn(DummyEvent())
d.addErrback(self.assertIsInstance, failure.Failure)
return d
|
import sys
from twisted.trial import unittest
from twisted.python import failure
from twisted.python import util
from ..spawn import SpawnCommand
class DummyEvent(object):
def __init__(self, text=None):
self.text = text
class SpawnCommandProtocolTestCase(unittest.TestCase):
def test_good_process(self):
spawn = SpawnCommand(sys.executable)
d = spawn(DummyEvent())
d.addCallback(self.assertEqual, True)
return d
def test_bad_process(self):
spawn = SpawnCommand("/not/a/real/executable")
d = spawn(DummyEvent())
d.addErrback(self.assertIsInstance, failure.Failure)
return d
def test_write_data(self):
TEXT = "Test spawn process"
def read_data(result):
f = open("spawnfile.txt")
try:
self.assertEqual(f.read(), TEXT)
finally:
f.close()
spawn = SpawnCommand(util.sibpath(__file__, "test_spawn.sh"))
d = spawn(DummyEvent(TEXT))
d.addCallback(read_data)
return d
|
Test that spawned process actually writes data
|
Test that spawned process actually writes data
|
Python
|
bsd-2-clause
|
jdswinbank/Comet,jdswinbank/Comet
|
import sys
from twisted.trial import unittest
from twisted.python import failure
+ from twisted.python import util
from ..spawn import SpawnCommand
class DummyEvent(object):
- text = ""
+ def __init__(self, text=None):
+ self.text = text
class SpawnCommandProtocolTestCase(unittest.TestCase):
def test_good_process(self):
spawn = SpawnCommand(sys.executable)
d = spawn(DummyEvent())
d.addCallback(self.assertEqual, True)
return d
def test_bad_process(self):
spawn = SpawnCommand("/not/a/real/executable")
d = spawn(DummyEvent())
d.addErrback(self.assertIsInstance, failure.Failure)
return d
+ def test_write_data(self):
+ TEXT = "Test spawn process"
+ def read_data(result):
+ f = open("spawnfile.txt")
+ try:
+ self.assertEqual(f.read(), TEXT)
+ finally:
+ f.close()
+ spawn = SpawnCommand(util.sibpath(__file__, "test_spawn.sh"))
+ d = spawn(DummyEvent(TEXT))
+ d.addCallback(read_data)
+ return d
+
|
Test that spawned process actually writes data
|
## Code Before:
import sys
from twisted.trial import unittest
from twisted.python import failure
from ..spawn import SpawnCommand
class DummyEvent(object):
text = ""
class SpawnCommandProtocolTestCase(unittest.TestCase):
def test_good_process(self):
spawn = SpawnCommand(sys.executable)
d = spawn(DummyEvent())
d.addCallback(self.assertEqual, True)
return d
def test_bad_process(self):
spawn = SpawnCommand("/not/a/real/executable")
d = spawn(DummyEvent())
d.addErrback(self.assertIsInstance, failure.Failure)
return d
## Instruction:
Test that spawned process actually writes data
## Code After:
import sys
from twisted.trial import unittest
from twisted.python import failure
from twisted.python import util
from ..spawn import SpawnCommand
class DummyEvent(object):
def __init__(self, text=None):
self.text = text
class SpawnCommandProtocolTestCase(unittest.TestCase):
def test_good_process(self):
spawn = SpawnCommand(sys.executable)
d = spawn(DummyEvent())
d.addCallback(self.assertEqual, True)
return d
def test_bad_process(self):
spawn = SpawnCommand("/not/a/real/executable")
d = spawn(DummyEvent())
d.addErrback(self.assertIsInstance, failure.Failure)
return d
def test_write_data(self):
TEXT = "Test spawn process"
def read_data(result):
f = open("spawnfile.txt")
try:
self.assertEqual(f.read(), TEXT)
finally:
f.close()
spawn = SpawnCommand(util.sibpath(__file__, "test_spawn.sh"))
d = spawn(DummyEvent(TEXT))
d.addCallback(read_data)
return d
|
// ... existing code ...
from twisted.python import failure
from twisted.python import util
// ... modified code ...
class DummyEvent(object):
def __init__(self, text=None):
self.text = text
...
return d
def test_write_data(self):
TEXT = "Test spawn process"
def read_data(result):
f = open("spawnfile.txt")
try:
self.assertEqual(f.read(), TEXT)
finally:
f.close()
spawn = SpawnCommand(util.sibpath(__file__, "test_spawn.sh"))
d = spawn(DummyEvent(TEXT))
d.addCallback(read_data)
return d
// ... rest of the code ...
|
5eb67411a44366ed90a6078f29f1977013c1a39c
|
awx/main/migrations/0017_v300_prompting_migrations.py
|
awx/main/migrations/0017_v300_prompting_migrations.py
|
from __future__ import unicode_literals
from awx.main.migrations import _ask_for_variables as ask_for_variables
from awx.main.migrations import _migration_utils as migration_utils
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0016_v300_prompting_changes'),
]
operations = [
migrations.RunPython(migration_utils.set_current_apps_for_migrations),
migrations.RunPython(ask_for_variables.migrate_credential),
]
|
from __future__ import unicode_literals
from awx.main.migrations import _rbac as rbac
from awx.main.migrations import _ask_for_variables as ask_for_variables
from awx.main.migrations import _migration_utils as migration_utils
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0016_v300_prompting_changes'),
]
operations = [
migrations.RunPython(migration_utils.set_current_apps_for_migrations),
migrations.RunPython(ask_for_variables.migrate_credential),
migrations.RunPython(rbac.rebuild_role_hierarchy),
]
|
Rebuild role hierarchy after making changes in migrations
|
Rebuild role hierarchy after making changes in migrations
Signals don't fire in migrations, so gotta do this step manually
|
Python
|
apache-2.0
|
snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx
|
from __future__ import unicode_literals
+ from awx.main.migrations import _rbac as rbac
from awx.main.migrations import _ask_for_variables as ask_for_variables
from awx.main.migrations import _migration_utils as migration_utils
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0016_v300_prompting_changes'),
]
operations = [
migrations.RunPython(migration_utils.set_current_apps_for_migrations),
migrations.RunPython(ask_for_variables.migrate_credential),
+ migrations.RunPython(rbac.rebuild_role_hierarchy),
]
|
Rebuild role hierarchy after making changes in migrations
|
## Code Before:
from __future__ import unicode_literals
from awx.main.migrations import _ask_for_variables as ask_for_variables
from awx.main.migrations import _migration_utils as migration_utils
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0016_v300_prompting_changes'),
]
operations = [
migrations.RunPython(migration_utils.set_current_apps_for_migrations),
migrations.RunPython(ask_for_variables.migrate_credential),
]
## Instruction:
Rebuild role hierarchy after making changes in migrations
## Code After:
from __future__ import unicode_literals
from awx.main.migrations import _rbac as rbac
from awx.main.migrations import _ask_for_variables as ask_for_variables
from awx.main.migrations import _migration_utils as migration_utils
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0016_v300_prompting_changes'),
]
operations = [
migrations.RunPython(migration_utils.set_current_apps_for_migrations),
migrations.RunPython(ask_for_variables.migrate_credential),
migrations.RunPython(rbac.rebuild_role_hierarchy),
]
|
// ... existing code ...
from awx.main.migrations import _rbac as rbac
from awx.main.migrations import _ask_for_variables as ask_for_variables
// ... modified code ...
migrations.RunPython(ask_for_variables.migrate_credential),
migrations.RunPython(rbac.rebuild_role_hierarchy),
]
// ... rest of the code ...
|
7972c0fbaf8b46810dd36e0d824c341ea4234b47
|
swampdragon_live/models.py
|
swampdragon_live/models.py
|
from django.db.models.signals import post_save, pre_delete
from django.contrib.contenttypes.models import ContentType
from django.dispatch import receiver
from .pushers import push_new_content_for_instance
from .pushers import push_new_content_for_queryset
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
queryset_pk=instance.pk)
push_new_content_for_instance(instance_type_pk=instance_type.pk,
instance_pk=instance.pk)
@receiver(pre_delete)
def pre_delete_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
queryset_pk=instance.pk)
|
from django.db.models.signals import post_save, pre_delete
from django.contrib.contenttypes.models import ContentType
from django.dispatch import receiver
from .pushers import push_new_content_for_instance
from .pushers import push_new_content_for_queryset
@receiver(post_save)
def post_save_handler(sender, instance, created, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
if created:
push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
queryset_pk=instance.pk)
else:
push_new_content_for_instance(instance_type_pk=instance_type.pk,
instance_pk=instance.pk)
@receiver(pre_delete)
def pre_delete_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
queryset_pk=instance.pk)
|
Optimize number of updates for queryset and instance listeners
|
Optimize number of updates for queryset and instance listeners
Only push additions to queryset listeners, not instance changes.
Only push changes to instance listeners, not queryset additions.
|
Python
|
mit
|
mback2k/swampdragon-live,mback2k/swampdragon-live
|
from django.db.models.signals import post_save, pre_delete
from django.contrib.contenttypes.models import ContentType
from django.dispatch import receiver
from .pushers import push_new_content_for_instance
from .pushers import push_new_content_for_queryset
@receiver(post_save)
- def post_save_handler(sender, instance, **kwargs):
+ def post_save_handler(sender, instance, created, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
+ if created:
- push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
+ push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
- queryset_pk=instance.pk)
+ queryset_pk=instance.pk)
-
+ else:
- push_new_content_for_instance(instance_type_pk=instance_type.pk,
+ push_new_content_for_instance(instance_type_pk=instance_type.pk,
- instance_pk=instance.pk)
+ instance_pk=instance.pk)
@receiver(pre_delete)
def pre_delete_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
queryset_pk=instance.pk)
|
Optimize number of updates for queryset and instance listeners
|
## Code Before:
from django.db.models.signals import post_save, pre_delete
from django.contrib.contenttypes.models import ContentType
from django.dispatch import receiver
from .pushers import push_new_content_for_instance
from .pushers import push_new_content_for_queryset
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
queryset_pk=instance.pk)
push_new_content_for_instance(instance_type_pk=instance_type.pk,
instance_pk=instance.pk)
@receiver(pre_delete)
def pre_delete_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
queryset_pk=instance.pk)
## Instruction:
Optimize number of updates for queryset and instance listeners
## Code After:
from django.db.models.signals import post_save, pre_delete
from django.contrib.contenttypes.models import ContentType
from django.dispatch import receiver
from .pushers import push_new_content_for_instance
from .pushers import push_new_content_for_queryset
@receiver(post_save)
def post_save_handler(sender, instance, created, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
if created:
push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
queryset_pk=instance.pk)
else:
push_new_content_for_instance(instance_type_pk=instance_type.pk,
instance_pk=instance.pk)
@receiver(pre_delete)
def pre_delete_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
queryset_pk=instance.pk)
|
# ... existing code ...
@receiver(post_save)
def post_save_handler(sender, instance, created, **kwargs):
if ContentType.objects.exists():
# ... modified code ...
if created:
push_new_content_for_queryset(queryset_type_pk=instance_type.pk,
queryset_pk=instance.pk)
else:
push_new_content_for_instance(instance_type_pk=instance_type.pk,
instance_pk=instance.pk)
# ... rest of the code ...
|
75c48ecbac476fd751e55745cc2935c1dac1f138
|
longest_duplicated_substring.py
|
longest_duplicated_substring.py
|
import sys
# O(n^4) approach: generate all possible substrings and
# compare each for equality.
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
# Alternate approach with while loop here and max update outside.
# Can also break length check into function.
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
import sys
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
Move todos into issues tracking on GitHub
|
Move todos into issues tracking on GitHub
|
Python
|
mit
|
taylor-peterson/longest-duplicated-substring
|
import sys
-
- # O(n^4) approach: generate all possible substrings and
- # compare each for equality.
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
- # Alternate approach with while loop here and max update outside.
- # Can also break length check into function.
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
Move todos into issues tracking on GitHub
|
## Code Before:
import sys
# O(n^4) approach: generate all possible substrings and
# compare each for equality.
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
# Alternate approach with while loop here and max update outside.
# Can also break length check into function.
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
## Instruction:
Move todos into issues tracking on GitHub
## Code After:
import sys
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
...
...
for j in range(i+1,string_length):
for substring_length in range(string_length-j):
...
|
2e6f0934c67baf27cdf3930d48d6b733995e413f
|
benchmark/_interfaces.py
|
benchmark/_interfaces.py
|
from zope.interface import Interface
class IBackend(Interface):
"""
A backend for storing and querying the results.
"""
def store(result):
"""
Store a single benchmarking result.
:param dict result: The result in the JSON compatible format.
:return: A Deferred that produces an identifier for the stored
result.
"""
def retrieve(id):
"""
Retrieve a previously stored result by its identifier.
:param id: The identifier of the result.
:return: A Deferred that fires with the result in the JSON format.
"""
def query(filter, limit):
"""
Retrieve previously stored results that match the given filter.
The returned results will have the same values as specified in the
filter for the fields that are specified in the filter.
:param dict filter: The filter in the JSON compatible format.
:param int limit: The number of the *latest* results to return.
:return: A Deferred that fires with a list of the results
in the JSON compatible format.
"""
def delete(id):
"""
Delete a previously stored result by its identifier.
:param id: The identifier of the result.
:return: A Deferred that fires when the result is removed.
"""
|
from zope.interface import Interface
class IBackend(Interface):
"""
A backend for storing and querying the results.
"""
def store(result):
"""
Store a single benchmarking result.
:param dict result: The result in the JSON compatible format.
:return: A Deferred that produces an identifier for the stored
result.
"""
def retrieve(id):
"""
Retrieve a previously stored result by its identifier.
:param id: The identifier of the result.
:return: A Deferred that fires with the result in the JSON format.
"""
def query(filter, limit):
"""
Retrieve previously stored results that match the given filter.
The returned results will have the same values as specified in the
filter for the fields that are specified in the filter.
:param dict filter: The filter in the JSON compatible format.
:param int limit: The number of the results to return. The
results are sorted by their timestamp in descending order.
:return: A Deferred that fires with a list of the results
in the JSON compatible format.
"""
def delete(id):
"""
Delete a previously stored result by its identifier.
:param id: The identifier of the result.
:return: A Deferred that fires when the result is removed.
"""
|
Make the query docstring a bit clearer
|
Make the query docstring a bit clearer
|
Python
|
apache-2.0
|
ClusterHQ/benchmark-server,ClusterHQ/benchmark-server
|
from zope.interface import Interface
class IBackend(Interface):
"""
A backend for storing and querying the results.
"""
def store(result):
"""
Store a single benchmarking result.
:param dict result: The result in the JSON compatible format.
:return: A Deferred that produces an identifier for the stored
result.
"""
def retrieve(id):
"""
Retrieve a previously stored result by its identifier.
:param id: The identifier of the result.
:return: A Deferred that fires with the result in the JSON format.
"""
def query(filter, limit):
"""
Retrieve previously stored results that match the given filter.
The returned results will have the same values as specified in the
filter for the fields that are specified in the filter.
:param dict filter: The filter in the JSON compatible format.
- :param int limit: The number of the *latest* results to return.
+ :param int limit: The number of the results to return. The
+ results are sorted by their timestamp in descending order.
:return: A Deferred that fires with a list of the results
in the JSON compatible format.
"""
def delete(id):
"""
Delete a previously stored result by its identifier.
:param id: The identifier of the result.
:return: A Deferred that fires when the result is removed.
"""
|
Make the query docstring a bit clearer
|
## Code Before:
from zope.interface import Interface
class IBackend(Interface):
"""
A backend for storing and querying the results.
"""
def store(result):
"""
Store a single benchmarking result.
:param dict result: The result in the JSON compatible format.
:return: A Deferred that produces an identifier for the stored
result.
"""
def retrieve(id):
"""
Retrieve a previously stored result by its identifier.
:param id: The identifier of the result.
:return: A Deferred that fires with the result in the JSON format.
"""
def query(filter, limit):
"""
Retrieve previously stored results that match the given filter.
The returned results will have the same values as specified in the
filter for the fields that are specified in the filter.
:param dict filter: The filter in the JSON compatible format.
:param int limit: The number of the *latest* results to return.
:return: A Deferred that fires with a list of the results
in the JSON compatible format.
"""
def delete(id):
"""
Delete a previously stored result by its identifier.
:param id: The identifier of the result.
:return: A Deferred that fires when the result is removed.
"""
## Instruction:
Make the query docstring a bit clearer
## Code After:
from zope.interface import Interface
class IBackend(Interface):
"""
A backend for storing and querying the results.
"""
def store(result):
"""
Store a single benchmarking result.
:param dict result: The result in the JSON compatible format.
:return: A Deferred that produces an identifier for the stored
result.
"""
def retrieve(id):
"""
Retrieve a previously stored result by its identifier.
:param id: The identifier of the result.
:return: A Deferred that fires with the result in the JSON format.
"""
def query(filter, limit):
"""
Retrieve previously stored results that match the given filter.
The returned results will have the same values as specified in the
filter for the fields that are specified in the filter.
:param dict filter: The filter in the JSON compatible format.
:param int limit: The number of the results to return. The
results are sorted by their timestamp in descending order.
:return: A Deferred that fires with a list of the results
in the JSON compatible format.
"""
def delete(id):
"""
Delete a previously stored result by its identifier.
:param id: The identifier of the result.
:return: A Deferred that fires when the result is removed.
"""
|
// ... existing code ...
:param dict filter: The filter in the JSON compatible format.
:param int limit: The number of the results to return. The
results are sorted by their timestamp in descending order.
:return: A Deferred that fires with a list of the results
// ... rest of the code ...
|
534633d078fe6f81e67ead075ac31faac0c3c60d
|
tests/__init__.py
|
tests/__init__.py
|
import pycurl
def setup_package():
print('Testing %s' % pycurl.version)
|
def setup_package():
# import here, not globally, so that running
# python -m tests.appmanager
# to launch the app manager is possible without having pycurl installed
# (as the test app does not depend on pycurl)
import pycurl
print('Testing %s' % pycurl.version)
|
Make it possible to run test app without pycurl being installed
|
Make it possible to run test app without pycurl being installed
|
Python
|
lgpl-2.1
|
pycurl/pycurl,pycurl/pycurl,pycurl/pycurl
|
- import pycurl
-
def setup_package():
+ # import here, not globally, so that running
+ # python -m tests.appmanager
+ # to launch the app manager is possible without having pycurl installed
+ # (as the test app does not depend on pycurl)
+ import pycurl
+
print('Testing %s' % pycurl.version)
|
Make it possible to run test app without pycurl being installed
|
## Code Before:
import pycurl
def setup_package():
print('Testing %s' % pycurl.version)
## Instruction:
Make it possible to run test app without pycurl being installed
## Code After:
def setup_package():
# import here, not globally, so that running
# python -m tests.appmanager
# to launch the app manager is possible without having pycurl installed
# (as the test app does not depend on pycurl)
import pycurl
print('Testing %s' % pycurl.version)
|
// ... existing code ...
def setup_package():
# import here, not globally, so that running
# python -m tests.appmanager
# to launch the app manager is possible without having pycurl installed
# (as the test app does not depend on pycurl)
import pycurl
print('Testing %s' % pycurl.version)
// ... rest of the code ...
|
e3c413e9642a026dba20c91ae8865c4e193ada5b
|
tests/create_service_test.py
|
tests/create_service_test.py
|
from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
def test_append_raises_when_file_dne(self):
self.srw._append()
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
|
from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
"""I bailed out of this test, but I'll leave this here for now as an
example of how to interact with the Srv* classes."""
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
|
Remove an aborted test and add a docstring explaining why this test-less testcase is still here.
|
Remove an aborted test and add a docstring explaining why this test-less testcase is still here.
|
Python
|
apache-2.0
|
Yelp/paasta,Yelp/paasta,somic/paasta,gstarnberger/paasta,somic/paasta,gstarnberger/paasta
|
from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
+ """I bailed out of this test, but I'll leave this here for now as an
+ example of how to interact with the Srv* classes."""
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
-
- def test_append_raises_when_file_dne(self):
- self.srw._append()
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
|
Remove an aborted test and add a docstring explaining why this test-less testcase is still here.
|
## Code Before:
from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
def test_append_raises_when_file_dne(self):
self.srw._append()
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
## Instruction:
Remove an aborted test and add a docstring explaining why this test-less testcase is still here.
## Code After:
from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
"""I bailed out of this test, but I'll leave this here for now as an
example of how to interact with the Srv* classes."""
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
|
// ... existing code ...
class SrvReaderWriterTestCase(T.TestCase):
"""I bailed out of this test, but I'll leave this here for now as an
example of how to interact with the Srv* classes."""
@T.setup
// ... modified code ...
self.srw = create_service.SrvReaderWriter(paths)
// ... rest of the code ...
|
266027514c740c30c0efae5fcd1e2932f1be9933
|
perfrunner/tests/ycsb2.py
|
perfrunner/tests/ycsb2.py
|
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
self.check_num_items()
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.build_index()
self.access()
self.report_kpi()
|
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.build_index()
self.access()
self.report_kpi()
|
Check the number of items a little bit later
|
Check the number of items a little bit later
Due to MB-22749
Change-Id: Icffe46201223efa5645644ca40b99dffe4f0fb31
Reviewed-on: http://review.couchbase.org/76413
Tested-by: Build Bot <[email protected]>
Reviewed-by: Pavel Paulau <[email protected]>
|
Python
|
apache-2.0
|
couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner
|
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
- self.check_num_items()
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
+ self.check_num_items()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
+ self.check_num_items()
self.build_index()
self.access()
self.report_kpi()
|
Check the number of items a little bit later
|
## Code Before:
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
self.check_num_items()
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.build_index()
self.access()
self.report_kpi()
## Instruction:
Check the number of items a little bit later
## Code After:
from perfrunner.helpers.cbmonitor import with_stats
from perfrunner.helpers.local import clone_ycsb
from perfrunner.helpers.worker import ycsb_data_load_task, ycsb_task
from perfrunner.tests import PerfTest
from perfrunner.tests.n1ql import N1QLTest
class YCSBTest(PerfTest):
def download_ycsb(self):
clone_ycsb(repo=self.test_config.ycsb_settings.repo,
branch=self.test_config.ycsb_settings.branch)
def load(self, *args, **kwargs):
PerfTest.load(self, task=ycsb_data_load_task)
@with_stats
def access(self, *args, **kwargs):
PerfTest.access(self, task=ycsb_task)
def _report_kpi(self):
self.reporter.post_to_sf(
self.metric_helper.parse_ycsb_throughput()
)
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.access()
self.report_kpi()
class YCSBN1QLTest(YCSBTest, N1QLTest):
def run(self):
self.download_ycsb()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.build_index()
self.access()
self.report_kpi()
|
# ... existing code ...
PerfTest.load(self, task=ycsb_data_load_task)
# ... modified code ...
self.wait_for_persistence()
self.check_num_items()
...
self.wait_for_persistence()
self.check_num_items()
# ... rest of the code ...
|
591aaa938c22b797fc6bbeb5050ec489cc966a47
|
tests/run_tests.py
|
tests/run_tests.py
|
from unittest import main
from test_core import *
from test_lazy import *
if __name__ == '__main__':
main()
|
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '..')))
from unittest import main
from test_core import *
from test_lazy import *
if __name__ == '__main__':
main()
|
Make running unit tests more friendly
|
Make running unit tests more friendly
|
Python
|
mit
|
CovenantEyes/py_stringlike
|
+ import sys, os
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '..')))
from unittest import main
from test_core import *
from test_lazy import *
if __name__ == '__main__':
main()
|
Make running unit tests more friendly
|
## Code Before:
from unittest import main
from test_core import *
from test_lazy import *
if __name__ == '__main__':
main()
## Instruction:
Make running unit tests more friendly
## Code After:
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '..')))
from unittest import main
from test_core import *
from test_lazy import *
if __name__ == '__main__':
main()
|
...
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '..')))
...
|
4d1444e2f2a455e691342a82f0e116e210593411
|
s01/c01.py
|
s01/c01.py
|
"""Set 01 - Challenge 01."""
import base64
hex_string = ('49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f'
'69736f6e6f7573206d757368726f6f6d')
b64_string = b'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
def hex2b64(hex_string):
"""Convert a hex string into a base64 encoded byte string."""
hex_data = bytearray.fromhex(hex_string)
# Strip trailing newline
return base64.encodebytes(hex_data)[:-1]
assert hex2b64(hex_string) == b64_string
|
"""Set 01 - Challenge 01."""
import binascii
hex_string = ('49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f'
'69736f6e6f7573206d757368726f6f6d')
b64_string = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
def hex2b64(hex_string):
"""Convert a hex string into a base64 encoded string."""
return binascii.b2a_base64(binascii.a2b_hex(hex_string)).strip()
assert hex2b64(hex_string) == b64_string
|
Revert "Updated function to work on bytes rather than binascii functions."
|
Revert "Updated function to work on bytes rather than binascii functions."
This reverts commit 25176b64aed599059e4b552fbd76c5f4bc28434e.
|
Python
|
mit
|
sornars/matasano-challenges-py
|
"""Set 01 - Challenge 01."""
- import base64
+
+ import binascii
hex_string = ('49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f'
'69736f6e6f7573206d757368726f6f6d')
- b64_string = b'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
+ b64_string = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
def hex2b64(hex_string):
- """Convert a hex string into a base64 encoded byte string."""
+ """Convert a hex string into a base64 encoded string."""
+ return binascii.b2a_base64(binascii.a2b_hex(hex_string)).strip()
- hex_data = bytearray.fromhex(hex_string)
- # Strip trailing newline
- return base64.encodebytes(hex_data)[:-1]
assert hex2b64(hex_string) == b64_string
|
Revert "Updated function to work on bytes rather than binascii functions."
|
## Code Before:
"""Set 01 - Challenge 01."""
import base64
hex_string = ('49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f'
'69736f6e6f7573206d757368726f6f6d')
b64_string = b'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
def hex2b64(hex_string):
"""Convert a hex string into a base64 encoded byte string."""
hex_data = bytearray.fromhex(hex_string)
# Strip trailing newline
return base64.encodebytes(hex_data)[:-1]
assert hex2b64(hex_string) == b64_string
## Instruction:
Revert "Updated function to work on bytes rather than binascii functions."
## Code After:
"""Set 01 - Challenge 01."""
import binascii
hex_string = ('49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f'
'69736f6e6f7573206d757368726f6f6d')
b64_string = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
def hex2b64(hex_string):
"""Convert a hex string into a base64 encoded string."""
return binascii.b2a_base64(binascii.a2b_hex(hex_string)).strip()
assert hex2b64(hex_string) == b64_string
|
...
"""Set 01 - Challenge 01."""
import binascii
...
'69736f6e6f7573206d757368726f6f6d')
b64_string = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
...
def hex2b64(hex_string):
"""Convert a hex string into a base64 encoded string."""
return binascii.b2a_base64(binascii.a2b_hex(hex_string)).strip()
...
|
7f1db4023f2310529822d721379b1019aaf320fc
|
tablib/formats/_df.py
|
tablib/formats/_df.py
|
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
from pandas import DataFrame
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
|
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
try:
from pandas import DataFrame
except ImportError:
DataFrame = None
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
if DataFrame is None:
return False
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
if DataFrame is None:
raise NotImplementedError(
'DataFrame Format requires `pandas` to be installed.'
' Try `pip install tablib[pandas]`.')
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
|
Raise NotImplementedError if pandas is not installed
|
Raise NotImplementedError if pandas is not installed
|
Python
|
mit
|
kennethreitz/tablib
|
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
+ try:
- from pandas import DataFrame
+ from pandas import DataFrame
+ except ImportError:
+ DataFrame = None
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
+ if DataFrame is None:
+ return False
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
+ if DataFrame is None:
+ raise NotImplementedError(
+ 'DataFrame Format requires `pandas` to be installed.'
+ ' Try `pip install tablib[pandas]`.')
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
|
Raise NotImplementedError if pandas is not installed
|
## Code Before:
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
from pandas import DataFrame
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
## Instruction:
Raise NotImplementedError if pandas is not installed
## Code After:
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
try:
from pandas import DataFrame
except ImportError:
DataFrame = None
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
if DataFrame is None:
return False
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
if DataFrame is None:
raise NotImplementedError(
'DataFrame Format requires `pandas` to be installed.'
' Try `pip install tablib[pandas]`.')
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
|
# ... existing code ...
try:
from pandas import DataFrame
except ImportError:
DataFrame = None
# ... modified code ...
"""Returns True if given stream is a DataFrame."""
if DataFrame is None:
return False
try:
...
"""Returns DataFrame representation of DataBook."""
if DataFrame is None:
raise NotImplementedError(
'DataFrame Format requires `pandas` to be installed.'
' Try `pip install tablib[pandas]`.')
dataframe = DataFrame(dset.dict, columns=dset.headers)
# ... rest of the code ...
|
10c6112dd343901b502c31655a001e612ed6e441
|
api/logs/permissions.py
|
api/logs/permissions.py
|
from rest_framework import permissions
from website.models import Node, NodeLog
from api.nodes.permissions import ContributorOrPublic
from api.base.utils import get_object_or_error
class ContributorOrPublicForLogs(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
assert isinstance(obj, (NodeLog)), 'obj must be a NodeLog, got {}'.format(obj)
for node_id in obj._backrefs['logged']['node']['logs']:
node = get_object_or_error(Node, node_id, display_name='node')
if ContributorOrPublic().has_object_permission(request, view, node):
return True
return False
|
from rest_framework import permissions
from website.models import Node, NodeLog
from api.nodes.permissions import ContributorOrPublic
from api.base.utils import get_object_or_error
class ContributorOrPublicForLogs(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
assert isinstance(obj, (NodeLog)), 'obj must be a NodeLog, got {}'.format(obj)
if obj._backrefs.get('logged'):
for node_id in obj._backrefs['logged']['node']['logs']:
node = get_object_or_error(Node, node_id, display_name='node')
if ContributorOrPublic().has_object_permission(request, view, node):
return True
if getattr(obj, 'node'):
if ContributorOrPublic().has_object_permission(request, view, obj.node):
return True
return False
|
Add case for when there are no node backrefs on logs. Again, this whole method will change when eliminating backrefs from nodelogs is merged.
|
Add case for when there are no node backrefs on logs. Again, this whole method will change when eliminating backrefs from nodelogs is merged.
|
Python
|
apache-2.0
|
doublebits/osf.io,mluo613/osf.io,cwisecarver/osf.io,billyhunt/osf.io,baylee-d/osf.io,caneruguz/osf.io,mattclark/osf.io,Johnetordoff/osf.io,kwierman/osf.io,kwierman/osf.io,amyshi188/osf.io,acshi/osf.io,mfraezz/osf.io,zamattiac/osf.io,pattisdr/osf.io,samchrisinger/osf.io,RomanZWang/osf.io,hmoco/osf.io,alexschiller/osf.io,chrisseto/osf.io,felliott/osf.io,laurenrevere/osf.io,chrisseto/osf.io,alexschiller/osf.io,abought/osf.io,felliott/osf.io,mluo613/osf.io,TomBaxter/osf.io,abought/osf.io,TomHeatwole/osf.io,RomanZWang/osf.io,doublebits/osf.io,emetsger/osf.io,mluo613/osf.io,kwierman/osf.io,aaxelb/osf.io,mluke93/osf.io,caneruguz/osf.io,Nesiehr/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,billyhunt/osf.io,kwierman/osf.io,binoculars/osf.io,mluke93/osf.io,billyhunt/osf.io,doublebits/osf.io,chennan47/osf.io,Nesiehr/osf.io,saradbowman/osf.io,hmoco/osf.io,chennan47/osf.io,DanielSBrown/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,cslzchen/osf.io,wearpants/osf.io,zachjanicki/osf.io,monikagrabowska/osf.io,adlius/osf.io,SSJohns/osf.io,icereval/osf.io,alexschiller/osf.io,mattclark/osf.io,wearpants/osf.io,zachjanicki/osf.io,jnayak1/osf.io,jnayak1/osf.io,chrisseto/osf.io,baylee-d/osf.io,amyshi188/osf.io,billyhunt/osf.io,samchrisinger/osf.io,erinspace/osf.io,rdhyee/osf.io,crcresearch/osf.io,hmoco/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,doublebits/osf.io,SSJohns/osf.io,cwisecarver/osf.io,RomanZWang/osf.io,kch8qx/osf.io,erinspace/osf.io,kch8qx/osf.io,wearpants/osf.io,rdhyee/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,HalcyonChimera/osf.io,sloria/osf.io,cslzchen/osf.io,doublebits/osf.io,Johnetordoff/osf.io,icereval/osf.io,samchrisinger/osf.io,DanielSBrown/osf.io,crcresearch/osf.io,aaxelb/osf.io,emetsger/osf.io,Johnetordoff/osf.io,jnayak1/osf.io,kch8qx/osf.io,laurenrevere/osf.io,icereval/osf.io,emetsger/osf.io,leb2dg/osf.io,abought/osf.io,CenterForOpenScience/osf.io,rdhyee/osf.io,billyhunt/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,adlius/osf.io,acshi/osf.io,alexschiller/osf.io,TomBaxter/osf.io,RomanZWang/osf.io,caneruguz/osf.io,adlius/osf.io,jnayak1/osf.io,amyshi188/osf.io,asanfilippo7/osf.io,cwisecarver/osf.io,acshi/osf.io,DanielSBrown/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,SSJohns/osf.io,zamattiac/osf.io,mfraezz/osf.io,TomBaxter/osf.io,caseyrollins/osf.io,kch8qx/osf.io,leb2dg/osf.io,cwisecarver/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,caseyrollins/osf.io,asanfilippo7/osf.io,TomHeatwole/osf.io,brianjgeiger/osf.io,mluke93/osf.io,abought/osf.io,acshi/osf.io,alexschiller/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,asanfilippo7/osf.io,mluke93/osf.io,adlius/osf.io,laurenrevere/osf.io,TomHeatwole/osf.io,HalcyonChimera/osf.io,zachjanicki/osf.io,leb2dg/osf.io,felliott/osf.io,chennan47/osf.io,pattisdr/osf.io,TomHeatwole/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,acshi/osf.io,caseyrollins/osf.io,emetsger/osf.io,cslzchen/osf.io,wearpants/osf.io,mluo613/osf.io,DanielSBrown/osf.io,binoculars/osf.io,erinspace/osf.io,mattclark/osf.io,asanfilippo7/osf.io,hmoco/osf.io,zamattiac/osf.io,Johnetordoff/osf.io,zachjanicki/osf.io,amyshi188/osf.io,felliott/osf.io,SSJohns/osf.io,HalcyonChimera/osf.io,Nesiehr/osf.io,kch8qx/osf.io,samchrisinger/osf.io,chrisseto/osf.io,crcresearch/osf.io,sloria/osf.io,RomanZWang/osf.io,binoculars/osf.io,aaxelb/osf.io,rdhyee/osf.io
|
from rest_framework import permissions
from website.models import Node, NodeLog
from api.nodes.permissions import ContributorOrPublic
from api.base.utils import get_object_or_error
class ContributorOrPublicForLogs(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
assert isinstance(obj, (NodeLog)), 'obj must be a NodeLog, got {}'.format(obj)
+ if obj._backrefs.get('logged'):
- for node_id in obj._backrefs['logged']['node']['logs']:
+ for node_id in obj._backrefs['logged']['node']['logs']:
- node = get_object_or_error(Node, node_id, display_name='node')
+ node = get_object_or_error(Node, node_id, display_name='node')
- if ContributorOrPublic().has_object_permission(request, view, node):
+ if ContributorOrPublic().has_object_permission(request, view, node):
+ return True
+
+ if getattr(obj, 'node'):
+ if ContributorOrPublic().has_object_permission(request, view, obj.node):
return True
+
return False
|
Add case for when there are no node backrefs on logs. Again, this whole method will change when eliminating backrefs from nodelogs is merged.
|
## Code Before:
from rest_framework import permissions
from website.models import Node, NodeLog
from api.nodes.permissions import ContributorOrPublic
from api.base.utils import get_object_or_error
class ContributorOrPublicForLogs(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
assert isinstance(obj, (NodeLog)), 'obj must be a NodeLog, got {}'.format(obj)
for node_id in obj._backrefs['logged']['node']['logs']:
node = get_object_or_error(Node, node_id, display_name='node')
if ContributorOrPublic().has_object_permission(request, view, node):
return True
return False
## Instruction:
Add case for when there are no node backrefs on logs. Again, this whole method will change when eliminating backrefs from nodelogs is merged.
## Code After:
from rest_framework import permissions
from website.models import Node, NodeLog
from api.nodes.permissions import ContributorOrPublic
from api.base.utils import get_object_or_error
class ContributorOrPublicForLogs(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
assert isinstance(obj, (NodeLog)), 'obj must be a NodeLog, got {}'.format(obj)
if obj._backrefs.get('logged'):
for node_id in obj._backrefs['logged']['node']['logs']:
node = get_object_or_error(Node, node_id, display_name='node')
if ContributorOrPublic().has_object_permission(request, view, node):
return True
if getattr(obj, 'node'):
if ContributorOrPublic().has_object_permission(request, view, obj.node):
return True
return False
|
// ... existing code ...
if obj._backrefs.get('logged'):
for node_id in obj._backrefs['logged']['node']['logs']:
node = get_object_or_error(Node, node_id, display_name='node')
if ContributorOrPublic().has_object_permission(request, view, node):
return True
if getattr(obj, 'node'):
if ContributorOrPublic().has_object_permission(request, view, obj.node):
return True
return False
// ... rest of the code ...
|
52933f030b246615429ac74f7f156b7a33225d7f
|
opengrid/tests/test_plotting.py
|
opengrid/tests/test_plotting.py
|
import unittest
class PlotStyleTest(unittest.TestCase):
def test_default(self):
from opengrid.library.plotting import plot_style
plt = plot_style()
class CarpetTest(unittest.TestCase):
def test_default(self):
import numpy as np
import pandas as pd
from opengrid.library import plotting
index = pd.date_range('2015-1-1', '2015-12-31', freq='h')
ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc')
plotting.carpet(ser)
if __name__ == '__main__':
unittest.main()
|
import unittest
import pandas as pd
from opengrid.library import plotting
class PlotStyleTest(unittest.TestCase):
def test_default(self):
plt = plotting.plot_style()
class CarpetTest(unittest.TestCase):
def test_default(self):
import numpy as np
index = pd.date_range('2015-1-1', '2015-12-31', freq='h')
ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc')
assert plotting.carpet(ser) is not None
def test_empty(self):
assert plotting.carpet(pd.Series(index=list('abc'))) is None
if __name__ == '__main__':
unittest.main()
|
Resolve RuntimeError: Invalid DISPLAY variable - tst
|
[BLD] Resolve RuntimeError: Invalid DISPLAY variable - tst
|
Python
|
apache-2.0
|
opengridcc/opengrid
|
import unittest
+ import pandas as pd
+ from opengrid.library import plotting
class PlotStyleTest(unittest.TestCase):
def test_default(self):
- from opengrid.library.plotting import plot_style
- plt = plot_style()
+ plt = plotting.plot_style()
class CarpetTest(unittest.TestCase):
def test_default(self):
import numpy as np
- import pandas as pd
- from opengrid.library import plotting
index = pd.date_range('2015-1-1', '2015-12-31', freq='h')
ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc')
- plotting.carpet(ser)
+ assert plotting.carpet(ser) is not None
+
+ def test_empty(self):
+ assert plotting.carpet(pd.Series(index=list('abc'))) is None
if __name__ == '__main__':
unittest.main()
|
Resolve RuntimeError: Invalid DISPLAY variable - tst
|
## Code Before:
import unittest
class PlotStyleTest(unittest.TestCase):
def test_default(self):
from opengrid.library.plotting import plot_style
plt = plot_style()
class CarpetTest(unittest.TestCase):
def test_default(self):
import numpy as np
import pandas as pd
from opengrid.library import plotting
index = pd.date_range('2015-1-1', '2015-12-31', freq='h')
ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc')
plotting.carpet(ser)
if __name__ == '__main__':
unittest.main()
## Instruction:
Resolve RuntimeError: Invalid DISPLAY variable - tst
## Code After:
import unittest
import pandas as pd
from opengrid.library import plotting
class PlotStyleTest(unittest.TestCase):
def test_default(self):
plt = plotting.plot_style()
class CarpetTest(unittest.TestCase):
def test_default(self):
import numpy as np
index = pd.date_range('2015-1-1', '2015-12-31', freq='h')
ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc')
assert plotting.carpet(ser) is not None
def test_empty(self):
assert plotting.carpet(pd.Series(index=list('abc'))) is None
if __name__ == '__main__':
unittest.main()
|
...
import unittest
import pandas as pd
from opengrid.library import plotting
...
def test_default(self):
plt = plotting.plot_style()
...
import numpy as np
index = pd.date_range('2015-1-1', '2015-12-31', freq='h')
...
ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc')
assert plotting.carpet(ser) is not None
def test_empty(self):
assert plotting.carpet(pd.Series(index=list('abc'))) is None
...
|
08c864a914b7996115f6b265cddb3c96c40e4fb5
|
global_functions.py
|
global_functions.py
|
import random
import hashlib
def get_random_id():
# generate a random unique integer
random_id = random.randrange(1, 100000000)
return random_id
def get_attributes_from_class(instance_of_class):
members = [attr for attr in dir(instance_of_class) if
not callable(getattr(instance_of_class, attr)) and not attr.startswith("__")]
attributes_dict = dict()
for member in members:
attributes_dict[member] = getattr(instance_of_class, member)
return attributes_dict
def sha1_hash(value):
# convert string to bytes
value = str.encode(value)
# calculate a SHA1 hash
hash_object = hashlib.sha1(value)
hashed_value = hash_object.hexdigest()
return hashed_value
|
import random
import hashlib
def get_random_id():
"""generates a random integer value between 1 and 100000000
:return
(int): randomly generated integer
"""
# generate a random unique integer
random_id = random.randrange(1, 100000000)
return random_id
def get_attributes_from_class(instance_of_class):
"""Get attributes from a class objects and returns a dictionary containing
the attribute name as (key) and the attribute value as (value)
:arg
instance_of_class: An object
:return
(dict): Attribute name as (key) and the attribute value as (value)
"""
# get a list of member attributes of class
members = [attr for attr in dir(instance_of_class) if
not callable(getattr(instance_of_class, attr)) and not attr.startswith("__")]
# loop through members array and add the member value to the attributes dictionary
attributes_dict = dict()
for member in members:
attributes_dict[member] = getattr(instance_of_class, member)
return attributes_dict
def sha1_hash(value):
"""Calculates the SHA1 has of a string
:arg:
value (str): String to be hashed
:return
(str): SHA1 hash
"""
# convert string to bytes
value = str.encode(value)
# calculate a SHA1 hash
hash_object = hashlib.sha1(value)
hashed_value = hash_object.hexdigest()
return hashed_value
|
Add descriptive docstring comments global functions
|
[UPDATE] Add descriptive docstring comments global functions
|
Python
|
mit
|
EinsteinCarrey/Shoppinglist,EinsteinCarrey/Shoppinglist,EinsteinCarrey/Shoppinglist
|
import random
import hashlib
def get_random_id():
+ """generates a random integer value between 1 and 100000000
+ :return
+ (int): randomly generated integer
+ """
# generate a random unique integer
random_id = random.randrange(1, 100000000)
return random_id
def get_attributes_from_class(instance_of_class):
+ """Get attributes from a class objects and returns a dictionary containing
+ the attribute name as (key) and the attribute value as (value)
+
+ :arg
+ instance_of_class: An object
+
+ :return
+ (dict): Attribute name as (key) and the attribute value as (value)
+
+ """
+ # get a list of member attributes of class
members = [attr for attr in dir(instance_of_class) if
not callable(getattr(instance_of_class, attr)) and not attr.startswith("__")]
+ # loop through members array and add the member value to the attributes dictionary
attributes_dict = dict()
for member in members:
attributes_dict[member] = getattr(instance_of_class, member)
return attributes_dict
def sha1_hash(value):
+ """Calculates the SHA1 has of a string
+
+ :arg:
+ value (str): String to be hashed
+
+ :return
+ (str): SHA1 hash
+ """
# convert string to bytes
value = str.encode(value)
# calculate a SHA1 hash
hash_object = hashlib.sha1(value)
hashed_value = hash_object.hexdigest()
return hashed_value
|
Add descriptive docstring comments global functions
|
## Code Before:
import random
import hashlib
def get_random_id():
# generate a random unique integer
random_id = random.randrange(1, 100000000)
return random_id
def get_attributes_from_class(instance_of_class):
members = [attr for attr in dir(instance_of_class) if
not callable(getattr(instance_of_class, attr)) and not attr.startswith("__")]
attributes_dict = dict()
for member in members:
attributes_dict[member] = getattr(instance_of_class, member)
return attributes_dict
def sha1_hash(value):
# convert string to bytes
value = str.encode(value)
# calculate a SHA1 hash
hash_object = hashlib.sha1(value)
hashed_value = hash_object.hexdigest()
return hashed_value
## Instruction:
Add descriptive docstring comments global functions
## Code After:
import random
import hashlib
def get_random_id():
"""generates a random integer value between 1 and 100000000
:return
(int): randomly generated integer
"""
# generate a random unique integer
random_id = random.randrange(1, 100000000)
return random_id
def get_attributes_from_class(instance_of_class):
"""Get attributes from a class objects and returns a dictionary containing
the attribute name as (key) and the attribute value as (value)
:arg
instance_of_class: An object
:return
(dict): Attribute name as (key) and the attribute value as (value)
"""
# get a list of member attributes of class
members = [attr for attr in dir(instance_of_class) if
not callable(getattr(instance_of_class, attr)) and not attr.startswith("__")]
# loop through members array and add the member value to the attributes dictionary
attributes_dict = dict()
for member in members:
attributes_dict[member] = getattr(instance_of_class, member)
return attributes_dict
def sha1_hash(value):
"""Calculates the SHA1 has of a string
:arg:
value (str): String to be hashed
:return
(str): SHA1 hash
"""
# convert string to bytes
value = str.encode(value)
# calculate a SHA1 hash
hash_object = hashlib.sha1(value)
hashed_value = hash_object.hexdigest()
return hashed_value
|
# ... existing code ...
def get_random_id():
"""generates a random integer value between 1 and 100000000
:return
(int): randomly generated integer
"""
# generate a random unique integer
# ... modified code ...
def get_attributes_from_class(instance_of_class):
"""Get attributes from a class objects and returns a dictionary containing
the attribute name as (key) and the attribute value as (value)
:arg
instance_of_class: An object
:return
(dict): Attribute name as (key) and the attribute value as (value)
"""
# get a list of member attributes of class
members = [attr for attr in dir(instance_of_class) if
...
# loop through members array and add the member value to the attributes dictionary
attributes_dict = dict()
...
def sha1_hash(value):
"""Calculates the SHA1 has of a string
:arg:
value (str): String to be hashed
:return
(str): SHA1 hash
"""
# convert string to bytes
# ... rest of the code ...
|
c7511d81236f2a28019d8d8e103b03e0d1150e32
|
django_website/blog/admin.py
|
django_website/blog/admin.py
|
from __future__ import absolute_import
from django.contrib import admin
from .models import Entry
admin.site.register(Entry,
list_display = ('headline', 'pub_date', 'is_active', 'is_published', 'author'),
list_filter = ('is_active',),
exclude = ('summary_html', 'body_html'),
prepopulated_fields = {"slug": ("headline",)}
)
|
from __future__ import absolute_import
from django.contrib import admin
from .models import Entry
class EntryAdmin(admin.ModelAdmin):
list_display = ('headline', 'pub_date', 'is_active', 'is_published', 'author')
list_filter = ('is_active',)
exclude = ('summary_html', 'body_html')
prepopulated_fields = {"slug": ("headline",)}
admin.site.register(Entry, EntryAdmin)
|
Use proper ModelAdmin for blog entry
|
Use proper ModelAdmin for blog entry
|
Python
|
bsd-3-clause
|
khkaminska/djangoproject.com,nanuxbe/django,rmoorman/djangoproject.com,gnarf/djangoproject.com,relekang/djangoproject.com,relekang/djangoproject.com,django/djangoproject.com,alawnchen/djangoproject.com,vxvinh1511/djangoproject.com,nanuxbe/django,nanuxbe/django,django/djangoproject.com,xavierdutreilh/djangoproject.com,gnarf/djangoproject.com,django/djangoproject.com,relekang/djangoproject.com,alawnchen/djangoproject.com,khkaminska/djangoproject.com,alawnchen/djangoproject.com,django/djangoproject.com,rmoorman/djangoproject.com,relekang/djangoproject.com,hassanabidpk/djangoproject.com,rmoorman/djangoproject.com,rmoorman/djangoproject.com,xavierdutreilh/djangoproject.com,khkaminska/djangoproject.com,django/djangoproject.com,xavierdutreilh/djangoproject.com,xavierdutreilh/djangoproject.com,django/djangoproject.com,hassanabidpk/djangoproject.com,vxvinh1511/djangoproject.com,gnarf/djangoproject.com,hassanabidpk/djangoproject.com,hassanabidpk/djangoproject.com,nanuxbe/django,vxvinh1511/djangoproject.com,gnarf/djangoproject.com,vxvinh1511/djangoproject.com,khkaminska/djangoproject.com,alawnchen/djangoproject.com
|
from __future__ import absolute_import
from django.contrib import admin
from .models import Entry
- admin.site.register(Entry,
+ class EntryAdmin(admin.ModelAdmin):
- list_display = ('headline', 'pub_date', 'is_active', 'is_published', 'author'),
+ list_display = ('headline', 'pub_date', 'is_active', 'is_published', 'author')
- list_filter = ('is_active',),
+ list_filter = ('is_active',)
- exclude = ('summary_html', 'body_html'),
+ exclude = ('summary_html', 'body_html')
prepopulated_fields = {"slug": ("headline",)}
- )
+ admin.site.register(Entry, EntryAdmin)
+
|
Use proper ModelAdmin for blog entry
|
## Code Before:
from __future__ import absolute_import
from django.contrib import admin
from .models import Entry
admin.site.register(Entry,
list_display = ('headline', 'pub_date', 'is_active', 'is_published', 'author'),
list_filter = ('is_active',),
exclude = ('summary_html', 'body_html'),
prepopulated_fields = {"slug": ("headline",)}
)
## Instruction:
Use proper ModelAdmin for blog entry
## Code After:
from __future__ import absolute_import
from django.contrib import admin
from .models import Entry
class EntryAdmin(admin.ModelAdmin):
list_display = ('headline', 'pub_date', 'is_active', 'is_published', 'author')
list_filter = ('is_active',)
exclude = ('summary_html', 'body_html')
prepopulated_fields = {"slug": ("headline",)}
admin.site.register(Entry, EntryAdmin)
|
// ... existing code ...
class EntryAdmin(admin.ModelAdmin):
list_display = ('headline', 'pub_date', 'is_active', 'is_published', 'author')
list_filter = ('is_active',)
exclude = ('summary_html', 'body_html')
prepopulated_fields = {"slug": ("headline",)}
admin.site.register(Entry, EntryAdmin)
// ... rest of the code ...
|
de958b9fc68ad6209749edbfe2bdde0ef68cf3c8
|
experiments/middleware.py
|
experiments/middleware.py
|
from experiments.utils import participant
class ExperimentsRetentionMiddleware(object):
def process_response(self, request, response):
# We detect widgets by relying on the fact that they are flagged as being embedable, and don't include these in visit tracking
if getattr(response, 'xframe_options_exempt', False):
return response
experiment_user = participant(request)
experiment_user.visit()
return response
|
from experiments.utils import participant
class ExperimentsRetentionMiddleware(object):
def process_response(self, request, response):
# Don't track, failed pages, ajax requests, logged out users or widget impressions.
# We detect widgets by relying on the fact that they are flagged as being embedable
if response.status_code != 200 or request.is_ajax() or getattr(response, 'xframe_options_exempt', False):
return response
experiment_user = participant(request)
experiment_user.visit()
return response
|
Revert "tidy up ajax page loads so they count towards experiments"
|
Revert "tidy up ajax page loads so they count towards experiments"
This reverts commit a37cacb96c4021fcc2f9e23e024d8947bb4e644f.
|
Python
|
mit
|
mixcloud/django-experiments,bjarnoldus/django-experiments,bjarnoldus/django-experiments,robertobarreda/django-experiments,mixcloud/django-experiments,robertobarreda/django-experiments,squamous/django-experiments,squamous/django-experiments,uhuramedia/django-experiments,mixcloud/django-experiments,bjarnoldus/django-experiments,uhuramedia/django-experiments,squamous/django-experiments,uhuramedia/django-experiments,robertobarreda/django-experiments
|
from experiments.utils import participant
class ExperimentsRetentionMiddleware(object):
def process_response(self, request, response):
+ # Don't track, failed pages, ajax requests, logged out users or widget impressions.
- # We detect widgets by relying on the fact that they are flagged as being embedable, and don't include these in visit tracking
+ # We detect widgets by relying on the fact that they are flagged as being embedable
- if getattr(response, 'xframe_options_exempt', False):
+ if response.status_code != 200 or request.is_ajax() or getattr(response, 'xframe_options_exempt', False):
return response
experiment_user = participant(request)
experiment_user.visit()
return response
|
Revert "tidy up ajax page loads so they count towards experiments"
|
## Code Before:
from experiments.utils import participant
class ExperimentsRetentionMiddleware(object):
def process_response(self, request, response):
# We detect widgets by relying on the fact that they are flagged as being embedable, and don't include these in visit tracking
if getattr(response, 'xframe_options_exempt', False):
return response
experiment_user = participant(request)
experiment_user.visit()
return response
## Instruction:
Revert "tidy up ajax page loads so they count towards experiments"
## Code After:
from experiments.utils import participant
class ExperimentsRetentionMiddleware(object):
def process_response(self, request, response):
# Don't track, failed pages, ajax requests, logged out users or widget impressions.
# We detect widgets by relying on the fact that they are flagged as being embedable
if response.status_code != 200 or request.is_ajax() or getattr(response, 'xframe_options_exempt', False):
return response
experiment_user = participant(request)
experiment_user.visit()
return response
|
// ... existing code ...
def process_response(self, request, response):
# Don't track, failed pages, ajax requests, logged out users or widget impressions.
# We detect widgets by relying on the fact that they are flagged as being embedable
if response.status_code != 200 or request.is_ajax() or getattr(response, 'xframe_options_exempt', False):
return response
// ... rest of the code ...
|
b3cbd97738c03975f89cc0264cfd47ea44b9728e
|
annoycode.py
|
annoycode.py
|
from data import Data
if __name__ == "__main__":
data = Data()
if not data.load() or not data.hasMatches():
print("Use trainer.py to generate data for use.")
exit(-1)
string = "A B C ! -"
(newString, subs) = data.subMatches(string)
print("Input: ", string)
print(" ", string.encode("utf-8"))
print("Output: ", newString)
print(" ", newString.encode("utf-8"))
print("{} substitutions".format(subs))
|
from data import Data
if __name__ == "__main__":
data = Data()
if not data.load() or not data.hasMatches():
print("Use trainer.py to generate data for use.")
exit(-1)
string = "ABC!-"
stringEnc = string.encode("utf-8")
(newString, subs) = data.subMatches(string)
newStringEnc = newString.encode("utf-8")
inCnt = len(stringEnc)
outCnt = len(newStringEnc)
incPerc = float(outCnt) / float(inCnt) * 100
print("Input: ", string)
print(" ", stringEnc)
print("Output: ", newString)
print(" ", newStringEnc)
print("{} substitutions".format(subs))
print("{} -> {} bytes, +{}%".format(inCnt, outCnt, incPerc))
|
Print stats on in/out byte count and increase in percent.
|
ac: Print stats on in/out byte count and increase in percent.
|
Python
|
mit
|
netromdk/annoycode
|
from data import Data
if __name__ == "__main__":
data = Data()
if not data.load() or not data.hasMatches():
print("Use trainer.py to generate data for use.")
exit(-1)
- string = "A B C ! -"
+ string = "ABC!-"
+ stringEnc = string.encode("utf-8")
(newString, subs) = data.subMatches(string)
+ newStringEnc = newString.encode("utf-8")
+
+ inCnt = len(stringEnc)
+ outCnt = len(newStringEnc)
+ incPerc = float(outCnt) / float(inCnt) * 100
print("Input: ", string)
- print(" ", string.encode("utf-8"))
+ print(" ", stringEnc)
print("Output: ", newString)
- print(" ", newString.encode("utf-8"))
+ print(" ", newStringEnc)
print("{} substitutions".format(subs))
+ print("{} -> {} bytes, +{}%".format(inCnt, outCnt, incPerc))
|
Print stats on in/out byte count and increase in percent.
|
## Code Before:
from data import Data
if __name__ == "__main__":
data = Data()
if not data.load() or not data.hasMatches():
print("Use trainer.py to generate data for use.")
exit(-1)
string = "A B C ! -"
(newString, subs) = data.subMatches(string)
print("Input: ", string)
print(" ", string.encode("utf-8"))
print("Output: ", newString)
print(" ", newString.encode("utf-8"))
print("{} substitutions".format(subs))
## Instruction:
Print stats on in/out byte count and increase in percent.
## Code After:
from data import Data
if __name__ == "__main__":
data = Data()
if not data.load() or not data.hasMatches():
print("Use trainer.py to generate data for use.")
exit(-1)
string = "ABC!-"
stringEnc = string.encode("utf-8")
(newString, subs) = data.subMatches(string)
newStringEnc = newString.encode("utf-8")
inCnt = len(stringEnc)
outCnt = len(newStringEnc)
incPerc = float(outCnt) / float(inCnt) * 100
print("Input: ", string)
print(" ", stringEnc)
print("Output: ", newString)
print(" ", newStringEnc)
print("{} substitutions".format(subs))
print("{} -> {} bytes, +{}%".format(inCnt, outCnt, incPerc))
|
# ... existing code ...
string = "ABC!-"
stringEnc = string.encode("utf-8")
(newString, subs) = data.subMatches(string)
newStringEnc = newString.encode("utf-8")
inCnt = len(stringEnc)
outCnt = len(newStringEnc)
incPerc = float(outCnt) / float(inCnt) * 100
# ... modified code ...
print("Input: ", string)
print(" ", stringEnc)
print("Output: ", newString)
print(" ", newStringEnc)
print("{} substitutions".format(subs))
print("{} -> {} bytes, +{}%".format(inCnt, outCnt, incPerc))
# ... rest of the code ...
|
4f7382303d56871b2b174e291b47b238777f5d32
|
yubico/yubico_exceptions.py
|
yubico/yubico_exceptions.py
|
__all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'InvalidValidationResponse',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):
self.status_code = status_code
def __str__(self):
return ('Yubico server returned the following status code: %s' %
(self.status_code))
class InvalidClientIdError(YubicoError):
def __init__(self, client_id):
self.client_id = client_id
def __str__(self):
return 'The client with ID %s does not exist' % (self.client_id)
class InvalidValidationResponse(YubicoError):
def __init__(self, reason, response, parameters=None):
self.reason = reason
self.response = response
self.parameters = parameters
def __str__(self):
return self.reason
class SignatureVerificationError(YubicoError):
def __init__(self, generated_signature, response_signature):
self.generated_signature = generated_signature
self.response_signature = response_signature
def __str__(self):
return repr('Server response message signature verification failed' +
'(expected %s, got %s)' % (self.generated_signature,
self.response_signature))
|
__all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'InvalidValidationResponse',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):
self.status_code = status_code
def __str__(self):
return ('Yubico server returned the following status code: %s' %
(self.status_code))
class InvalidClientIdError(YubicoError):
def __init__(self, client_id):
self.client_id = client_id
def __str__(self):
return 'The client with ID %s does not exist' % (self.client_id)
class InvalidValidationResponse(YubicoError):
def __init__(self, reason, response, parameters=None):
self.reason = reason
self.response = response
self.parameters = parameters
self.message = self.reason
def __str__(self):
return self.reason
class SignatureVerificationError(YubicoError):
def __init__(self, generated_signature, response_signature):
self.generated_signature = generated_signature
self.response_signature = response_signature
def __str__(self):
return repr('Server response message signature verification failed' +
'(expected %s, got %s)' % (self.generated_signature,
self.response_signature))
|
Set message attribute on InvalidValidationResponse error class.
|
Set message attribute on InvalidValidationResponse error class.
|
Python
|
bsd-3-clause
|
Kami/python-yubico-client
|
__all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'InvalidValidationResponse',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):
self.status_code = status_code
def __str__(self):
return ('Yubico server returned the following status code: %s' %
(self.status_code))
class InvalidClientIdError(YubicoError):
def __init__(self, client_id):
self.client_id = client_id
def __str__(self):
return 'The client with ID %s does not exist' % (self.client_id)
class InvalidValidationResponse(YubicoError):
def __init__(self, reason, response, parameters=None):
self.reason = reason
self.response = response
self.parameters = parameters
+ self.message = self.reason
def __str__(self):
return self.reason
class SignatureVerificationError(YubicoError):
def __init__(self, generated_signature, response_signature):
self.generated_signature = generated_signature
self.response_signature = response_signature
def __str__(self):
return repr('Server response message signature verification failed' +
'(expected %s, got %s)' % (self.generated_signature,
self.response_signature))
|
Set message attribute on InvalidValidationResponse error class.
|
## Code Before:
__all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'InvalidValidationResponse',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):
self.status_code = status_code
def __str__(self):
return ('Yubico server returned the following status code: %s' %
(self.status_code))
class InvalidClientIdError(YubicoError):
def __init__(self, client_id):
self.client_id = client_id
def __str__(self):
return 'The client with ID %s does not exist' % (self.client_id)
class InvalidValidationResponse(YubicoError):
def __init__(self, reason, response, parameters=None):
self.reason = reason
self.response = response
self.parameters = parameters
def __str__(self):
return self.reason
class SignatureVerificationError(YubicoError):
def __init__(self, generated_signature, response_signature):
self.generated_signature = generated_signature
self.response_signature = response_signature
def __str__(self):
return repr('Server response message signature verification failed' +
'(expected %s, got %s)' % (self.generated_signature,
self.response_signature))
## Instruction:
Set message attribute on InvalidValidationResponse error class.
## Code After:
__all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'InvalidValidationResponse',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):
self.status_code = status_code
def __str__(self):
return ('Yubico server returned the following status code: %s' %
(self.status_code))
class InvalidClientIdError(YubicoError):
def __init__(self, client_id):
self.client_id = client_id
def __str__(self):
return 'The client with ID %s does not exist' % (self.client_id)
class InvalidValidationResponse(YubicoError):
def __init__(self, reason, response, parameters=None):
self.reason = reason
self.response = response
self.parameters = parameters
self.message = self.reason
def __str__(self):
return self.reason
class SignatureVerificationError(YubicoError):
def __init__(self, generated_signature, response_signature):
self.generated_signature = generated_signature
self.response_signature = response_signature
def __str__(self):
return repr('Server response message signature verification failed' +
'(expected %s, got %s)' % (self.generated_signature,
self.response_signature))
|
...
self.parameters = parameters
self.message = self.reason
...
|
8d50750ae94e2c94059dcbf1009dd46441d44842
|
__init__.py
|
__init__.py
|
from flask import Flask, render_template
from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface
import configparser
from .momentjs import momentjs
app = Flask(__name__)
# Security
WTF_CSRF_ENABLED = True
app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR'
app.jinja_env.globals['momentjs'] = momentjs
# App Config
config = configparser.ConfigParser()
config.read('config/config.ini')
app.config['MONGODB_DB'] = config['MongoDB']['db_name']
app.config['MONGODB_HOST'] = config['MongoDB']['host']
app.config['MONGODB_PORT'] = int(config['MongoDB']['port'])
app.config['MONGODB_USERNAME'] = config['MongoDB']['username']
app.config['MONGODB_PASSWORD'] = config['MongoDB']['password']
db = MongoEngine(app)
def register_blueprints(app):
# Prevents circular imports
from weighttracker.views.measurement_views import measurements
app.register_blueprint(measurements)
from weighttracker.views.inspiration_views import inspirations
app.register_blueprint(inspirations)
from weighttracker.views.foodjournal_views import foodjournals
app.register_blueprint(foodjournals)
register_blueprints(app)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return render_template('index.html')
if __name__ == '__main__':
app.run()
|
from flask import Flask, render_template
from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface
import configparser
from .momentjs import momentjs
app = Flask(__name__)
# Security
WTF_CSRF_ENABLED = True
app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR'
app.jinja_env.globals['momentjs'] = momentjs
# App Config
config = configparser.ConfigParser()
config.read('config/config.ini')
app.config['MONGODB_DB_SETTINGS'] = {
'name': config['MongoDB']['db_name'],
'host': config['MongoDB']['host'],
'port': int(config['MongoDB']['port']),
'username': config['MongoDB']['username'],
'password': config['MongoDB']['password']}
db = MongoEngine(app)
def register_blueprints(app):
# Prevents circular imports
from weighttracker.views.measurement_views import measurements
app.register_blueprint(measurements)
from weighttracker.views.inspiration_views import inspirations
app.register_blueprint(inspirations)
from weighttracker.views.foodjournal_views import foodjournals
app.register_blueprint(foodjournals)
register_blueprints(app)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return render_template('index.html')
if __name__ == '__main__':
app.run()
|
Update how we set the connection information for MongoDB to support Mongo 3.0.5
|
Update how we set the connection information for MongoDB to support Mongo 3.0.5
Signed-off-by: Robert Dempsey <[email protected]>
|
Python
|
mit
|
rdempsey/weight-tracker,rdempsey/weight-tracker,rdempsey/weight-tracker
|
from flask import Flask, render_template
from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface
import configparser
from .momentjs import momentjs
app = Flask(__name__)
# Security
WTF_CSRF_ENABLED = True
app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR'
app.jinja_env.globals['momentjs'] = momentjs
# App Config
config = configparser.ConfigParser()
config.read('config/config.ini')
- app.config['MONGODB_DB'] = config['MongoDB']['db_name']
- app.config['MONGODB_HOST'] = config['MongoDB']['host']
- app.config['MONGODB_PORT'] = int(config['MongoDB']['port'])
- app.config['MONGODB_USERNAME'] = config['MongoDB']['username']
- app.config['MONGODB_PASSWORD'] = config['MongoDB']['password']
+ app.config['MONGODB_DB_SETTINGS'] = {
+ 'name': config['MongoDB']['db_name'],
+ 'host': config['MongoDB']['host'],
+ 'port': int(config['MongoDB']['port']),
+ 'username': config['MongoDB']['username'],
+ 'password': config['MongoDB']['password']}
db = MongoEngine(app)
def register_blueprints(app):
# Prevents circular imports
from weighttracker.views.measurement_views import measurements
app.register_blueprint(measurements)
from weighttracker.views.inspiration_views import inspirations
app.register_blueprint(inspirations)
from weighttracker.views.foodjournal_views import foodjournals
app.register_blueprint(foodjournals)
register_blueprints(app)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return render_template('index.html')
if __name__ == '__main__':
app.run()
|
Update how we set the connection information for MongoDB to support Mongo 3.0.5
|
## Code Before:
from flask import Flask, render_template
from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface
import configparser
from .momentjs import momentjs
app = Flask(__name__)
# Security
WTF_CSRF_ENABLED = True
app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR'
app.jinja_env.globals['momentjs'] = momentjs
# App Config
config = configparser.ConfigParser()
config.read('config/config.ini')
app.config['MONGODB_DB'] = config['MongoDB']['db_name']
app.config['MONGODB_HOST'] = config['MongoDB']['host']
app.config['MONGODB_PORT'] = int(config['MongoDB']['port'])
app.config['MONGODB_USERNAME'] = config['MongoDB']['username']
app.config['MONGODB_PASSWORD'] = config['MongoDB']['password']
db = MongoEngine(app)
def register_blueprints(app):
# Prevents circular imports
from weighttracker.views.measurement_views import measurements
app.register_blueprint(measurements)
from weighttracker.views.inspiration_views import inspirations
app.register_blueprint(inspirations)
from weighttracker.views.foodjournal_views import foodjournals
app.register_blueprint(foodjournals)
register_blueprints(app)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return render_template('index.html')
if __name__ == '__main__':
app.run()
## Instruction:
Update how we set the connection information for MongoDB to support Mongo 3.0.5
## Code After:
from flask import Flask, render_template
from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface
import configparser
from .momentjs import momentjs
app = Flask(__name__)
# Security
WTF_CSRF_ENABLED = True
app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR'
app.jinja_env.globals['momentjs'] = momentjs
# App Config
config = configparser.ConfigParser()
config.read('config/config.ini')
app.config['MONGODB_DB_SETTINGS'] = {
'name': config['MongoDB']['db_name'],
'host': config['MongoDB']['host'],
'port': int(config['MongoDB']['port']),
'username': config['MongoDB']['username'],
'password': config['MongoDB']['password']}
db = MongoEngine(app)
def register_blueprints(app):
# Prevents circular imports
from weighttracker.views.measurement_views import measurements
app.register_blueprint(measurements)
from weighttracker.views.inspiration_views import inspirations
app.register_blueprint(inspirations)
from weighttracker.views.foodjournal_views import foodjournals
app.register_blueprint(foodjournals)
register_blueprints(app)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return render_template('index.html')
if __name__ == '__main__':
app.run()
|
...
app.config['MONGODB_DB_SETTINGS'] = {
'name': config['MongoDB']['db_name'],
'host': config['MongoDB']['host'],
'port': int(config['MongoDB']['port']),
'username': config['MongoDB']['username'],
'password': config['MongoDB']['password']}
...
|
25ea87b810d717690679613251fbc262f11c021f
|
pajbot/modules/linefarming.py
|
pajbot/modules/linefarming.py
|
import logging
from pajbot.managers.handler import HandlerManager
from pajbot.models.user import User
from pajbot.modules import BaseModule
from pajbot.modules import ModuleSetting
log = logging.getLogger(__name__)
class LineFarmingModule(BaseModule):
ID = __name__.split(".")[-1]
NAME = "Line Farming"
DESCRIPTION = "Keep track on the amount of lines users type in chat"
ENABLED_DEFAULT = True
CATEGORY = "Feature"
SETTINGS = [
ModuleSetting(
key="count_offline", label="Count lines in offline chat", type="boolean", required=True, default=False
)
]
def on_pubmsg(self, source, **rest):
if self.bot.is_online or self.settings["count_offline"] is True:
# this funky syntax makes SQLAlchemy increment
# the num_lines atomically with SET num_lines=("user".num_lines + 1)
source.num_lines = User.num_lines + 1
def enable(self, bot):
HandlerManager.add_handler("on_pubmsg", self.on_pubmsg)
def disable(self, bot):
HandlerManager.remove_handler("on_pubmsg", self.on_pubmsg)
|
import logging
from pajbot.managers.handler import HandlerManager
from pajbot.models.user import User
from pajbot.modules import BaseModule
from pajbot.modules import ModuleSetting
log = logging.getLogger(__name__)
class LineFarmingModule(BaseModule):
ID = __name__.split(".")[-1]
NAME = "Line Farming"
DESCRIPTION = "Keep track on the amount of lines users type in chat"
ENABLED_DEFAULT = True
CATEGORY = "Feature"
SETTINGS = [
ModuleSetting(
key="count_offline", label="Count lines in offline chat", type="boolean", required=True, default=False
)
]
def on_pubmsg(self, source, **rest):
if self.bot.is_online or self.settings["count_offline"] is True:
source.num_lines += 1
def enable(self, bot):
HandlerManager.add_handler("on_pubmsg", self.on_pubmsg)
def disable(self, bot):
HandlerManager.remove_handler("on_pubmsg", self.on_pubmsg)
|
Revert to using += to increment user's lines Doing it the "atomic" way was causing str(user.num_lines) to become ""user".num_lines + :num_lines_1" which is not intended
|
Revert to using += to increment user's lines
Doing it the "atomic" way was causing str(user.num_lines) to become ""user".num_lines + :num_lines_1" which is not intended
|
Python
|
mit
|
pajlada/pajbot,pajlada/pajbot,pajlada/pajbot,pajlada/tyggbot,pajlada/tyggbot,pajlada/tyggbot,pajlada/pajbot,pajlada/tyggbot
|
import logging
from pajbot.managers.handler import HandlerManager
from pajbot.models.user import User
from pajbot.modules import BaseModule
from pajbot.modules import ModuleSetting
log = logging.getLogger(__name__)
class LineFarmingModule(BaseModule):
ID = __name__.split(".")[-1]
NAME = "Line Farming"
DESCRIPTION = "Keep track on the amount of lines users type in chat"
ENABLED_DEFAULT = True
CATEGORY = "Feature"
SETTINGS = [
ModuleSetting(
key="count_offline", label="Count lines in offline chat", type="boolean", required=True, default=False
)
]
def on_pubmsg(self, source, **rest):
if self.bot.is_online or self.settings["count_offline"] is True:
- # this funky syntax makes SQLAlchemy increment
- # the num_lines atomically with SET num_lines=("user".num_lines + 1)
- source.num_lines = User.num_lines + 1
+ source.num_lines += 1
def enable(self, bot):
HandlerManager.add_handler("on_pubmsg", self.on_pubmsg)
def disable(self, bot):
HandlerManager.remove_handler("on_pubmsg", self.on_pubmsg)
|
Revert to using += to increment user's lines Doing it the "atomic" way was causing str(user.num_lines) to become ""user".num_lines + :num_lines_1" which is not intended
|
## Code Before:
import logging
from pajbot.managers.handler import HandlerManager
from pajbot.models.user import User
from pajbot.modules import BaseModule
from pajbot.modules import ModuleSetting
log = logging.getLogger(__name__)
class LineFarmingModule(BaseModule):
ID = __name__.split(".")[-1]
NAME = "Line Farming"
DESCRIPTION = "Keep track on the amount of lines users type in chat"
ENABLED_DEFAULT = True
CATEGORY = "Feature"
SETTINGS = [
ModuleSetting(
key="count_offline", label="Count lines in offline chat", type="boolean", required=True, default=False
)
]
def on_pubmsg(self, source, **rest):
if self.bot.is_online or self.settings["count_offline"] is True:
# this funky syntax makes SQLAlchemy increment
# the num_lines atomically with SET num_lines=("user".num_lines + 1)
source.num_lines = User.num_lines + 1
def enable(self, bot):
HandlerManager.add_handler("on_pubmsg", self.on_pubmsg)
def disable(self, bot):
HandlerManager.remove_handler("on_pubmsg", self.on_pubmsg)
## Instruction:
Revert to using += to increment user's lines Doing it the "atomic" way was causing str(user.num_lines) to become ""user".num_lines + :num_lines_1" which is not intended
## Code After:
import logging
from pajbot.managers.handler import HandlerManager
from pajbot.models.user import User
from pajbot.modules import BaseModule
from pajbot.modules import ModuleSetting
log = logging.getLogger(__name__)
class LineFarmingModule(BaseModule):
ID = __name__.split(".")[-1]
NAME = "Line Farming"
DESCRIPTION = "Keep track on the amount of lines users type in chat"
ENABLED_DEFAULT = True
CATEGORY = "Feature"
SETTINGS = [
ModuleSetting(
key="count_offline", label="Count lines in offline chat", type="boolean", required=True, default=False
)
]
def on_pubmsg(self, source, **rest):
if self.bot.is_online or self.settings["count_offline"] is True:
source.num_lines += 1
def enable(self, bot):
HandlerManager.add_handler("on_pubmsg", self.on_pubmsg)
def disable(self, bot):
HandlerManager.remove_handler("on_pubmsg", self.on_pubmsg)
|
# ... existing code ...
if self.bot.is_online or self.settings["count_offline"] is True:
source.num_lines += 1
# ... rest of the code ...
|
3ffaf00e18208a1877c3d2286ba284071d5d3e09
|
wafer/pages/serializers.py
|
wafer/pages/serializers.py
|
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.save()
return page
|
from django.contrib.auth import get_user_model
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
people = serializers.PrimaryKeyRelatedField(
many=True, allow_null=True,
queryset=get_user_model().objects.all())
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.include_in_menu = validated_data['include_in_menu']
page.exclude_from_static = validated_data['exclude_from_static']
page.people = validated_data.get('people')
page.save()
return page
|
Add people and other fields to page update options
|
Add people and other fields to page update options
|
Python
|
isc
|
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
|
+ from django.contrib.auth import get_user_model
+
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
+
+ people = serializers.PrimaryKeyRelatedField(
+ many=True, allow_null=True,
+ queryset=get_user_model().objects.all())
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
+ page.include_in_menu = validated_data['include_in_menu']
+ page.exclude_from_static = validated_data['exclude_from_static']
+ page.people = validated_data.get('people')
page.save()
return page
|
Add people and other fields to page update options
|
## Code Before:
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.save()
return page
## Instruction:
Add people and other fields to page update options
## Code After:
from django.contrib.auth import get_user_model
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
people = serializers.PrimaryKeyRelatedField(
many=True, allow_null=True,
queryset=get_user_model().objects.all())
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.include_in_menu = validated_data['include_in_menu']
page.exclude_from_static = validated_data['exclude_from_static']
page.people = validated_data.get('people')
page.save()
return page
|
...
from django.contrib.auth import get_user_model
from rest_framework import serializers
...
class PageSerializer(serializers.ModelSerializer):
people = serializers.PrimaryKeyRelatedField(
many=True, allow_null=True,
queryset=get_user_model().objects.all())
...
page.content = validated_data['content']
page.include_in_menu = validated_data['include_in_menu']
page.exclude_from_static = validated_data['exclude_from_static']
page.people = validated_data.get('people')
page.save()
...
|
6099451fe088fe74945bbeedeeee66896bd7ff3d
|
voctocore/lib/sources/__init__.py
|
voctocore/lib/sources/__init__.py
|
import logging
from lib.config import Config
from lib.sources.decklinkavsource import DeckLinkAVSource
from lib.sources.imgvsource import ImgVSource
from lib.sources.tcpavsource import TCPAVSource
from lib.sources.testsource import TestSource
from lib.sources.videoloopsource import VideoLoopSource
log = logging.getLogger('AVSourceManager')
sources = {}
def spawn_source(name, port, has_audio=True, has_video=True,
force_num_streams=None):
kind = Config.getSourceKind(name)
if kind == 'img':
sources[name] = ImgVSource(name)
elif kind == 'decklink':
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
elif kind == 'test':
sources[name] = TestSource(name, has_audio, has_video)
elif kind == 'videoloop':
sources[name] = VideoLoopSource(name)
elif kind == 'tcp':
sources[name] = TCPAVSource(name, port, has_audio, has_video,
force_num_streams)
else:
log.warning('Unknown source kind "%s", defaulting to "tcp"', kind)
return sources[name]
def restart_source(name):
assert False, "restart_source() not implemented"
|
import logging
from lib.config import Config
from lib.sources.decklinkavsource import DeckLinkAVSource
from lib.sources.imgvsource import ImgVSource
from lib.sources.tcpavsource import TCPAVSource
from lib.sources.testsource import TestSource
from lib.sources.videoloopsource import VideoLoopSource
log = logging.getLogger('AVSourceManager')
sources = {}
def spawn_source(name, port, has_audio=True, has_video=True,
force_num_streams=None):
kind = Config.getSourceKind(name)
if kind == 'img':
sources[name] = ImgVSource(name)
elif kind == 'decklink':
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
elif kind == 'videoloop':
sources[name] = VideoLoopSource(name)
elif kind == 'tcp':
sources[name] = TCPAVSource(name, port, has_audio, has_video,
force_num_streams)
else:
if kind != 'test':
log.warning('Unknown value "%s" in attribute "kind" in definition of source %s (see section [source.%s] in configuration). Falling back to kind "test".', kind, name, name)
sources[name] = TestSource(name, has_audio, has_video)
return sources[name]
def restart_source(name):
assert False, "restart_source() not implemented"
|
Use test sources as the default in configuration (and improve warning message, when falling back to)
|
Use test sources as the default in configuration (and improve warning message, when falling back to)
|
Python
|
mit
|
voc/voctomix,voc/voctomix
|
import logging
from lib.config import Config
from lib.sources.decklinkavsource import DeckLinkAVSource
from lib.sources.imgvsource import ImgVSource
from lib.sources.tcpavsource import TCPAVSource
from lib.sources.testsource import TestSource
from lib.sources.videoloopsource import VideoLoopSource
log = logging.getLogger('AVSourceManager')
sources = {}
def spawn_source(name, port, has_audio=True, has_video=True,
force_num_streams=None):
kind = Config.getSourceKind(name)
if kind == 'img':
sources[name] = ImgVSource(name)
elif kind == 'decklink':
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
- elif kind == 'test':
- sources[name] = TestSource(name, has_audio, has_video)
elif kind == 'videoloop':
sources[name] = VideoLoopSource(name)
elif kind == 'tcp':
sources[name] = TCPAVSource(name, port, has_audio, has_video,
force_num_streams)
else:
- log.warning('Unknown source kind "%s", defaulting to "tcp"', kind)
+ if kind != 'test':
+ log.warning('Unknown value "%s" in attribute "kind" in definition of source %s (see section [source.%s] in configuration). Falling back to kind "test".', kind, name, name)
+ sources[name] = TestSource(name, has_audio, has_video)
+
return sources[name]
def restart_source(name):
assert False, "restart_source() not implemented"
|
Use test sources as the default in configuration (and improve warning message, when falling back to)
|
## Code Before:
import logging
from lib.config import Config
from lib.sources.decklinkavsource import DeckLinkAVSource
from lib.sources.imgvsource import ImgVSource
from lib.sources.tcpavsource import TCPAVSource
from lib.sources.testsource import TestSource
from lib.sources.videoloopsource import VideoLoopSource
log = logging.getLogger('AVSourceManager')
sources = {}
def spawn_source(name, port, has_audio=True, has_video=True,
force_num_streams=None):
kind = Config.getSourceKind(name)
if kind == 'img':
sources[name] = ImgVSource(name)
elif kind == 'decklink':
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
elif kind == 'test':
sources[name] = TestSource(name, has_audio, has_video)
elif kind == 'videoloop':
sources[name] = VideoLoopSource(name)
elif kind == 'tcp':
sources[name] = TCPAVSource(name, port, has_audio, has_video,
force_num_streams)
else:
log.warning('Unknown source kind "%s", defaulting to "tcp"', kind)
return sources[name]
def restart_source(name):
assert False, "restart_source() not implemented"
## Instruction:
Use test sources as the default in configuration (and improve warning message, when falling back to)
## Code After:
import logging
from lib.config import Config
from lib.sources.decklinkavsource import DeckLinkAVSource
from lib.sources.imgvsource import ImgVSource
from lib.sources.tcpavsource import TCPAVSource
from lib.sources.testsource import TestSource
from lib.sources.videoloopsource import VideoLoopSource
log = logging.getLogger('AVSourceManager')
sources = {}
def spawn_source(name, port, has_audio=True, has_video=True,
force_num_streams=None):
kind = Config.getSourceKind(name)
if kind == 'img':
sources[name] = ImgVSource(name)
elif kind == 'decklink':
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
elif kind == 'videoloop':
sources[name] = VideoLoopSource(name)
elif kind == 'tcp':
sources[name] = TCPAVSource(name, port, has_audio, has_video,
force_num_streams)
else:
if kind != 'test':
log.warning('Unknown value "%s" in attribute "kind" in definition of source %s (see section [source.%s] in configuration). Falling back to kind "test".', kind, name, name)
sources[name] = TestSource(name, has_audio, has_video)
return sources[name]
def restart_source(name):
assert False, "restart_source() not implemented"
|
// ... existing code ...
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
elif kind == 'videoloop':
// ... modified code ...
else:
if kind != 'test':
log.warning('Unknown value "%s" in attribute "kind" in definition of source %s (see section [source.%s] in configuration). Falling back to kind "test".', kind, name, name)
sources[name] = TestSource(name, has_audio, has_video)
return sources[name]
// ... rest of the code ...
|
c06ab929e1f7a55ddc0ed978939ea604cad003cb
|
hamper/plugins/roulette.py
|
hamper/plugins/roulette.py
|
import random, datetime
from hamper.interfaces import ChatCommandPlugin, Command
class Roulette(ChatCommandPlugin):
"""Feeling lucky? !roulette to see how lucky"""
name = 'roulette'
priority = 0
class Roulette(Command):
'''Try not to die'''
regex = r'^roulette$'
name = 'roulette'
short_desc = 'feeling lucky?'
long_desc = "See how lucky you are, just don't bleed everywhere"
def command(self, bot, comm, groups):
if comm['pm']:
return False
dice = random.randint(1,6)
if dice == 6:
bot.kick(comm["channel"], comm["user"], "You shot yourself!")
else:
bot.reply(comm, "*click*")
return True
roulette = Roulette()
|
import random
from hamper.interfaces import ChatCommandPlugin, Command
class Roulette(ChatCommandPlugin):
"""Feeling lucky? !roulette to see how lucky"""
name = 'roulette'
priority = 0
class Roulette(Command):
'''Try not to die'''
regex = r'^roulette$'
name = 'roulette'
short_desc = 'feeling lucky?'
long_desc = "See how lucky you are, just don't bleed everywhere"
def command(self, bot, comm, groups):
if comm['pm']:
return False
dice = random.randint(1, 6)
if dice == 6:
bot.kick(comm["channel"], comm["user"], "You shot yourself!")
else:
bot.reply(comm, "*click*")
return True
roulette = Roulette()
|
Revert "This should break the flakes8 check on Travis"
|
Revert "This should break the flakes8 check on Travis"
This reverts commit 91c3d6c30d75ce66228d52c74bf8a4d8e7628670.
|
Python
|
mit
|
hamperbot/hamper,maxking/hamper,iankronquist/hamper
|
- import random, datetime
+ import random
from hamper.interfaces import ChatCommandPlugin, Command
class Roulette(ChatCommandPlugin):
"""Feeling lucky? !roulette to see how lucky"""
name = 'roulette'
priority = 0
class Roulette(Command):
'''Try not to die'''
regex = r'^roulette$'
name = 'roulette'
short_desc = 'feeling lucky?'
long_desc = "See how lucky you are, just don't bleed everywhere"
def command(self, bot, comm, groups):
if comm['pm']:
return False
- dice = random.randint(1,6)
+ dice = random.randint(1, 6)
if dice == 6:
bot.kick(comm["channel"], comm["user"], "You shot yourself!")
else:
bot.reply(comm, "*click*")
return True
roulette = Roulette()
|
Revert "This should break the flakes8 check on Travis"
|
## Code Before:
import random, datetime
from hamper.interfaces import ChatCommandPlugin, Command
class Roulette(ChatCommandPlugin):
"""Feeling lucky? !roulette to see how lucky"""
name = 'roulette'
priority = 0
class Roulette(Command):
'''Try not to die'''
regex = r'^roulette$'
name = 'roulette'
short_desc = 'feeling lucky?'
long_desc = "See how lucky you are, just don't bleed everywhere"
def command(self, bot, comm, groups):
if comm['pm']:
return False
dice = random.randint(1,6)
if dice == 6:
bot.kick(comm["channel"], comm["user"], "You shot yourself!")
else:
bot.reply(comm, "*click*")
return True
roulette = Roulette()
## Instruction:
Revert "This should break the flakes8 check on Travis"
## Code After:
import random
from hamper.interfaces import ChatCommandPlugin, Command
class Roulette(ChatCommandPlugin):
"""Feeling lucky? !roulette to see how lucky"""
name = 'roulette'
priority = 0
class Roulette(Command):
'''Try not to die'''
regex = r'^roulette$'
name = 'roulette'
short_desc = 'feeling lucky?'
long_desc = "See how lucky you are, just don't bleed everywhere"
def command(self, bot, comm, groups):
if comm['pm']:
return False
dice = random.randint(1, 6)
if dice == 6:
bot.kick(comm["channel"], comm["user"], "You shot yourself!")
else:
bot.reply(comm, "*click*")
return True
roulette = Roulette()
|
// ... existing code ...
import random
// ... modified code ...
dice = random.randint(1, 6)
if dice == 6:
// ... rest of the code ...
|
7a7729e9af8e91411526525c19c5d434609e0f21
|
logger.py
|
logger.py
|
MSG_INFO = 0x01
MSG_WARNING = 0x02
MSG_ERROR = 0x04
MSG_VERBOSE = 0x08
MSG_ALL = MSG_INFO | MSG_WARNING | MSG_ERROR | MSG_VERBOSE
def logi(msg):
print("[INFO] " + msg)
def logv(msg):
print("[VERBOSE] " + msg)
def logw(msg):
print("[WARNING] " + msg)
def loge(msg):
print("[ERROR] " + msg)
class Logger(object):
def __init__(self):
self.logger_level = MSG_ALL
def info(self, msg):
if self.logger_level & MSG_INFO:
logi(msg)
def warning(self, msg):
if self.logger_level & MSG_WARNING:
logw(msg)
def error(self, msg):
if self.logger_level & MSG_ERROR:
loge(msg)
def verbose(self, msg):
if self.logger_level & MSG_VERBOSE:
logv(msg)
|
MSG_INFO = 0x01
MSG_WARNING = 0x02
MSG_ERROR = 0x04
MSG_VERBOSE = 0x08
MSG_ALL = MSG_INFO | MSG_WARNING | MSG_ERROR | MSG_VERBOSE
def logi(msg):
print("[INFO] " + msg)
def logv(msg):
print("[VERBOSE] " + msg)
def logw(msg):
print("[WARNING] " + msg)
def loge(msg):
print("\033[1;31m[ERROR] " + msg + "\033[m")
class Logger(object):
def __init__(self):
self.logger_level = MSG_ALL
def info(self, msg):
if self.logger_level & MSG_INFO:
logi(msg)
def warning(self, msg):
if self.logger_level & MSG_WARNING:
logw(msg)
def error(self, msg):
if self.logger_level & MSG_ERROR:
loge(msg)
def verbose(self, msg):
if self.logger_level & MSG_VERBOSE:
logv(msg)
|
Add color for error message.
|
Add color for error message.
|
Python
|
mit
|
PyOCL/oclGA,PyOCL/OpenCLGA,PyOCL/OpenCLGA,PyOCL/oclGA,PyOCL/oclGA,PyOCL/TSP,PyOCL/TSP,PyOCL/oclGA,PyOCL/OpenCLGA
|
MSG_INFO = 0x01
MSG_WARNING = 0x02
MSG_ERROR = 0x04
MSG_VERBOSE = 0x08
MSG_ALL = MSG_INFO | MSG_WARNING | MSG_ERROR | MSG_VERBOSE
def logi(msg):
print("[INFO] " + msg)
def logv(msg):
print("[VERBOSE] " + msg)
def logw(msg):
print("[WARNING] " + msg)
def loge(msg):
- print("[ERROR] " + msg)
+ print("\033[1;31m[ERROR] " + msg + "\033[m")
class Logger(object):
def __init__(self):
self.logger_level = MSG_ALL
def info(self, msg):
if self.logger_level & MSG_INFO:
logi(msg)
def warning(self, msg):
if self.logger_level & MSG_WARNING:
logw(msg)
def error(self, msg):
if self.logger_level & MSG_ERROR:
loge(msg)
def verbose(self, msg):
if self.logger_level & MSG_VERBOSE:
logv(msg)
|
Add color for error message.
|
## Code Before:
MSG_INFO = 0x01
MSG_WARNING = 0x02
MSG_ERROR = 0x04
MSG_VERBOSE = 0x08
MSG_ALL = MSG_INFO | MSG_WARNING | MSG_ERROR | MSG_VERBOSE
def logi(msg):
print("[INFO] " + msg)
def logv(msg):
print("[VERBOSE] " + msg)
def logw(msg):
print("[WARNING] " + msg)
def loge(msg):
print("[ERROR] " + msg)
class Logger(object):
def __init__(self):
self.logger_level = MSG_ALL
def info(self, msg):
if self.logger_level & MSG_INFO:
logi(msg)
def warning(self, msg):
if self.logger_level & MSG_WARNING:
logw(msg)
def error(self, msg):
if self.logger_level & MSG_ERROR:
loge(msg)
def verbose(self, msg):
if self.logger_level & MSG_VERBOSE:
logv(msg)
## Instruction:
Add color for error message.
## Code After:
MSG_INFO = 0x01
MSG_WARNING = 0x02
MSG_ERROR = 0x04
MSG_VERBOSE = 0x08
MSG_ALL = MSG_INFO | MSG_WARNING | MSG_ERROR | MSG_VERBOSE
def logi(msg):
print("[INFO] " + msg)
def logv(msg):
print("[VERBOSE] " + msg)
def logw(msg):
print("[WARNING] " + msg)
def loge(msg):
print("\033[1;31m[ERROR] " + msg + "\033[m")
class Logger(object):
def __init__(self):
self.logger_level = MSG_ALL
def info(self, msg):
if self.logger_level & MSG_INFO:
logi(msg)
def warning(self, msg):
if self.logger_level & MSG_WARNING:
logw(msg)
def error(self, msg):
if self.logger_level & MSG_ERROR:
loge(msg)
def verbose(self, msg):
if self.logger_level & MSG_VERBOSE:
logv(msg)
|
// ... existing code ...
def loge(msg):
print("\033[1;31m[ERROR] " + msg + "\033[m")
// ... rest of the code ...
|
f17a70980f1964e40a22fad5e54f4cafcdcf9d52
|
useless_passport_validator/ulibrary.py
|
useless_passport_validator/ulibrary.py
|
from collections import namedtuple
"""Document constants"""
countries = ["Mordor", "Gondor", "Lorien", "Shire"]
genders = ["Male", "Female"]
cities = {
'Mordor': 'Minas Morgul,Barad Dur',
'Gondor': 'Minas Tirith,Isengard,Osgiliath',
'Lorien': 'Lorien',
'Shire': 'Hobbiton,Waymeet,Frogmorton,Tuckborough'
}
purpose = ["Visit", "Transit", "Work", "Immigrate"]
"""Store user input here"""
UPassport = namedtuple("UPassport", "country name gender isscity expdate serial")
UPass = namedtuple("UPass", "name gender purpose duration serial expires")
UWorkVisa = namedtuple("UWorkVisa", "name proff duration expires")
URecord = namedtuple("URecord", "purpose duration")
|
from collections import namedtuple
def init():
"""Document constants"""
global countries
countries = ["Mordor", "Gondor", "Lorien", "Shire"]
global genders
genders = ["Male", "Female"]
global cities
cities = {
'Mordor': 'Minas Morgul,Barad Dur',
'Gondor': 'Minas Tirith,Isengard,Osgiliath',
'Lorien': 'Lorien',
'Shire': 'Hobbiton,Waymeet,Frogmorton,Tuckborough'
}
global purpose
purpose = ["Visit", "Transit", "Work", "Immigrate"]
"""Store user input here"""
global UPassport
UPassport = namedtuple("UPassport", "country name gender isscity expdate serial")
global UPass
UPass = namedtuple("UPass", "name gender purpose duration serial expires")
global UWorkVisa
UWorkVisa = namedtuple("UWorkVisa", "name proff duration expires")
global URecord
URecord = namedtuple("URecord", "purpose duration")
|
Define init function. Make variables actually global
|
Define init function. Make variables actually global
|
Python
|
mit
|
Hethurin/UApp
|
from collections import namedtuple
+ def init():
- """Document constants"""
+ """Document constants"""
+ global countries
- countries = ["Mordor", "Gondor", "Lorien", "Shire"]
+ countries = ["Mordor", "Gondor", "Lorien", "Shire"]
+ global genders
- genders = ["Male", "Female"]
+ genders = ["Male", "Female"]
+ global cities
- cities = {
+ cities = {
- 'Mordor': 'Minas Morgul,Barad Dur',
+ 'Mordor': 'Minas Morgul,Barad Dur',
- 'Gondor': 'Minas Tirith,Isengard,Osgiliath',
+ 'Gondor': 'Minas Tirith,Isengard,Osgiliath',
- 'Lorien': 'Lorien',
+ 'Lorien': 'Lorien',
- 'Shire': 'Hobbiton,Waymeet,Frogmorton,Tuckborough'
+ 'Shire': 'Hobbiton,Waymeet,Frogmorton,Tuckborough'
}
+ global purpose
- purpose = ["Visit", "Transit", "Work", "Immigrate"]
+ purpose = ["Visit", "Transit", "Work", "Immigrate"]
- """Store user input here"""
+ """Store user input here"""
+ global UPassport
- UPassport = namedtuple("UPassport", "country name gender isscity expdate serial")
+ UPassport = namedtuple("UPassport", "country name gender isscity expdate serial")
+ global UPass
- UPass = namedtuple("UPass", "name gender purpose duration serial expires")
+ UPass = namedtuple("UPass", "name gender purpose duration serial expires")
+ global UWorkVisa
- UWorkVisa = namedtuple("UWorkVisa", "name proff duration expires")
+ UWorkVisa = namedtuple("UWorkVisa", "name proff duration expires")
+ global URecord
- URecord = namedtuple("URecord", "purpose duration")
+ URecord = namedtuple("URecord", "purpose duration")
|
Define init function. Make variables actually global
|
## Code Before:
from collections import namedtuple
"""Document constants"""
countries = ["Mordor", "Gondor", "Lorien", "Shire"]
genders = ["Male", "Female"]
cities = {
'Mordor': 'Minas Morgul,Barad Dur',
'Gondor': 'Minas Tirith,Isengard,Osgiliath',
'Lorien': 'Lorien',
'Shire': 'Hobbiton,Waymeet,Frogmorton,Tuckborough'
}
purpose = ["Visit", "Transit", "Work", "Immigrate"]
"""Store user input here"""
UPassport = namedtuple("UPassport", "country name gender isscity expdate serial")
UPass = namedtuple("UPass", "name gender purpose duration serial expires")
UWorkVisa = namedtuple("UWorkVisa", "name proff duration expires")
URecord = namedtuple("URecord", "purpose duration")
## Instruction:
Define init function. Make variables actually global
## Code After:
from collections import namedtuple
def init():
"""Document constants"""
global countries
countries = ["Mordor", "Gondor", "Lorien", "Shire"]
global genders
genders = ["Male", "Female"]
global cities
cities = {
'Mordor': 'Minas Morgul,Barad Dur',
'Gondor': 'Minas Tirith,Isengard,Osgiliath',
'Lorien': 'Lorien',
'Shire': 'Hobbiton,Waymeet,Frogmorton,Tuckborough'
}
global purpose
purpose = ["Visit", "Transit", "Work", "Immigrate"]
"""Store user input here"""
global UPassport
UPassport = namedtuple("UPassport", "country name gender isscity expdate serial")
global UPass
UPass = namedtuple("UPass", "name gender purpose duration serial expires")
global UWorkVisa
UWorkVisa = namedtuple("UWorkVisa", "name proff duration expires")
global URecord
URecord = namedtuple("URecord", "purpose duration")
|
# ... existing code ...
def init():
"""Document constants"""
global countries
countries = ["Mordor", "Gondor", "Lorien", "Shire"]
global genders
genders = ["Male", "Female"]
global cities
cities = {
'Mordor': 'Minas Morgul,Barad Dur',
'Gondor': 'Minas Tirith,Isengard,Osgiliath',
'Lorien': 'Lorien',
'Shire': 'Hobbiton,Waymeet,Frogmorton,Tuckborough'
}
global purpose
purpose = ["Visit", "Transit", "Work", "Immigrate"]
"""Store user input here"""
global UPassport
UPassport = namedtuple("UPassport", "country name gender isscity expdate serial")
global UPass
UPass = namedtuple("UPass", "name gender purpose duration serial expires")
global UWorkVisa
UWorkVisa = namedtuple("UWorkVisa", "name proff duration expires")
global URecord
URecord = namedtuple("URecord", "purpose duration")
# ... rest of the code ...
|
d6b4024d502e189e67d9027a50e472b7c295a83f
|
misc/migrate_miro_vhs.py
|
misc/migrate_miro_vhs.py
|
import boto3
def get_existing_records(dynamodb_client):
"""
Generates existing Miro records from the SourceData table.
"""
paginator = dynamodb_client.get_paginator('scan')
for page in paginator.paginate(TableName='SourceData'):
for item in page['Items']:
yield item
if __name__ == '__main__':
dynamodb_client = boto3.client('dynamodb')
for item in get_existing_records(dynamodb_client):
print(item)
break
|
import boto3
OLD_TABLE = 'SourceData'
OLD_BUCKET = 'wellcomecollection-vhs-sourcedata'
NEW_TABLE = 'wellcomecollection-vhs-sourcedata-miro'
NEW_BUCKET = 'wellcomecollection-vhs-sourcedata-miro'
def get_existing_records(dynamodb_client):
"""
Generates existing Miro records from the SourceData table.
"""
paginator = dynamodb_client.get_paginator('scan')
for page in paginator.paginate(TableName=OLD_TABLE):
for item in page['Items']:
if 'reindexShard' not in item:
print(item)
if item['sourceName'] != {'S': 'miro'}:
continue
yield item
if __name__ == '__main__':
dynamodb_client = boto3.client('dynamodb')
s3_client = boto3.client('s3')
for item in get_existing_records(dynamodb_client):
del item['sourceName']
s3_client.copy_object(
Bucket=NEW_BUCKET,
Key=item['s3key']['S'].replace('miro/', ''),
CopySource={
'Bucket': OLD_BUCKET,
'Key': item['s3key']['S']
}
)
print(item)
break
|
Copy the S3 object into the new bucket
|
Copy the S3 object into the new bucket
|
Python
|
mit
|
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
|
import boto3
+
+
+ OLD_TABLE = 'SourceData'
+ OLD_BUCKET = 'wellcomecollection-vhs-sourcedata'
+
+ NEW_TABLE = 'wellcomecollection-vhs-sourcedata-miro'
+ NEW_BUCKET = 'wellcomecollection-vhs-sourcedata-miro'
def get_existing_records(dynamodb_client):
"""
Generates existing Miro records from the SourceData table.
"""
paginator = dynamodb_client.get_paginator('scan')
- for page in paginator.paginate(TableName='SourceData'):
+ for page in paginator.paginate(TableName=OLD_TABLE):
for item in page['Items']:
+ if 'reindexShard' not in item:
+ print(item)
+
+ if item['sourceName'] != {'S': 'miro'}:
+ continue
yield item
if __name__ == '__main__':
dynamodb_client = boto3.client('dynamodb')
+ s3_client = boto3.client('s3')
for item in get_existing_records(dynamodb_client):
+ del item['sourceName']
+
+ s3_client.copy_object(
+ Bucket=NEW_BUCKET,
+ Key=item['s3key']['S'].replace('miro/', ''),
+ CopySource={
+ 'Bucket': OLD_BUCKET,
+ 'Key': item['s3key']['S']
+ }
+ )
+
print(item)
break
|
Copy the S3 object into the new bucket
|
## Code Before:
import boto3
def get_existing_records(dynamodb_client):
"""
Generates existing Miro records from the SourceData table.
"""
paginator = dynamodb_client.get_paginator('scan')
for page in paginator.paginate(TableName='SourceData'):
for item in page['Items']:
yield item
if __name__ == '__main__':
dynamodb_client = boto3.client('dynamodb')
for item in get_existing_records(dynamodb_client):
print(item)
break
## Instruction:
Copy the S3 object into the new bucket
## Code After:
import boto3
OLD_TABLE = 'SourceData'
OLD_BUCKET = 'wellcomecollection-vhs-sourcedata'
NEW_TABLE = 'wellcomecollection-vhs-sourcedata-miro'
NEW_BUCKET = 'wellcomecollection-vhs-sourcedata-miro'
def get_existing_records(dynamodb_client):
"""
Generates existing Miro records from the SourceData table.
"""
paginator = dynamodb_client.get_paginator('scan')
for page in paginator.paginate(TableName=OLD_TABLE):
for item in page['Items']:
if 'reindexShard' not in item:
print(item)
if item['sourceName'] != {'S': 'miro'}:
continue
yield item
if __name__ == '__main__':
dynamodb_client = boto3.client('dynamodb')
s3_client = boto3.client('s3')
for item in get_existing_records(dynamodb_client):
del item['sourceName']
s3_client.copy_object(
Bucket=NEW_BUCKET,
Key=item['s3key']['S'].replace('miro/', ''),
CopySource={
'Bucket': OLD_BUCKET,
'Key': item['s3key']['S']
}
)
print(item)
break
|
// ... existing code ...
import boto3
OLD_TABLE = 'SourceData'
OLD_BUCKET = 'wellcomecollection-vhs-sourcedata'
NEW_TABLE = 'wellcomecollection-vhs-sourcedata-miro'
NEW_BUCKET = 'wellcomecollection-vhs-sourcedata-miro'
// ... modified code ...
paginator = dynamodb_client.get_paginator('scan')
for page in paginator.paginate(TableName=OLD_TABLE):
for item in page['Items']:
if 'reindexShard' not in item:
print(item)
if item['sourceName'] != {'S': 'miro'}:
continue
yield item
...
dynamodb_client = boto3.client('dynamodb')
s3_client = boto3.client('s3')
...
for item in get_existing_records(dynamodb_client):
del item['sourceName']
s3_client.copy_object(
Bucket=NEW_BUCKET,
Key=item['s3key']['S'].replace('miro/', ''),
CopySource={
'Bucket': OLD_BUCKET,
'Key': item['s3key']['S']
}
)
print(item)
// ... rest of the code ...
|
30ed3800fdeec4aec399e6e0ec0760e46eb891ec
|
djangoautoconf/model_utils/model_reversion.py
|
djangoautoconf/model_utils/model_reversion.py
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
from reversion.revisions import default_revision_manager
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
default_revision_manager.save_revision((item,))
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
def create_initial_version(obj):
try:
from reversion.revisions import default_revision_manager
default_revision_manager.save_revision((obj,))
except:
from reversion.revisions import add_to_revision
add_to_revision(obj)
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
create_initial_version(item)
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
|
Fix broken initial version creation.
|
Fix broken initial version creation.
|
Python
|
bsd-3-clause
|
weijia/djangoautoconf,weijia/djangoautoconf
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
+
+
+ def create_initial_version(obj):
+ try:
- from reversion.revisions import default_revision_manager
+ from reversion.revisions import default_revision_manager
+ default_revision_manager.save_revision((obj,))
+ except:
+ from reversion.revisions import add_to_revision
+ add_to_revision(obj)
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
- default_revision_manager.save_revision((item,))
+ create_initial_version(item)
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
|
Fix broken initial version creation.
|
## Code Before:
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
from reversion.revisions import default_revision_manager
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
default_revision_manager.save_revision((item,))
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
## Instruction:
Fix broken initial version creation.
## Code After:
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
def create_initial_version(obj):
try:
from reversion.revisions import default_revision_manager
default_revision_manager.save_revision((obj,))
except:
from reversion.revisions import add_to_revision
add_to_revision(obj)
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
create_initial_version(item)
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
|
// ... existing code ...
from reversion.models import Version
def create_initial_version(obj):
try:
from reversion.revisions import default_revision_manager
default_revision_manager.save_revision((obj,))
except:
from reversion.revisions import add_to_revision
add_to_revision(obj)
// ... modified code ...
try:
create_initial_version(item)
except:
// ... rest of the code ...
|
fa2d26f6c7652f1c4964ff5df076bf9dcdd3a493
|
webvtt/exceptions.py
|
webvtt/exceptions.py
|
class MalformedFileError(Exception):
"""Error raised when the file is not well formatted"""
class MalformedCaptionError(Exception):
"""Error raised when a caption is not well formatted"""
|
class MalformedFileError(Exception):
"""Error raised when the file is not well formatted"""
class MalformedCaptionError(Exception):
"""Error raised when a caption is not well formatted"""
class InvalidCaptionsError(Exception):
"""Error raised when passing wrong captions to the segmenter"""
|
Add exception for invalid captions
|
Add exception for invalid captions
|
Python
|
mit
|
sampattuzzi/webvtt-py,glut23/webvtt-py
|
class MalformedFileError(Exception):
"""Error raised when the file is not well formatted"""
class MalformedCaptionError(Exception):
"""Error raised when a caption is not well formatted"""
+
+ class InvalidCaptionsError(Exception):
+ """Error raised when passing wrong captions to the segmenter"""
|
Add exception for invalid captions
|
## Code Before:
class MalformedFileError(Exception):
"""Error raised when the file is not well formatted"""
class MalformedCaptionError(Exception):
"""Error raised when a caption is not well formatted"""
## Instruction:
Add exception for invalid captions
## Code After:
class MalformedFileError(Exception):
"""Error raised when the file is not well formatted"""
class MalformedCaptionError(Exception):
"""Error raised when a caption is not well formatted"""
class InvalidCaptionsError(Exception):
"""Error raised when passing wrong captions to the segmenter"""
|
// ... existing code ...
"""Error raised when a caption is not well formatted"""
class InvalidCaptionsError(Exception):
"""Error raised when passing wrong captions to the segmenter"""
// ... rest of the code ...
|
c6f2ff563c08eb43ba3f33bc9aaa2647e78701d2
|
fenced_code_plus/__init__.py
|
fenced_code_plus/__init__.py
|
from fenced_code_plus import FencedCodePlusExtension
from fenced_code_plus import makeExtension
|
from __future__ import absolute_import
from fenced_code_plus.fenced_code_plus import FencedCodePlusExtension
from fenced_code_plus.fenced_code_plus import makeExtension
|
Make import compatable with python3.5
|
Make import compatable with python3.5
|
Python
|
bsd-3-clause
|
amfarrell/fenced-code-plus
|
+ from __future__ import absolute_import
- from fenced_code_plus import FencedCodePlusExtension
- from fenced_code_plus import makeExtension
+ from fenced_code_plus.fenced_code_plus import FencedCodePlusExtension
+ from fenced_code_plus.fenced_code_plus import makeExtension
+
|
Make import compatable with python3.5
|
## Code Before:
from fenced_code_plus import FencedCodePlusExtension
from fenced_code_plus import makeExtension
## Instruction:
Make import compatable with python3.5
## Code After:
from __future__ import absolute_import
from fenced_code_plus.fenced_code_plus import FencedCodePlusExtension
from fenced_code_plus.fenced_code_plus import makeExtension
|
...
from __future__ import absolute_import
from fenced_code_plus.fenced_code_plus import FencedCodePlusExtension
from fenced_code_plus.fenced_code_plus import makeExtension
...
|
a817afa1580aeb59fcbe837893c9ec8c5e7e0667
|
anygit/clisetup.py
|
anygit/clisetup.py
|
import logging.config
import os
from paste.deploy import loadapp
import sys
DIR = os.path.abspath(os.path.dirname(__file__))
conf = os.path.join(DIR, '../conf/anygit.ini')
application = loadapp('config:%s' % conf, relative_to='/')
app = loadapp('config:%s' % conf,relative_to=os.getcwd())
logging.config.fileConfig(conf)
|
import logging.config
import os
from paste.deploy import loadapp
import sys
DIR = os.path.abspath(os.path.dirname(__file__))
conf = os.path.join(DIR, '../conf/anygit.ini')
logging.config.fileConfig(conf)
application = loadapp('config:%s' % conf, relative_to='/')
app = loadapp('config:%s' % conf,relative_to=os.getcwd())
|
Load the logging config right away so it actually works
|
Load the logging config right away so it actually works
|
Python
|
mit
|
ebroder/anygit,ebroder/anygit
|
import logging.config
import os
from paste.deploy import loadapp
import sys
DIR = os.path.abspath(os.path.dirname(__file__))
conf = os.path.join(DIR, '../conf/anygit.ini')
+ logging.config.fileConfig(conf)
application = loadapp('config:%s' % conf, relative_to='/')
app = loadapp('config:%s' % conf,relative_to=os.getcwd())
- logging.config.fileConfig(conf)
+
|
Load the logging config right away so it actually works
|
## Code Before:
import logging.config
import os
from paste.deploy import loadapp
import sys
DIR = os.path.abspath(os.path.dirname(__file__))
conf = os.path.join(DIR, '../conf/anygit.ini')
application = loadapp('config:%s' % conf, relative_to='/')
app = loadapp('config:%s' % conf,relative_to=os.getcwd())
logging.config.fileConfig(conf)
## Instruction:
Load the logging config right away so it actually works
## Code After:
import logging.config
import os
from paste.deploy import loadapp
import sys
DIR = os.path.abspath(os.path.dirname(__file__))
conf = os.path.join(DIR, '../conf/anygit.ini')
logging.config.fileConfig(conf)
application = loadapp('config:%s' % conf, relative_to='/')
app = loadapp('config:%s' % conf,relative_to=os.getcwd())
|
...
conf = os.path.join(DIR, '../conf/anygit.ini')
logging.config.fileConfig(conf)
application = loadapp('config:%s' % conf, relative_to='/')
...
app = loadapp('config:%s' % conf,relative_to=os.getcwd())
...
|
eeeba609afe732b8e95aa535e70d4cdd2ae1aac7
|
tests/unit/test_cufflinks.py
|
tests/unit/test_cufflinks.py
|
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(DATA_DIR, "cufflinks", "merged.gtf")
ref_gtf = os.path.join(DATA_DIR, "cufflinks", "ref-transcripts.gtf")
out_dir = "cufflinks-test"
def setUp(self):
safe_makedir(self.out_dir)
@attr("unit")
def test_cufflinks_clean(self):
clean_fn = os.path.join(self.out_dir, "clean.gtf")
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
# fixed_fn = os.path.join(self.out_dir, "fixed.gtf")
# fixed = cufflinks.fix_cufflinks_attributes(self.ref_gtf, clean, fixed_fn)
assert(file_exists(clean))
assert(os.path.exists(dirty))
# assert(file_exists(fixed))
def tearDown(self):
shutil.rmtree(self.out_dir)
|
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(DATA_DIR, "cufflinks", "merged.gtf")
ref_gtf = os.path.join(DATA_DIR, "cufflinks", "ref-transcripts.gtf")
out_dir = "cufflinks-test"
def setUp(self):
safe_makedir(self.out_dir)
@attr("unit")
def test_cufflinks_clean(self):
clean_fn = os.path.join(self.out_dir, "clean.gtf")
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
assert(file_exists(clean))
assert(os.path.exists(dirty))
def tearDown(self):
shutil.rmtree(self.out_dir)
|
Remove some cruft from the cufflinks test.
|
Remove some cruft from the cufflinks test.
|
Python
|
mit
|
vladsaveliev/bcbio-nextgen,biocyberman/bcbio-nextgen,verdurin/bcbio-nextgen,fw1121/bcbio-nextgen,gifford-lab/bcbio-nextgen,chapmanb/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,hjanime/bcbio-nextgen,verdurin/bcbio-nextgen,lbeltrame/bcbio-nextgen,verdurin/bcbio-nextgen,SciLifeLab/bcbio-nextgen,chapmanb/bcbio-nextgen,lpantano/bcbio-nextgen,vladsaveliev/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,mjafin/bcbio-nextgen,brainstorm/bcbio-nextgen,lbeltrame/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen,fw1121/bcbio-nextgen,a113n/bcbio-nextgen,brainstorm/bcbio-nextgen,SciLifeLab/bcbio-nextgen,mjafin/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,mjafin/bcbio-nextgen,lbeltrame/bcbio-nextgen,biocyberman/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,chapmanb/bcbio-nextgen,gifford-lab/bcbio-nextgen,lpantano/bcbio-nextgen,lpantano/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,gifford-lab/bcbio-nextgen,fw1121/bcbio-nextgen,vladsaveliev/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen,a113n/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,hjanime/bcbio-nextgen,SciLifeLab/bcbio-nextgen,brainstorm/bcbio-nextgen,biocyberman/bcbio-nextgen,hjanime/bcbio-nextgen,a113n/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen
|
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(DATA_DIR, "cufflinks", "merged.gtf")
ref_gtf = os.path.join(DATA_DIR, "cufflinks", "ref-transcripts.gtf")
out_dir = "cufflinks-test"
def setUp(self):
safe_makedir(self.out_dir)
@attr("unit")
def test_cufflinks_clean(self):
clean_fn = os.path.join(self.out_dir, "clean.gtf")
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
- # fixed_fn = os.path.join(self.out_dir, "fixed.gtf")
- # fixed = cufflinks.fix_cufflinks_attributes(self.ref_gtf, clean, fixed_fn)
assert(file_exists(clean))
assert(os.path.exists(dirty))
- # assert(file_exists(fixed))
def tearDown(self):
shutil.rmtree(self.out_dir)
|
Remove some cruft from the cufflinks test.
|
## Code Before:
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(DATA_DIR, "cufflinks", "merged.gtf")
ref_gtf = os.path.join(DATA_DIR, "cufflinks", "ref-transcripts.gtf")
out_dir = "cufflinks-test"
def setUp(self):
safe_makedir(self.out_dir)
@attr("unit")
def test_cufflinks_clean(self):
clean_fn = os.path.join(self.out_dir, "clean.gtf")
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
# fixed_fn = os.path.join(self.out_dir, "fixed.gtf")
# fixed = cufflinks.fix_cufflinks_attributes(self.ref_gtf, clean, fixed_fn)
assert(file_exists(clean))
assert(os.path.exists(dirty))
# assert(file_exists(fixed))
def tearDown(self):
shutil.rmtree(self.out_dir)
## Instruction:
Remove some cruft from the cufflinks test.
## Code After:
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(DATA_DIR, "cufflinks", "merged.gtf")
ref_gtf = os.path.join(DATA_DIR, "cufflinks", "ref-transcripts.gtf")
out_dir = "cufflinks-test"
def setUp(self):
safe_makedir(self.out_dir)
@attr("unit")
def test_cufflinks_clean(self):
clean_fn = os.path.join(self.out_dir, "clean.gtf")
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
assert(file_exists(clean))
assert(os.path.exists(dirty))
def tearDown(self):
shutil.rmtree(self.out_dir)
|
...
dirty_fn)
assert(file_exists(clean))
...
assert(os.path.exists(dirty))
...
|
6d84cdb641d2d873118cb6cb26c5a7521ae40bd8
|
dcclient/dcclient.py
|
dcclient/dcclient.py
|
import rpc
from xml_manager.manager import ManagedXml
from oslo.config import cfg
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
self.xml.addVlan(vlan)
self._update()
|
import rpc
from xml_manager.manager import ManagedXml
from neutron.openstack.common import log as logger
from oslo.config import cfg
LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
try:
self.xml.addVlan(vlan)
self._update()
except:
LOG.info("Trying to create already existing network %d:", vlan)
|
Add error treatment for existing network
|
Add error treatment for existing network
|
Python
|
apache-2.0
|
NeutronUfscarDatacom/DriverDatacom
|
import rpc
from xml_manager.manager import ManagedXml
+ from neutron.openstack.common import log as logger
from oslo.config import cfg
+
+ LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
+ try:
- self.xml.addVlan(vlan)
+ self.xml.addVlan(vlan)
- self._update()
+ self._update()
+ except:
+ LOG.info("Trying to create already existing network %d:", vlan)
|
Add error treatment for existing network
|
## Code Before:
import rpc
from xml_manager.manager import ManagedXml
from oslo.config import cfg
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
self.xml.addVlan(vlan)
self._update()
## Instruction:
Add error treatment for existing network
## Code After:
import rpc
from xml_manager.manager import ManagedXml
from neutron.openstack.common import log as logger
from oslo.config import cfg
LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
try:
self.xml.addVlan(vlan)
self._update()
except:
LOG.info("Trying to create already existing network %d:", vlan)
|
# ... existing code ...
from neutron.openstack.common import log as logger
from oslo.config import cfg
# ... modified code ...
LOG = logger.getLogger(__name__)
...
"""
try:
self.xml.addVlan(vlan)
self._update()
except:
LOG.info("Trying to create already existing network %d:", vlan)
# ... rest of the code ...
|
48f1d12f97be8a7bca60809967b88f77ba7d6393
|
setup.py
|
setup.py
|
from distutils.core import setup
distobj = setup(
name="Axiom",
version="0.1",
maintainer="Divmod, Inc.",
maintainer_email="[email protected]",
url="http://divmod.org/trac/wiki/AxiomProject",
license="MIT",
platforms=["any"],
description="An in-process object-relational database",
classifiers=[
"Intended Audience :: Developers",
"Programming Language :: Python",
"Development Status :: 2 - Pre-Alpha",
"Topic :: Database"],
scripts=['bin/axiomatic'],
packages=['axiom',
'axiom.scripts',
'axiom.plugins',
'axiom.test'],
package_data={'axiom': ['examples/*']})
from epsilon.setuphelper import regeneratePluginCache
regeneratePluginCache(distobj)
|
from distutils.core import setup
import axiom
distobj = setup(
name="Axiom",
version=axiom.version.short(),
maintainer="Divmod, Inc.",
maintainer_email="[email protected]",
url="http://divmod.org/trac/wiki/DivmodAxiom",
license="MIT",
platforms=["any"],
description="An in-process object-relational database",
classifiers=[
"Intended Audience :: Developers",
"Programming Language :: Python",
"Development Status :: 2 - Pre-Alpha",
"Topic :: Database"],
scripts=['bin/axiomatic'],
packages=['axiom',
'axiom.scripts',
'axiom.plugins',
'axiom.test'],
package_data={'axiom': ['examples/*']})
from epsilon.setuphelper import regeneratePluginCache
regeneratePluginCache(distobj)
|
Use new Epsilon versioned feature.
|
Use new Epsilon versioned feature.
|
Python
|
mit
|
twisted/axiom,hawkowl/axiom
|
from distutils.core import setup
+
+ import axiom
distobj = setup(
name="Axiom",
- version="0.1",
+ version=axiom.version.short(),
maintainer="Divmod, Inc.",
maintainer_email="[email protected]",
- url="http://divmod.org/trac/wiki/AxiomProject",
+ url="http://divmod.org/trac/wiki/DivmodAxiom",
license="MIT",
platforms=["any"],
description="An in-process object-relational database",
classifiers=[
"Intended Audience :: Developers",
"Programming Language :: Python",
"Development Status :: 2 - Pre-Alpha",
"Topic :: Database"],
scripts=['bin/axiomatic'],
packages=['axiom',
'axiom.scripts',
'axiom.plugins',
'axiom.test'],
package_data={'axiom': ['examples/*']})
from epsilon.setuphelper import regeneratePluginCache
regeneratePluginCache(distobj)
|
Use new Epsilon versioned feature.
|
## Code Before:
from distutils.core import setup
distobj = setup(
name="Axiom",
version="0.1",
maintainer="Divmod, Inc.",
maintainer_email="[email protected]",
url="http://divmod.org/trac/wiki/AxiomProject",
license="MIT",
platforms=["any"],
description="An in-process object-relational database",
classifiers=[
"Intended Audience :: Developers",
"Programming Language :: Python",
"Development Status :: 2 - Pre-Alpha",
"Topic :: Database"],
scripts=['bin/axiomatic'],
packages=['axiom',
'axiom.scripts',
'axiom.plugins',
'axiom.test'],
package_data={'axiom': ['examples/*']})
from epsilon.setuphelper import regeneratePluginCache
regeneratePluginCache(distobj)
## Instruction:
Use new Epsilon versioned feature.
## Code After:
from distutils.core import setup
import axiom
distobj = setup(
name="Axiom",
version=axiom.version.short(),
maintainer="Divmod, Inc.",
maintainer_email="[email protected]",
url="http://divmod.org/trac/wiki/DivmodAxiom",
license="MIT",
platforms=["any"],
description="An in-process object-relational database",
classifiers=[
"Intended Audience :: Developers",
"Programming Language :: Python",
"Development Status :: 2 - Pre-Alpha",
"Topic :: Database"],
scripts=['bin/axiomatic'],
packages=['axiom',
'axiom.scripts',
'axiom.plugins',
'axiom.test'],
package_data={'axiom': ['examples/*']})
from epsilon.setuphelper import regeneratePluginCache
regeneratePluginCache(distobj)
|
// ... existing code ...
from distutils.core import setup
import axiom
// ... modified code ...
name="Axiom",
version=axiom.version.short(),
maintainer="Divmod, Inc.",
...
maintainer_email="[email protected]",
url="http://divmod.org/trac/wiki/DivmodAxiom",
license="MIT",
// ... rest of the code ...
|
bc8675b170748b51403fb31d03ed06399268cb7b
|
examples/test_deferred_asserts.py
|
examples/test_deferred_asserts.py
|
import pytest
from seleniumbase import BaseCase
class DeferredAssertTests(BaseCase):
@pytest.mark.expected_failure
def test_deferred_asserts(self):
self.open("https://xkcd.com/993/")
self.wait_for_element("#comic")
print("\n(This test should fail)")
self.deferred_assert_element('img[alt="Brand Identity"]')
self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail
self.deferred_assert_element("#comicmap")
self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail
self.deferred_assert_text("Random", "#middleContainer")
self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail
self.process_deferred_asserts()
|
import pytest
from seleniumbase import BaseCase
class DeferredAssertTests(BaseCase):
@pytest.mark.expected_failure
def test_deferred_asserts(self):
self.open("https://xkcd.com/993/")
self.wait_for_element("#comic")
print("\n(This test should fail)")
self.deferred_assert_element('img[alt="Brand Identity"]')
self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail
self.deferred_assert_element("#comicmap")
self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail
self.deferred_assert_text("Random", "#middleContainer")
self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail
self.deferred_assert_exact_text("Brand Identity", "#ctitle")
self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail
self.process_deferred_asserts()
|
Update an example test that uses deferred asserts
|
Update an example test that uses deferred asserts
|
Python
|
mit
|
mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase
|
import pytest
from seleniumbase import BaseCase
class DeferredAssertTests(BaseCase):
@pytest.mark.expected_failure
def test_deferred_asserts(self):
self.open("https://xkcd.com/993/")
self.wait_for_element("#comic")
print("\n(This test should fail)")
self.deferred_assert_element('img[alt="Brand Identity"]')
self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail
self.deferred_assert_element("#comicmap")
self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail
self.deferred_assert_text("Random", "#middleContainer")
self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail
+ self.deferred_assert_exact_text("Brand Identity", "#ctitle")
+ self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail
self.process_deferred_asserts()
|
Update an example test that uses deferred asserts
|
## Code Before:
import pytest
from seleniumbase import BaseCase
class DeferredAssertTests(BaseCase):
@pytest.mark.expected_failure
def test_deferred_asserts(self):
self.open("https://xkcd.com/993/")
self.wait_for_element("#comic")
print("\n(This test should fail)")
self.deferred_assert_element('img[alt="Brand Identity"]')
self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail
self.deferred_assert_element("#comicmap")
self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail
self.deferred_assert_text("Random", "#middleContainer")
self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail
self.process_deferred_asserts()
## Instruction:
Update an example test that uses deferred asserts
## Code After:
import pytest
from seleniumbase import BaseCase
class DeferredAssertTests(BaseCase):
@pytest.mark.expected_failure
def test_deferred_asserts(self):
self.open("https://xkcd.com/993/")
self.wait_for_element("#comic")
print("\n(This test should fail)")
self.deferred_assert_element('img[alt="Brand Identity"]')
self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail
self.deferred_assert_element("#comicmap")
self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail
self.deferred_assert_text("Random", "#middleContainer")
self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail
self.deferred_assert_exact_text("Brand Identity", "#ctitle")
self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail
self.process_deferred_asserts()
|
// ... existing code ...
self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail
self.deferred_assert_exact_text("Brand Identity", "#ctitle")
self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail
self.process_deferred_asserts()
// ... rest of the code ...
|
b242de3217ad9cf6a98ca2513ed1e4f66d2537ad
|
tests/NongeneratingSymbolsRemove/SimpleTest.py
|
tests/NongeneratingSymbolsRemove/SimpleTest.py
|
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class SimpleTest(TestCase):
pass
if __name__ == '__main__':
main()
|
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class A(Nonterminal):
pass
class B(Nonterminal):
pass
class C(Nonterminal):
pass
class RuleAto0B(Rule):
fromSymbol = A
right = [0, B]
class RuleBto1(Rule):
fromSymbol = B
toSymbol = 1
class SimpleTest(TestCase):
def test_simpleTest(self):
g = Grammar(terminals=[0, 1],
nonterminals=[A, B, C],
rules=[RuleAto0B, RuleBto1])
changed = ContextFree.remove_nongenerastingSymbols(g)
self.assertTrue(changed.have_term([0, 1]))
self.assertTrue(changed.have_nonterm([A, B]))
self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
|
Add simple test of removing nongenerating symbols
|
Add simple test of removing nongenerating symbols
|
Python
|
mit
|
PatrikValkovic/grammpy
|
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
+ class A(Nonterminal):
+ pass
+
+
+ class B(Nonterminal):
+ pass
+
+
+ class C(Nonterminal):
+ pass
+
+
+ class RuleAto0B(Rule):
+ fromSymbol = A
+ right = [0, B]
+
+
+ class RuleBto1(Rule):
+ fromSymbol = B
+ toSymbol = 1
+
+
class SimpleTest(TestCase):
- pass
+ def test_simpleTest(self):
+ g = Grammar(terminals=[0, 1],
+ nonterminals=[A, B, C],
+ rules=[RuleAto0B, RuleBto1])
+ changed = ContextFree.remove_nongenerastingSymbols(g)
+ self.assertTrue(changed.have_term([0, 1]))
+ self.assertTrue(changed.have_nonterm([A, B]))
+ self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
|
Add simple test of removing nongenerating symbols
|
## Code Before:
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class SimpleTest(TestCase):
pass
if __name__ == '__main__':
main()
## Instruction:
Add simple test of removing nongenerating symbols
## Code After:
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class A(Nonterminal):
pass
class B(Nonterminal):
pass
class C(Nonterminal):
pass
class RuleAto0B(Rule):
fromSymbol = A
right = [0, B]
class RuleBto1(Rule):
fromSymbol = B
toSymbol = 1
class SimpleTest(TestCase):
def test_simpleTest(self):
g = Grammar(terminals=[0, 1],
nonterminals=[A, B, C],
rules=[RuleAto0B, RuleBto1])
changed = ContextFree.remove_nongenerastingSymbols(g)
self.assertTrue(changed.have_term([0, 1]))
self.assertTrue(changed.have_nonterm([A, B]))
self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
|
...
class A(Nonterminal):
pass
class B(Nonterminal):
pass
class C(Nonterminal):
pass
class RuleAto0B(Rule):
fromSymbol = A
right = [0, B]
class RuleBto1(Rule):
fromSymbol = B
toSymbol = 1
class SimpleTest(TestCase):
def test_simpleTest(self):
g = Grammar(terminals=[0, 1],
nonterminals=[A, B, C],
rules=[RuleAto0B, RuleBto1])
changed = ContextFree.remove_nongenerastingSymbols(g)
self.assertTrue(changed.have_term([0, 1]))
self.assertTrue(changed.have_nonterm([A, B]))
self.assertFalse(changed.have_nonterm(C))
...
|
b494a5b2ed94c1def6fb8bbbab5df5612ef30aa7
|
tests/test_api.py
|
tests/test_api.py
|
from bmi_tester.api import check_bmi
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
fp.write("input.yaml")
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
|
import os
from bmi_tester.api import check_bmi
def touch_file(fname):
with open(fname, "w"):
pass
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
fp.write(os.linesep.join(["input.yaml", "data.dat"]))
touch_file("input.yaml")
touch_file("data.dat")
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
|
Test a manifest with multiple files.
|
Test a manifest with multiple files.
|
Python
|
mit
|
csdms/bmi-tester
|
+ import os
+
from bmi_tester.api import check_bmi
+
+
+ def touch_file(fname):
+ with open(fname, "w"):
+ pass
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
+ touch_file("input.yaml")
- with open("input.yaml", "w"):
- pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
+ touch_file("input.yaml")
- with open("input.yaml", "w"):
- pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
+ fp.write(os.linesep.join(["input.yaml", "data.dat"]))
- fp.write("input.yaml")
+ touch_file("input.yaml")
+ touch_file("data.dat")
- with open("input.yaml", "w"):
- pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
|
Test a manifest with multiple files.
|
## Code Before:
from bmi_tester.api import check_bmi
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
fp.write("input.yaml")
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
## Instruction:
Test a manifest with multiple files.
## Code After:
import os
from bmi_tester.api import check_bmi
def touch_file(fname):
with open(fname, "w"):
pass
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
fp.write(os.linesep.join(["input.yaml", "data.dat"]))
touch_file("input.yaml")
touch_file("data.dat")
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
|
// ... existing code ...
import os
from bmi_tester.api import check_bmi
def touch_file(fname):
with open(fname, "w"):
pass
// ... modified code ...
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
...
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
...
with open("manifest.txt", "w") as fp:
fp.write(os.linesep.join(["input.yaml", "data.dat"]))
touch_file("input.yaml")
touch_file("data.dat")
assert (
// ... rest of the code ...
|
bc97d63893858ba8cbcd44f83f4123fdd826ac71
|
addons/bestja_api_user/models.py
|
addons/bestja_api_user/models.py
|
from openerp import models, fields, api
class User(models.Model):
_inherit = 'res.users'
def __init__(self, pool, cr):
super(User, self).__init__(pool, cr)
self._add_permitted_fields(level='privileged', fields={'email'})
self._add_permitted_fields(level='owner', fields={'email'})
@api.one
def _compute_user_access_level(self):
"""
Access level that the current (logged in) user has for the object.
Either "owner", "admin", "privileged" or None.
"""
super(User, self)._compute_user_access_level()
if not self.user_access_level and self.user_has_groups('bestja_api_user.api_access'):
self.user_access_level = 'privileged'
class Partner(models.Model):
_inherit = 'res.partner'
email = fields.Char(groups='bestja_api_user.api_access') # give access to the email field
|
from openerp import models, fields, api
class User(models.Model):
_inherit = 'res.users'
def __init__(self, pool, cr):
super(User, self).__init__(pool, cr)
self._add_permitted_fields(level='privileged', fields={'email'})
self._add_permitted_fields(level='owner', fields={'email'})
@api.one
def _compute_user_access_level(self):
"""
Access level that the current (logged in) user has for the object.
Either "owner", "admin", "privileged" or None.
"""
super(User, self)._compute_user_access_level()
if not self.user_access_level and self.user_has_groups('bestja_api_user.api_access'):
self.user_access_level = 'privileged'
class Partner(models.Model):
_inherit = 'res.partner'
email = fields.Char(groups='base.group_system,bestja_api_user.api_access') # give access to the email field
|
Fix for Partner's email not being accessible to administrator
|
Fix for Partner's email not being accessible to administrator
|
Python
|
agpl-3.0
|
EE/bestja,EE/bestja,ludwiktrammer/bestja,ludwiktrammer/bestja,ludwiktrammer/bestja,EE/bestja
|
from openerp import models, fields, api
class User(models.Model):
_inherit = 'res.users'
def __init__(self, pool, cr):
super(User, self).__init__(pool, cr)
self._add_permitted_fields(level='privileged', fields={'email'})
self._add_permitted_fields(level='owner', fields={'email'})
@api.one
def _compute_user_access_level(self):
"""
Access level that the current (logged in) user has for the object.
Either "owner", "admin", "privileged" or None.
"""
super(User, self)._compute_user_access_level()
if not self.user_access_level and self.user_has_groups('bestja_api_user.api_access'):
self.user_access_level = 'privileged'
class Partner(models.Model):
_inherit = 'res.partner'
- email = fields.Char(groups='bestja_api_user.api_access') # give access to the email field
+ email = fields.Char(groups='base.group_system,bestja_api_user.api_access') # give access to the email field
|
Fix for Partner's email not being accessible to administrator
|
## Code Before:
from openerp import models, fields, api
class User(models.Model):
_inherit = 'res.users'
def __init__(self, pool, cr):
super(User, self).__init__(pool, cr)
self._add_permitted_fields(level='privileged', fields={'email'})
self._add_permitted_fields(level='owner', fields={'email'})
@api.one
def _compute_user_access_level(self):
"""
Access level that the current (logged in) user has for the object.
Either "owner", "admin", "privileged" or None.
"""
super(User, self)._compute_user_access_level()
if not self.user_access_level and self.user_has_groups('bestja_api_user.api_access'):
self.user_access_level = 'privileged'
class Partner(models.Model):
_inherit = 'res.partner'
email = fields.Char(groups='bestja_api_user.api_access') # give access to the email field
## Instruction:
Fix for Partner's email not being accessible to administrator
## Code After:
from openerp import models, fields, api
class User(models.Model):
_inherit = 'res.users'
def __init__(self, pool, cr):
super(User, self).__init__(pool, cr)
self._add_permitted_fields(level='privileged', fields={'email'})
self._add_permitted_fields(level='owner', fields={'email'})
@api.one
def _compute_user_access_level(self):
"""
Access level that the current (logged in) user has for the object.
Either "owner", "admin", "privileged" or None.
"""
super(User, self)._compute_user_access_level()
if not self.user_access_level and self.user_has_groups('bestja_api_user.api_access'):
self.user_access_level = 'privileged'
class Partner(models.Model):
_inherit = 'res.partner'
email = fields.Char(groups='base.group_system,bestja_api_user.api_access') # give access to the email field
|
...
email = fields.Char(groups='base.group_system,bestja_api_user.api_access') # give access to the email field
...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.