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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
017182e317aa33c0bb4c13541ef19b11bb48e250 | members/views.py | members/views.py | from django.shortcuts import render
from django.http import HttpResponse
from .models import User
def homepage(request):
return render(request, "index.html", {})
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return HttpResponse(json_data, mimetype='application/json')
| from django.shortcuts import render
from django.http import HttpResponse
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data | Add view for searching users and return json format | Add view for searching users and return json format
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | from django.shortcuts import render
from django.http import HttpResponse
+ from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
+ @json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
+ return json_data
- return HttpResponse(json_data, mimetype='application/json')
- | Add view for searching users and return json format | ## Code Before:
from django.shortcuts import render
from django.http import HttpResponse
from .models import User
def homepage(request):
return render(request, "index.html", {})
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return HttpResponse(json_data, mimetype='application/json')
## Instruction:
Add view for searching users and return json format
## Code After:
from django.shortcuts import render
from django.http import HttpResponse
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data | # ... existing code ...
from hackfmi.utils import json_view
from .models import User
# ... modified code ...
@json_view
def search(request, name):
...
return json_data
# ... rest of the code ... |
261cb5aecc52d07b10d826e8b22d17817d1c3529 | web/backend/backend_django/apps/capacity/management/commands/importpath.py | web/backend/backend_django/apps/capacity/management/commands/importpath.py | from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
self.stdout.write("Done") | from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
i = 0
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
if i%1000==0: print(i)
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
i = i+1
self.stdout.write("Done") | Update import path method to reflect behaviour | Update import path method to reflect behaviour
| Python | apache-2.0 | tOverney/ADA-Project,tOverney/ADA-Project,tOverney/ADA-Project | from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
-
+ i = 0
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
+
+ if i%1000==0: print(i)
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
+ i = i+1
+
self.stdout.write("Done") | Update import path method to reflect behaviour | ## Code Before:
from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
self.stdout.write("Done")
## Instruction:
Update import path method to reflect behaviour
## Code After:
from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
i = 0
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
if i%1000==0: print(i)
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
i = i+1
self.stdout.write("Done") | // ... existing code ...
print(len(trips))
i = 0
for k, path in trips.items():
// ... modified code ...
stop_id = k[1]
if i%1000==0: print(i)
...
i = i+1
self.stdout.write("Done")
// ... rest of the code ... |
7b5850d1b89d34ff9a60c3862d18691961c86656 | poisson/tests/test_irf.py | poisson/tests/test_irf.py | from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_grid_initialize():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
| from nose.tools import assert_equal
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_initialize_defaults():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_initialize_from_file_like():
from StringIO import StringIO
import yaml
config = StringIO(yaml.dump({'shape': (7, 5)}))
model = BmiPoisson()
model.initialize(config)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_initialize_from_file():
import os
import yaml
import tempfile
with tempfile.NamedTemporaryFile('w', delete=False) as fp:
fp.write(yaml.dump({'shape': (7, 5)}))
name = fp.name
model = BmiPoisson()
model.initialize(name)
os.remove(name)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
| Test initialize with filename and file-like. | Test initialize with filename and file-like.
| Python | mit | mperignon/bmi-delta,mperignon/bmi-STM,mperignon/bmi-STM,mperignon/bmi-delta | + from nose.tools import assert_equal
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
- def test_grid_initialize():
+ def test_initialize_defaults():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
+
+
+ def test_initialize_from_file_like():
+ from StringIO import StringIO
+ import yaml
+
+ config = StringIO(yaml.dump({'shape': (7, 5)}))
+ model = BmiPoisson()
+ model.initialize(config)
+
+ assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
+
+
+ def test_initialize_from_file():
+ import os
+ import yaml
+ import tempfile
+
+ with tempfile.NamedTemporaryFile('w', delete=False) as fp:
+ fp.write(yaml.dump({'shape': (7, 5)}))
+ name = fp.name
+
+ model = BmiPoisson()
+ model.initialize(name)
+
+ os.remove(name)
+
+ assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
| Test initialize with filename and file-like. | ## Code Before:
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_grid_initialize():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
## Instruction:
Test initialize with filename and file-like.
## Code After:
from nose.tools import assert_equal
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_initialize_defaults():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_initialize_from_file_like():
from StringIO import StringIO
import yaml
config = StringIO(yaml.dump({'shape': (7, 5)}))
model = BmiPoisson()
model.initialize(config)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_initialize_from_file():
import os
import yaml
import tempfile
with tempfile.NamedTemporaryFile('w', delete=False) as fp:
fp.write(yaml.dump({'shape': (7, 5)}))
name = fp.name
model = BmiPoisson()
model.initialize(name)
os.remove(name)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
| // ... existing code ...
from nose.tools import assert_equal
from numpy.testing import assert_almost_equal, assert_array_less
// ... modified code ...
def test_initialize_defaults():
model = BmiPoisson()
...
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_initialize_from_file_like():
from StringIO import StringIO
import yaml
config = StringIO(yaml.dump({'shape': (7, 5)}))
model = BmiPoisson()
model.initialize(config)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_initialize_from_file():
import os
import yaml
import tempfile
with tempfile.NamedTemporaryFile('w', delete=False) as fp:
fp.write(yaml.dump({'shape': (7, 5)}))
name = fp.name
model = BmiPoisson()
model.initialize(name)
os.remove(name)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
// ... rest of the code ... |
8e68d7fab7b39828c31da734c8f47305c49e3fdd | twitterbot.py | twitterbot.py | import tweepy
import time
class TwitterBot:
def __init__(self, auth, listen_msg, response_msg):
auth = tweepy.OAuthHandler(auth['consumer_key'], auth['consumer_secret'])
auth.set_access_token(auth['access_token'], auth['access_token_secret'])
self.api = tweepy.API(auth)
self.responded_tweets = set()
self.listen, self.response = listen_msg, response_msg
def tweet(self, message, mention_id=None):
self.api.update_status(status=message, mention_id=mention_id)
def respond(self, mention_text, message):
for mention in self.api.mentions_timeline(count=1):
if mention_text in mention.text.lower():
self.tweet(message.format(mention.user.screen_name), mention.id)
self.api.create_favorite(mention.id)
print('Responded to {0}.'.format(mention.user.screen_name))
if __name__ == '__main__':
tb = TwitterBot()
tb.respond('hi', '{} hey buddy!')
| import tweepy
import time
class TwitterBot:
def __init__(self, auth, listen_msg, response_msg):
auth = tweepy.OAuthHandler(auth['consumer_key'], auth['consumer_secret'])
auth.set_access_token(auth['access_token'], auth['access_token_secret'])
self.api = tweepy.API(auth)
self.responded_tweets = set()
self.listen, self.response = listen_msg, response_msg
def tweet(self, message, mention_id=None):
self.api.update_status(status=message, in_reply_to_status_id=mention_id)
def respond(self, mention_text, message):
for mention in self.api.mentions_timeline(count=1):
if mention_text in mention.text.lower():
self.tweet(message.format(mention.user.screen_name), mention.id)
self.api.create_favorite(mention.id)
print('Responded to {0}.'.format(mention.user.screen_name))
if __name__ == '__main__':
tb = TwitterBot()
tb.respond('hi', '{} hey buddy!')
| Update Tweet method for api change | Update Tweet method for api change
| Python | mit | kshvmdn/twitter-autoreply,kshvmdn/twitter-birthday-responder,kshvmdn/TwitterBirthdayResponder | import tweepy
import time
class TwitterBot:
def __init__(self, auth, listen_msg, response_msg):
auth = tweepy.OAuthHandler(auth['consumer_key'], auth['consumer_secret'])
auth.set_access_token(auth['access_token'], auth['access_token_secret'])
self.api = tweepy.API(auth)
self.responded_tweets = set()
self.listen, self.response = listen_msg, response_msg
def tweet(self, message, mention_id=None):
- self.api.update_status(status=message, mention_id=mention_id)
+ self.api.update_status(status=message, in_reply_to_status_id=mention_id)
def respond(self, mention_text, message):
for mention in self.api.mentions_timeline(count=1):
if mention_text in mention.text.lower():
self.tweet(message.format(mention.user.screen_name), mention.id)
self.api.create_favorite(mention.id)
print('Responded to {0}.'.format(mention.user.screen_name))
if __name__ == '__main__':
tb = TwitterBot()
tb.respond('hi', '{} hey buddy!')
| Update Tweet method for api change | ## Code Before:
import tweepy
import time
class TwitterBot:
def __init__(self, auth, listen_msg, response_msg):
auth = tweepy.OAuthHandler(auth['consumer_key'], auth['consumer_secret'])
auth.set_access_token(auth['access_token'], auth['access_token_secret'])
self.api = tweepy.API(auth)
self.responded_tweets = set()
self.listen, self.response = listen_msg, response_msg
def tweet(self, message, mention_id=None):
self.api.update_status(status=message, mention_id=mention_id)
def respond(self, mention_text, message):
for mention in self.api.mentions_timeline(count=1):
if mention_text in mention.text.lower():
self.tweet(message.format(mention.user.screen_name), mention.id)
self.api.create_favorite(mention.id)
print('Responded to {0}.'.format(mention.user.screen_name))
if __name__ == '__main__':
tb = TwitterBot()
tb.respond('hi', '{} hey buddy!')
## Instruction:
Update Tweet method for api change
## Code After:
import tweepy
import time
class TwitterBot:
def __init__(self, auth, listen_msg, response_msg):
auth = tweepy.OAuthHandler(auth['consumer_key'], auth['consumer_secret'])
auth.set_access_token(auth['access_token'], auth['access_token_secret'])
self.api = tweepy.API(auth)
self.responded_tweets = set()
self.listen, self.response = listen_msg, response_msg
def tweet(self, message, mention_id=None):
self.api.update_status(status=message, in_reply_to_status_id=mention_id)
def respond(self, mention_text, message):
for mention in self.api.mentions_timeline(count=1):
if mention_text in mention.text.lower():
self.tweet(message.format(mention.user.screen_name), mention.id)
self.api.create_favorite(mention.id)
print('Responded to {0}.'.format(mention.user.screen_name))
if __name__ == '__main__':
tb = TwitterBot()
tb.respond('hi', '{} hey buddy!')
| // ... existing code ...
def tweet(self, message, mention_id=None):
self.api.update_status(status=message, in_reply_to_status_id=mention_id)
// ... rest of the code ... |
72f84b49ea9781f3252c49a1805c0ce19af5c635 | corehq/apps/case_search/dsl_utils.py | corehq/apps/case_search/dsl_utils.py | from django.utils.translation import gettext as _
from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize
from corehq.apps.case_search.exceptions import (
CaseFilterError,
XPathFunctionException,
)
from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS
def unwrap_value(value, context):
"""Returns the value of the node if it is wrapped in a function, otherwise just returns the node
"""
if isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, UnaryExpression) and value.op == '-':
return -1 * value.right
if not isinstance(value, FunctionCall):
return value
try:
return XPATH_VALUE_FUNCTIONS[value.name](value, context)
except KeyError:
raise CaseFilterError(
_("We don't know what to do with the function \"{}\". Accepted functions are: {}").format(
value.name,
", ".join(list(XPATH_VALUE_FUNCTIONS.keys())),
),
serialize(value)
)
except XPathFunctionException as e:
raise CaseFilterError(str(e), serialize(value))
| from django.utils.translation import gettext as _
from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize
from corehq.apps.case_search.exceptions import (
CaseFilterError,
XPathFunctionException,
)
from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS
def unwrap_value(value, context):
"""Returns the value of the node if it is wrapped in a function, otherwise just returns the node
"""
if isinstance(value, UnaryExpression) and value.op == '-':
return -1 * value.right
if not isinstance(value, FunctionCall):
return value
try:
return XPATH_VALUE_FUNCTIONS[value.name](value, context)
except KeyError:
raise CaseFilterError(
_("We don't know what to do with the function \"{}\". Accepted functions are: {}").format(
value.name,
", ".join(list(XPATH_VALUE_FUNCTIONS.keys())),
),
serialize(value)
)
except XPathFunctionException as e:
raise CaseFilterError(str(e), serialize(value))
| Revert "support unwrapping of basic types" | Revert "support unwrapping of basic types"
This reverts commit 86a5a1c8
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | from django.utils.translation import gettext as _
from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize
from corehq.apps.case_search.exceptions import (
CaseFilterError,
XPathFunctionException,
)
from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS
def unwrap_value(value, context):
"""Returns the value of the node if it is wrapped in a function, otherwise just returns the node
"""
- if isinstance(value, (str, int, float, bool)):
- return value
if isinstance(value, UnaryExpression) and value.op == '-':
return -1 * value.right
if not isinstance(value, FunctionCall):
return value
try:
return XPATH_VALUE_FUNCTIONS[value.name](value, context)
except KeyError:
raise CaseFilterError(
_("We don't know what to do with the function \"{}\". Accepted functions are: {}").format(
value.name,
", ".join(list(XPATH_VALUE_FUNCTIONS.keys())),
),
serialize(value)
)
except XPathFunctionException as e:
raise CaseFilterError(str(e), serialize(value))
| Revert "support unwrapping of basic types" | ## Code Before:
from django.utils.translation import gettext as _
from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize
from corehq.apps.case_search.exceptions import (
CaseFilterError,
XPathFunctionException,
)
from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS
def unwrap_value(value, context):
"""Returns the value of the node if it is wrapped in a function, otherwise just returns the node
"""
if isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, UnaryExpression) and value.op == '-':
return -1 * value.right
if not isinstance(value, FunctionCall):
return value
try:
return XPATH_VALUE_FUNCTIONS[value.name](value, context)
except KeyError:
raise CaseFilterError(
_("We don't know what to do with the function \"{}\". Accepted functions are: {}").format(
value.name,
", ".join(list(XPATH_VALUE_FUNCTIONS.keys())),
),
serialize(value)
)
except XPathFunctionException as e:
raise CaseFilterError(str(e), serialize(value))
## Instruction:
Revert "support unwrapping of basic types"
## Code After:
from django.utils.translation import gettext as _
from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize
from corehq.apps.case_search.exceptions import (
CaseFilterError,
XPathFunctionException,
)
from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS
def unwrap_value(value, context):
"""Returns the value of the node if it is wrapped in a function, otherwise just returns the node
"""
if isinstance(value, UnaryExpression) and value.op == '-':
return -1 * value.right
if not isinstance(value, FunctionCall):
return value
try:
return XPATH_VALUE_FUNCTIONS[value.name](value, context)
except KeyError:
raise CaseFilterError(
_("We don't know what to do with the function \"{}\". Accepted functions are: {}").format(
value.name,
", ".join(list(XPATH_VALUE_FUNCTIONS.keys())),
),
serialize(value)
)
except XPathFunctionException as e:
raise CaseFilterError(str(e), serialize(value))
| # ... existing code ...
"""
if isinstance(value, UnaryExpression) and value.op == '-':
# ... rest of the code ... |
87c861f6ed0e73e21983edc3add35954b9f0def5 | apps/configuration/fields.py | apps/configuration/fields.py | import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(str):
return "".join(ch for ch in str if unicodedata.category(ch)[0] != "C")
| import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(input):
valid_chars = ['\n', '\r']
return "".join(ch for ch in input if
unicodedata.category(ch)[0] != "C" or ch in valid_chars)
| Allow linebreaks textareas (should be valid in XML) | Allow linebreaks textareas (should be valid in XML)
| Python | apache-2.0 | CDE-UNIBE/qcat,CDE-UNIBE/qcat,CDE-UNIBE/qcat,CDE-UNIBE/qcat | import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
- def remove_control_characters(str):
+ def remove_control_characters(input):
- return "".join(ch for ch in str if unicodedata.category(ch)[0] != "C")
+ valid_chars = ['\n', '\r']
+ return "".join(ch for ch in input if
+ unicodedata.category(ch)[0] != "C" or ch in valid_chars)
| Allow linebreaks textareas (should be valid in XML) | ## Code Before:
import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(str):
return "".join(ch for ch in str if unicodedata.category(ch)[0] != "C")
## Instruction:
Allow linebreaks textareas (should be valid in XML)
## Code After:
import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(input):
valid_chars = ['\n', '\r']
return "".join(ch for ch in input if
unicodedata.category(ch)[0] != "C" or ch in valid_chars)
| # ... existing code ...
@staticmethod
def remove_control_characters(input):
valid_chars = ['\n', '\r']
return "".join(ch for ch in input if
unicodedata.category(ch)[0] != "C" or ch in valid_chars)
# ... rest of the code ... |
68b5484cfb0910b3ed68e99520decc6aca08bb2d | flask_webapi/__init__.py | flask_webapi/__init__.py | from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema
from marshmallow.utils import missing
from .api import WebAPI
from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route
from .views import ViewBase
| from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema
from marshmallow.utils import missing
from .api import WebAPI
from .errors import APIError
from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route
from .views import ViewBase
| Add import for APIError to make it easy to import by users | Add import for APIError to make it easy to import by users
| Python | mit | viniciuschiele/flask-webapi | from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema
from marshmallow.utils import missing
from .api import WebAPI
+ from .errors import APIError
from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route
from .views import ViewBase
| Add import for APIError to make it easy to import by users | ## Code Before:
from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema
from marshmallow.utils import missing
from .api import WebAPI
from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route
from .views import ViewBase
## Instruction:
Add import for APIError to make it easy to import by users
## Code After:
from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema
from marshmallow.utils import missing
from .api import WebAPI
from .errors import APIError
from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route
from .views import ViewBase
| ...
from .api import WebAPI
from .errors import APIError
from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route
... |
45c773c0d2c90a57949a758ab3ac5c15e2942528 | resource_mgt.py | resource_mgt.py | """Class to show file manipulations"""
import sys
original_file = open('wasteland.txt', mode='rt', encoding='utf-8')
file_to_write = open('wasteland-copy.txt', mode='wt', encoding='utf-8')
file_to_write.write("What are the roots that clutch, ")
file_to_write.write('what branches grow\n')
file_to_write.close()
file_reading = open('wasteland.txt', mode='rt', encoding='utf-8')
for line in file_reading.readlines():
print(line)
file_to_append = open('wasteland-copy.txt', mode='at', encoding='utf-8')
file_to_append.writelines(
['Son of man,\n',
'You cannot say, or guess, ',
'for you know only,\n',
'A heap of broken images, ',
'where the sun beats\n'])
file_to_append.close() | """Class to show file manipulations"""
import sys
original_file = open('wasteland.txt', mode='rt', encoding='utf-8')
file_to_write = open('wasteland-copy.txt', mode='wt', encoding='utf-8')
file_to_write.write("What are the roots that clutch, ")
file_to_write.write('what branches grow\n')
file_to_write.close()
file_reading = open('wasteland.txt', mode='rt', encoding='utf-8')
for line in file_reading.readlines():
print(line)
file_to_append = open('wasteland-copy.txt', mode='at', encoding='utf-8')
file_to_append.writelines(
['Son of man,\n',
'You cannot say, or guess, ',
'for you know only,\n',
'A heap of broken images, ',
'where the sun beats\n'])
file_to_append.close()
def words_per_line(flo):
return [len(line.split()) for line in flo.readlines()]
| Add a words per line function | Add a words per line function
| Python | mit | kentoj/python-fundamentals | """Class to show file manipulations"""
import sys
-
original_file = open('wasteland.txt', mode='rt', encoding='utf-8')
file_to_write = open('wasteland-copy.txt', mode='wt', encoding='utf-8')
file_to_write.write("What are the roots that clutch, ")
file_to_write.write('what branches grow\n')
file_to_write.close()
file_reading = open('wasteland.txt', mode='rt', encoding='utf-8')
for line in file_reading.readlines():
print(line)
-
file_to_append = open('wasteland-copy.txt', mode='at', encoding='utf-8')
file_to_append.writelines(
['Son of man,\n',
'You cannot say, or guess, ',
'for you know only,\n',
'A heap of broken images, ',
'where the sun beats\n'])
file_to_append.close()
+
+
+ def words_per_line(flo):
+ return [len(line.split()) for line in flo.readlines()]
+ | Add a words per line function | ## Code Before:
"""Class to show file manipulations"""
import sys
original_file = open('wasteland.txt', mode='rt', encoding='utf-8')
file_to_write = open('wasteland-copy.txt', mode='wt', encoding='utf-8')
file_to_write.write("What are the roots that clutch, ")
file_to_write.write('what branches grow\n')
file_to_write.close()
file_reading = open('wasteland.txt', mode='rt', encoding='utf-8')
for line in file_reading.readlines():
print(line)
file_to_append = open('wasteland-copy.txt', mode='at', encoding='utf-8')
file_to_append.writelines(
['Son of man,\n',
'You cannot say, or guess, ',
'for you know only,\n',
'A heap of broken images, ',
'where the sun beats\n'])
file_to_append.close()
## Instruction:
Add a words per line function
## Code After:
"""Class to show file manipulations"""
import sys
original_file = open('wasteland.txt', mode='rt', encoding='utf-8')
file_to_write = open('wasteland-copy.txt', mode='wt', encoding='utf-8')
file_to_write.write("What are the roots that clutch, ")
file_to_write.write('what branches grow\n')
file_to_write.close()
file_reading = open('wasteland.txt', mode='rt', encoding='utf-8')
for line in file_reading.readlines():
print(line)
file_to_append = open('wasteland-copy.txt', mode='at', encoding='utf-8')
file_to_append.writelines(
['Son of man,\n',
'You cannot say, or guess, ',
'for you know only,\n',
'A heap of broken images, ',
'where the sun beats\n'])
file_to_append.close()
def words_per_line(flo):
return [len(line.split()) for line in flo.readlines()]
| // ... existing code ...
import sys
// ... modified code ...
file_to_append = open('wasteland-copy.txt', mode='at', encoding='utf-8')
...
file_to_append.close()
def words_per_line(flo):
return [len(line.split()) for line in flo.readlines()]
// ... rest of the code ... |
dbbf8a8de7a3212ac0c91a74a9fe5dd197272483 | VOIAnalyzer.py | VOIAnalyzer.py |
import pandas as pd
import numpy as np
import argparse
import os
|
import pandas as pd
import numpy as np
import argparse
import os
def _analysis(img_mat, voi_mat, voi_no, eps=1e-12):
""" Extract VOI statistices for each VOI.
"""
vec = img_mat[voi_mat == voi_no]
vec2 = vec[~np.isnan(vec)]
# Statistics
v_mean = float(vec2.mean())
v_sd = float(vec2.std(ddof=1))
v_cov = v_sd / (v_mean + eps) * 100.
v_max = float(vec2.max())
v_min = float(vec2.min())
n_vox = vec.size
# Output
out_tab = pd.DataFrame({"VOI No." : [voi_no],
"No. of voxels" : [n_vox],
"Mean" : [v_mean],
"SD" : [v_sd],
"CoV" : [v_cov],
"Max" : [v_max],
"Min" : [v_min]})
return out_tab
def voi_analysis(img_file, voi_file, lut_file=None):
""" Extract VOI values.
It outputs Pandas DataFrame for VOI statistics.
Inputs:
img_file : Path for image to extract VOI values
voi_file : Path for VOI map
lut_file : Path for look-up table for VOI map.
If not None, look-up table is applied to output table.
Output:
out_tab : Pandas DataFrame for VOI statistics.
"""
# Load image & VOI
img_mat, img_aff = utils.loadImage(img_file)[:2]
voi_mat = utils.loadImage(voi_file)[0].astype(np.int16)
# Extract
maxNo = voi_mat.max()
out_tab = pd.concat([_analysis(img_mat, voi_mat, v_no)
for v_no in range(1, maxNo + 1, 1)])
# Calculate volumes (unit: cm3)
vol_per_vox = np.abs(np.prod(np.diag(img_aff[:3, :3])))
out_tab.loc[:, "Volume"] = out_tab.loc[:, "No. of voxels"] / 1000.
# Apply look-up table
if lut_file is not None:
lut = utils.loadLUT(lut_file)
out_tab.loc[:, "VOI"] = out_tab.loc[:, "VOI No."].map(lut)
# Image file name
out_tab.loc[:, "Path"] = img_file
return out_tab
| Implement basis for VOI analyzer. | Implement basis for VOI analyzer.
| Python | mit | spikefairway/VOIAnalyzer |
import pandas as pd
import numpy as np
import argparse
import os
+ def _analysis(img_mat, voi_mat, voi_no, eps=1e-12):
+ """ Extract VOI statistices for each VOI.
+ """
+ vec = img_mat[voi_mat == voi_no]
+ vec2 = vec[~np.isnan(vec)]
+
+ # Statistics
+ v_mean = float(vec2.mean())
+ v_sd = float(vec2.std(ddof=1))
+ v_cov = v_sd / (v_mean + eps) * 100.
+ v_max = float(vec2.max())
+ v_min = float(vec2.min())
+ n_vox = vec.size
+
+ # Output
+ out_tab = pd.DataFrame({"VOI No." : [voi_no],
+ "No. of voxels" : [n_vox],
+ "Mean" : [v_mean],
+ "SD" : [v_sd],
+ "CoV" : [v_cov],
+ "Max" : [v_max],
+ "Min" : [v_min]})
+
+ return out_tab
+
+ def voi_analysis(img_file, voi_file, lut_file=None):
+ """ Extract VOI values.
+ It outputs Pandas DataFrame for VOI statistics.
+
+ Inputs:
+ img_file : Path for image to extract VOI values
+
+ voi_file : Path for VOI map
+
+ lut_file : Path for look-up table for VOI map.
+ If not None, look-up table is applied to output table.
+
+ Output:
+ out_tab : Pandas DataFrame for VOI statistics.
+ """
+ # Load image & VOI
+ img_mat, img_aff = utils.loadImage(img_file)[:2]
+ voi_mat = utils.loadImage(voi_file)[0].astype(np.int16)
+
+ # Extract
+ maxNo = voi_mat.max()
+ out_tab = pd.concat([_analysis(img_mat, voi_mat, v_no)
+ for v_no in range(1, maxNo + 1, 1)])
+
+ # Calculate volumes (unit: cm3)
+ vol_per_vox = np.abs(np.prod(np.diag(img_aff[:3, :3])))
+ out_tab.loc[:, "Volume"] = out_tab.loc[:, "No. of voxels"] / 1000.
+
+ # Apply look-up table
+ if lut_file is not None:
+ lut = utils.loadLUT(lut_file)
+ out_tab.loc[:, "VOI"] = out_tab.loc[:, "VOI No."].map(lut)
+
+ # Image file name
+ out_tab.loc[:, "Path"] = img_file
+
+ return out_tab
- | Implement basis for VOI analyzer. | ## Code Before:
import pandas as pd
import numpy as np
import argparse
import os
## Instruction:
Implement basis for VOI analyzer.
## Code After:
import pandas as pd
import numpy as np
import argparse
import os
def _analysis(img_mat, voi_mat, voi_no, eps=1e-12):
""" Extract VOI statistices for each VOI.
"""
vec = img_mat[voi_mat == voi_no]
vec2 = vec[~np.isnan(vec)]
# Statistics
v_mean = float(vec2.mean())
v_sd = float(vec2.std(ddof=1))
v_cov = v_sd / (v_mean + eps) * 100.
v_max = float(vec2.max())
v_min = float(vec2.min())
n_vox = vec.size
# Output
out_tab = pd.DataFrame({"VOI No." : [voi_no],
"No. of voxels" : [n_vox],
"Mean" : [v_mean],
"SD" : [v_sd],
"CoV" : [v_cov],
"Max" : [v_max],
"Min" : [v_min]})
return out_tab
def voi_analysis(img_file, voi_file, lut_file=None):
""" Extract VOI values.
It outputs Pandas DataFrame for VOI statistics.
Inputs:
img_file : Path for image to extract VOI values
voi_file : Path for VOI map
lut_file : Path for look-up table for VOI map.
If not None, look-up table is applied to output table.
Output:
out_tab : Pandas DataFrame for VOI statistics.
"""
# Load image & VOI
img_mat, img_aff = utils.loadImage(img_file)[:2]
voi_mat = utils.loadImage(voi_file)[0].astype(np.int16)
# Extract
maxNo = voi_mat.max()
out_tab = pd.concat([_analysis(img_mat, voi_mat, v_no)
for v_no in range(1, maxNo + 1, 1)])
# Calculate volumes (unit: cm3)
vol_per_vox = np.abs(np.prod(np.diag(img_aff[:3, :3])))
out_tab.loc[:, "Volume"] = out_tab.loc[:, "No. of voxels"] / 1000.
# Apply look-up table
if lut_file is not None:
lut = utils.loadLUT(lut_file)
out_tab.loc[:, "VOI"] = out_tab.loc[:, "VOI No."].map(lut)
# Image file name
out_tab.loc[:, "Path"] = img_file
return out_tab
| ...
def _analysis(img_mat, voi_mat, voi_no, eps=1e-12):
""" Extract VOI statistices for each VOI.
"""
vec = img_mat[voi_mat == voi_no]
vec2 = vec[~np.isnan(vec)]
# Statistics
v_mean = float(vec2.mean())
v_sd = float(vec2.std(ddof=1))
v_cov = v_sd / (v_mean + eps) * 100.
v_max = float(vec2.max())
v_min = float(vec2.min())
n_vox = vec.size
# Output
out_tab = pd.DataFrame({"VOI No." : [voi_no],
"No. of voxels" : [n_vox],
"Mean" : [v_mean],
"SD" : [v_sd],
"CoV" : [v_cov],
"Max" : [v_max],
"Min" : [v_min]})
return out_tab
def voi_analysis(img_file, voi_file, lut_file=None):
""" Extract VOI values.
It outputs Pandas DataFrame for VOI statistics.
Inputs:
img_file : Path for image to extract VOI values
voi_file : Path for VOI map
lut_file : Path for look-up table for VOI map.
If not None, look-up table is applied to output table.
Output:
out_tab : Pandas DataFrame for VOI statistics.
"""
# Load image & VOI
img_mat, img_aff = utils.loadImage(img_file)[:2]
voi_mat = utils.loadImage(voi_file)[0].astype(np.int16)
# Extract
maxNo = voi_mat.max()
out_tab = pd.concat([_analysis(img_mat, voi_mat, v_no)
for v_no in range(1, maxNo + 1, 1)])
# Calculate volumes (unit: cm3)
vol_per_vox = np.abs(np.prod(np.diag(img_aff[:3, :3])))
out_tab.loc[:, "Volume"] = out_tab.loc[:, "No. of voxels"] / 1000.
# Apply look-up table
if lut_file is not None:
lut = utils.loadLUT(lut_file)
out_tab.loc[:, "VOI"] = out_tab.loc[:, "VOI No."].map(lut)
# Image file name
out_tab.loc[:, "Path"] = img_file
return out_tab
... |
95f48c85aee59906fc498c8c44c34551fca32a43 | tests/blueprints/metrics/test_metrics.py | tests/blueprints/metrics/test_metrics.py |
def test_metrics(make_admin_app):
client = _get_test_client(make_admin_app, True)
response = client.get('/metrics')
assert response.status_code == 200
assert response.content_type == 'text/plain; version=0.0.4; charset=utf-8'
assert response.mimetype == 'text/plain'
assert response.get_data(as_text=True) == (
'users_enabled_count 0\n'
'users_disabled_count 0\n'
'users_suspended_count 0\n'
'users_deleted_count 0\n'
'users_total_count 0\n'
)
def test_disabled_metrics(make_admin_app):
client = _get_test_client(make_admin_app, False)
response = client.get('/metrics')
assert response.status_code == 404
def _get_test_client(make_admin_app, metrics_enabled):
config_overrides = {'METRICS_ENABLED': metrics_enabled}
app = make_admin_app(**config_overrides)
return app.test_client()
|
import pytest
from ...conftest import database_recreated
# To be overridden by test parametrization
@pytest.fixture
def config_overrides():
return {}
@pytest.fixture
def client(config_overrides, make_admin_app, db):
app = make_admin_app(**config_overrides)
with app.app_context():
with database_recreated(db):
yield app.test_client()
@pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': True}])
def test_metrics(client):
response = client.get('/metrics')
assert response.status_code == 200
assert response.content_type == 'text/plain; version=0.0.4; charset=utf-8'
assert response.mimetype == 'text/plain'
assert response.get_data(as_text=True) == (
'users_enabled_count 0\n'
'users_disabled_count 0\n'
'users_suspended_count 0\n'
'users_deleted_count 0\n'
'users_total_count 0\n'
)
@pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': False}])
def test_disabled_metrics(client):
response = client.get('/metrics')
assert response.status_code == 404
| Adjust metrics test to set up/tear down database | Adjust metrics test to set up/tear down database
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps |
+ import pytest
- def test_metrics(make_admin_app):
- client = _get_test_client(make_admin_app, True)
+ from ...conftest import database_recreated
+
+
+ # To be overridden by test parametrization
+ @pytest.fixture
+ def config_overrides():
+ return {}
+
+
+ @pytest.fixture
+ def client(config_overrides, make_admin_app, db):
+ app = make_admin_app(**config_overrides)
+ with app.app_context():
+ with database_recreated(db):
+ yield app.test_client()
+
+
+ @pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': True}])
+ def test_metrics(client):
response = client.get('/metrics')
assert response.status_code == 200
assert response.content_type == 'text/plain; version=0.0.4; charset=utf-8'
assert response.mimetype == 'text/plain'
assert response.get_data(as_text=True) == (
'users_enabled_count 0\n'
'users_disabled_count 0\n'
'users_suspended_count 0\n'
'users_deleted_count 0\n'
'users_total_count 0\n'
)
+ @pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': False}])
- def test_disabled_metrics(make_admin_app):
+ def test_disabled_metrics(client):
- client = _get_test_client(make_admin_app, False)
-
response = client.get('/metrics')
assert response.status_code == 404
-
- def _get_test_client(make_admin_app, metrics_enabled):
- config_overrides = {'METRICS_ENABLED': metrics_enabled}
- app = make_admin_app(**config_overrides)
-
- return app.test_client()
- | Adjust metrics test to set up/tear down database | ## Code Before:
def test_metrics(make_admin_app):
client = _get_test_client(make_admin_app, True)
response = client.get('/metrics')
assert response.status_code == 200
assert response.content_type == 'text/plain; version=0.0.4; charset=utf-8'
assert response.mimetype == 'text/plain'
assert response.get_data(as_text=True) == (
'users_enabled_count 0\n'
'users_disabled_count 0\n'
'users_suspended_count 0\n'
'users_deleted_count 0\n'
'users_total_count 0\n'
)
def test_disabled_metrics(make_admin_app):
client = _get_test_client(make_admin_app, False)
response = client.get('/metrics')
assert response.status_code == 404
def _get_test_client(make_admin_app, metrics_enabled):
config_overrides = {'METRICS_ENABLED': metrics_enabled}
app = make_admin_app(**config_overrides)
return app.test_client()
## Instruction:
Adjust metrics test to set up/tear down database
## Code After:
import pytest
from ...conftest import database_recreated
# To be overridden by test parametrization
@pytest.fixture
def config_overrides():
return {}
@pytest.fixture
def client(config_overrides, make_admin_app, db):
app = make_admin_app(**config_overrides)
with app.app_context():
with database_recreated(db):
yield app.test_client()
@pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': True}])
def test_metrics(client):
response = client.get('/metrics')
assert response.status_code == 200
assert response.content_type == 'text/plain; version=0.0.4; charset=utf-8'
assert response.mimetype == 'text/plain'
assert response.get_data(as_text=True) == (
'users_enabled_count 0\n'
'users_disabled_count 0\n'
'users_suspended_count 0\n'
'users_deleted_count 0\n'
'users_total_count 0\n'
)
@pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': False}])
def test_disabled_metrics(client):
response = client.get('/metrics')
assert response.status_code == 404
| // ... existing code ...
import pytest
from ...conftest import database_recreated
# To be overridden by test parametrization
@pytest.fixture
def config_overrides():
return {}
@pytest.fixture
def client(config_overrides, make_admin_app, db):
app = make_admin_app(**config_overrides)
with app.app_context():
with database_recreated(db):
yield app.test_client()
@pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': True}])
def test_metrics(client):
response = client.get('/metrics')
// ... modified code ...
@pytest.mark.parametrize('config_overrides', [{'METRICS_ENABLED': False}])
def test_disabled_metrics(client):
response = client.get('/metrics')
...
assert response.status_code == 404
// ... rest of the code ... |
b0434a28080d59c27a755b70be195c9f3135bf94 | mdx_linkify/mdx_linkify.py | mdx_linkify/mdx_linkify.py | import bleach
from html5lib.sanitizer import HTMLSanitizer
from markdown.postprocessors import Postprocessor
from markdown import Extension
class MyTokenizer(HTMLSanitizer):
def sanitize_token(self, token):
return token
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks,
tokenizer=MyTokenizer)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
| import bleach
from markdown.postprocessors import Postprocessor
from markdown import Extension
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
| Make compatible with Bleach v2.0 and html5lib v1.0 | Make compatible with Bleach v2.0 and html5lib v1.0
| Python | mit | daGrevis/mdx_linkify | import bleach
-
- from html5lib.sanitizer import HTMLSanitizer
from markdown.postprocessors import Postprocessor
from markdown import Extension
-
-
- class MyTokenizer(HTMLSanitizer):
- def sanitize_token(self, token):
- return token
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
- callbacks=self._callbacks,
+ callbacks=self._callbacks)
- tokenizer=MyTokenizer)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
| Make compatible with Bleach v2.0 and html5lib v1.0 | ## Code Before:
import bleach
from html5lib.sanitizer import HTMLSanitizer
from markdown.postprocessors import Postprocessor
from markdown import Extension
class MyTokenizer(HTMLSanitizer):
def sanitize_token(self, token):
return token
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks,
tokenizer=MyTokenizer)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
## Instruction:
Make compatible with Bleach v2.0 and html5lib v1.0
## Code After:
import bleach
from markdown.postprocessors import Postprocessor
from markdown import Extension
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
| ...
import bleach
...
from markdown import Extension
...
text = bleach.linkify(text,
callbacks=self._callbacks)
return text
... |
f1939ef0eadb164dfbe95bf90b3a4cd8757c8a75 | src/ovirtsdk/infrastructure/common.py | src/ovirtsdk/infrastructure/common.py |
from ovirtsdk.utils.comperator import Comparator
from ovirtsdk.infrastructure.errors import ImmutableError
class Base(object):
''' Decorator base class '''
def __init__(self, context):
self.__context = context
@property
def context(self):
return self.__context
def __getattr__(self, item):
if not self.__dict__.has_key('superclass'):
return self.__getattribute__(item)
return self.superclass.__getattribute__(item)
def __eq__(self, other):
return Comparator.compare(self, other)
def __ne__(self, other):
return not self.__eq__(other)
def __setattr__(self, name, value):
if name in ['__context', 'context']:
raise ImmutableError(name)
else:
super(Base, self).__setattr__(name, value)
|
from ovirtsdk.utils.comperator import Comparator
from ovirtsdk.infrastructure.errors import ImmutableError
class Base(object):
''' Decorator base class '''
def __init__(self, context):
self.__context = context
@property
def context(self):
return self.__context
def __getattr__(self, item):
if not self.__dict__.has_key('superclass'):
return self.__getattribute__(item)
return self.superclass.__getattribute__(item)
def __eq__(self, other):
return Comparator.compare(self, other)
def __ne__(self, other):
return not self.__eq__(other)
def __setattr__(self, name, value):
if name in ['__context', 'context']:
raise ImmutableError(name)
else:
super(Base, self).__setattr__(name, value)
def export(self, outfile, level, namespace_='', name_='', namespacedef_='', pretty_print=True):
# This empty method is necessary in order to avoid exceptions when the
# infrastructure tries to invoke it on a collection decorator that is
# used as a parameter.
pass
| Add empty export method to decorator base | sdk: Add empty export method to decorator base
Decorators for resources and collections extend a common base class, for
example:
class VMSnapshotDisks(Base)
The resource decorators also extend the corresponding parameter class:
class VMSnapshotDisk(params.Disk, Base)
This means that resource decorators implement the "export" method,
responsible for generating the XML representation of the entity, but
collection decorators don't implement it.
There are situations where decorators are used as parameters, for
example, when creating a VM from a snapshot one could use the following
code:
snapshot = vm.snapshots.get(id="...")
The resulting object is a decorator, and it contains references to
decorators of collections, for example to the collection of disks. Later
this object can be used as a parameter, as follows:
snapshots = ovirtsdk.xml.params.Snapshots()
snapshots.add_snapshot(snapshot)
newvm = ovirtsdk.xml.params.VM(
name="newvm",
snapshots=snapshots,
...)
api.vms.add(newvm)
When doing this the infrastructure will try to generate the XML
document, calling the "export" method on the new VM object, and this
will recursively call the "export" methods of all the referenced
objects, including the collection decorators, which will fail because
they don't have such method.
This usage is not good practice, and not efficient, it is better to
avoid using decorators as parameters:
snapshot = ovirtsdk.params.Snapshot(id="...")
snapshots = ovirtsdk.params.Snapshots()
snapshots.add_snapshot(snapshot)
newvm = ovirtsdk.xml.params.VM(
name="newvm",
snapshots=snapshots,
...)
api.vms.add(newvm)
As this is difficult to enforce this patch adds to the Base class an
empty "export" method, so that these operations won't fail.
Change-Id: I6d2e6b9a42ad1a878f8edbbd41f3bb9d60db2bc8
Bug-Url: https://bugzilla.redhat.com/1024696
Signed-off-by: Juan Hernandez <[email protected]>
| Python | apache-2.0 | DragonRoman/ovirt-engine-sdk,DragonRoman/ovirt-engine-sdk,DragonRoman/ovirt-engine-sdk |
from ovirtsdk.utils.comperator import Comparator
from ovirtsdk.infrastructure.errors import ImmutableError
class Base(object):
''' Decorator base class '''
def __init__(self, context):
self.__context = context
@property
def context(self):
return self.__context
def __getattr__(self, item):
if not self.__dict__.has_key('superclass'):
return self.__getattribute__(item)
return self.superclass.__getattribute__(item)
def __eq__(self, other):
return Comparator.compare(self, other)
def __ne__(self, other):
return not self.__eq__(other)
def __setattr__(self, name, value):
if name in ['__context', 'context']:
raise ImmutableError(name)
else:
super(Base, self).__setattr__(name, value)
+ def export(self, outfile, level, namespace_='', name_='', namespacedef_='', pretty_print=True):
+ # This empty method is necessary in order to avoid exceptions when the
+ # infrastructure tries to invoke it on a collection decorator that is
+ # used as a parameter.
+ pass
+ | Add empty export method to decorator base | ## Code Before:
from ovirtsdk.utils.comperator import Comparator
from ovirtsdk.infrastructure.errors import ImmutableError
class Base(object):
''' Decorator base class '''
def __init__(self, context):
self.__context = context
@property
def context(self):
return self.__context
def __getattr__(self, item):
if not self.__dict__.has_key('superclass'):
return self.__getattribute__(item)
return self.superclass.__getattribute__(item)
def __eq__(self, other):
return Comparator.compare(self, other)
def __ne__(self, other):
return not self.__eq__(other)
def __setattr__(self, name, value):
if name in ['__context', 'context']:
raise ImmutableError(name)
else:
super(Base, self).__setattr__(name, value)
## Instruction:
Add empty export method to decorator base
## Code After:
from ovirtsdk.utils.comperator import Comparator
from ovirtsdk.infrastructure.errors import ImmutableError
class Base(object):
''' Decorator base class '''
def __init__(self, context):
self.__context = context
@property
def context(self):
return self.__context
def __getattr__(self, item):
if not self.__dict__.has_key('superclass'):
return self.__getattribute__(item)
return self.superclass.__getattribute__(item)
def __eq__(self, other):
return Comparator.compare(self, other)
def __ne__(self, other):
return not self.__eq__(other)
def __setattr__(self, name, value):
if name in ['__context', 'context']:
raise ImmutableError(name)
else:
super(Base, self).__setattr__(name, value)
def export(self, outfile, level, namespace_='', name_='', namespacedef_='', pretty_print=True):
# This empty method is necessary in order to avoid exceptions when the
# infrastructure tries to invoke it on a collection decorator that is
# used as a parameter.
pass
| # ... existing code ...
super(Base, self).__setattr__(name, value)
def export(self, outfile, level, namespace_='', name_='', namespacedef_='', pretty_print=True):
# This empty method is necessary in order to avoid exceptions when the
# infrastructure tries to invoke it on a collection decorator that is
# used as a parameter.
pass
# ... rest of the code ... |
485f04f0e396444dbb5635b21202b2cd2e0612ff | src/webapp/admin/login.py | src/webapp/admin/login.py | from datetime import timedelta, datetime
from functools import wraps
import hmac
from hashlib import sha1
from flask import Blueprint, session, redirect, url_for, request, current_app
ADMIN = "valid_admin"
TIME_FORMAT = '%Y%m%d%H%M%S'
TIME_LIMIT = timedelta(hours=3)
def _create_hmac(payload):
key = current_app.config["SECRET_KEY"]
payload = payload.encode("utf8")
mac = hmac.new(key, payload, sha1)
return mac.hexdigest()
def set_token():
expire = datetime.now() + TIME_LIMIT
token = expire.strftime(TIME_FORMAT)
session[ADMIN] = "%s|%s" % (token, _create_hmac(token))
def delete_token():
del session[ADMIN]
def _valid_token(token):
try:
token, token_mac = token.split(u"|", 1)
except:
return False
if not token_mac == _create_hmac(token):
return False
if datetime.now().strftime(TIME_FORMAT) < token:
return True
def valid_admin(fn):
@wraps(fn)
def nufun(*args, **kwargs):
if ADMIN in session:
if _valid_token(session[ADMIN]):
set_token()
return fn(*args, **kwargs)
delete_token()
session["next"] = request.path
return redirect(url_for(".login"))
return nufun
| from datetime import timedelta, datetime
from functools import wraps
import hmac
from hashlib import sha1
from flask import Blueprint, session, redirect, url_for, request, current_app
ADMIN = "valid_admin"
TIME_FORMAT = '%Y%m%d%H%M%S'
TIME_LIMIT = timedelta(hours=3)
def _create_hmac(payload):
key = current_app.config["SECRET_KEY"]
payload = payload.encode("utf8")
mac = hmac.new(key, payload, sha1)
return mac.hexdigest()
def set_token():
expire = datetime.now() + TIME_LIMIT
token = expire.strftime(TIME_FORMAT)
session[ADMIN] = "%s|%s" % (token, _create_hmac(token))
def delete_token():
del session[ADMIN]
def _valid_token(token):
try:
token, token_mac = token.split(u"|", 1)
except:
return False
if not token_mac == _create_hmac(token):
return False
if datetime.now().strftime(TIME_FORMAT) < token:
return True
def valid_admin(fn):
@wraps(fn)
def nufun(*args, **kwargs):
if ADMIN in session:
if _valid_token(session[ADMIN]):
set_token()
return fn(*args, **kwargs)
delete_token()
session["next"] = request.script_root + request.path
return redirect(url_for(".login"))
return nufun
| Fix redirect generation for reverse proxied solutions | Fix redirect generation for reverse proxied solutions
| Python | bsd-3-clause | janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system | from datetime import timedelta, datetime
from functools import wraps
import hmac
from hashlib import sha1
from flask import Blueprint, session, redirect, url_for, request, current_app
ADMIN = "valid_admin"
TIME_FORMAT = '%Y%m%d%H%M%S'
TIME_LIMIT = timedelta(hours=3)
def _create_hmac(payload):
key = current_app.config["SECRET_KEY"]
payload = payload.encode("utf8")
mac = hmac.new(key, payload, sha1)
return mac.hexdigest()
def set_token():
expire = datetime.now() + TIME_LIMIT
token = expire.strftime(TIME_FORMAT)
session[ADMIN] = "%s|%s" % (token, _create_hmac(token))
def delete_token():
del session[ADMIN]
def _valid_token(token):
try:
token, token_mac = token.split(u"|", 1)
except:
return False
if not token_mac == _create_hmac(token):
return False
if datetime.now().strftime(TIME_FORMAT) < token:
return True
def valid_admin(fn):
@wraps(fn)
def nufun(*args, **kwargs):
if ADMIN in session:
if _valid_token(session[ADMIN]):
set_token()
return fn(*args, **kwargs)
delete_token()
- session["next"] = request.path
+ session["next"] = request.script_root + request.path
return redirect(url_for(".login"))
return nufun
| Fix redirect generation for reverse proxied solutions | ## Code Before:
from datetime import timedelta, datetime
from functools import wraps
import hmac
from hashlib import sha1
from flask import Blueprint, session, redirect, url_for, request, current_app
ADMIN = "valid_admin"
TIME_FORMAT = '%Y%m%d%H%M%S'
TIME_LIMIT = timedelta(hours=3)
def _create_hmac(payload):
key = current_app.config["SECRET_KEY"]
payload = payload.encode("utf8")
mac = hmac.new(key, payload, sha1)
return mac.hexdigest()
def set_token():
expire = datetime.now() + TIME_LIMIT
token = expire.strftime(TIME_FORMAT)
session[ADMIN] = "%s|%s" % (token, _create_hmac(token))
def delete_token():
del session[ADMIN]
def _valid_token(token):
try:
token, token_mac = token.split(u"|", 1)
except:
return False
if not token_mac == _create_hmac(token):
return False
if datetime.now().strftime(TIME_FORMAT) < token:
return True
def valid_admin(fn):
@wraps(fn)
def nufun(*args, **kwargs):
if ADMIN in session:
if _valid_token(session[ADMIN]):
set_token()
return fn(*args, **kwargs)
delete_token()
session["next"] = request.path
return redirect(url_for(".login"))
return nufun
## Instruction:
Fix redirect generation for reverse proxied solutions
## Code After:
from datetime import timedelta, datetime
from functools import wraps
import hmac
from hashlib import sha1
from flask import Blueprint, session, redirect, url_for, request, current_app
ADMIN = "valid_admin"
TIME_FORMAT = '%Y%m%d%H%M%S'
TIME_LIMIT = timedelta(hours=3)
def _create_hmac(payload):
key = current_app.config["SECRET_KEY"]
payload = payload.encode("utf8")
mac = hmac.new(key, payload, sha1)
return mac.hexdigest()
def set_token():
expire = datetime.now() + TIME_LIMIT
token = expire.strftime(TIME_FORMAT)
session[ADMIN] = "%s|%s" % (token, _create_hmac(token))
def delete_token():
del session[ADMIN]
def _valid_token(token):
try:
token, token_mac = token.split(u"|", 1)
except:
return False
if not token_mac == _create_hmac(token):
return False
if datetime.now().strftime(TIME_FORMAT) < token:
return True
def valid_admin(fn):
@wraps(fn)
def nufun(*args, **kwargs):
if ADMIN in session:
if _valid_token(session[ADMIN]):
set_token()
return fn(*args, **kwargs)
delete_token()
session["next"] = request.script_root + request.path
return redirect(url_for(".login"))
return nufun
| // ... existing code ...
delete_token()
session["next"] = request.script_root + request.path
return redirect(url_for(".login"))
// ... rest of the code ... |
a612a245937781e86391e5c3ec8a740f36b405ce | problems/19/Solver.py | problems/19/Solver.py | class Solver:
def solve(self, start_number):
recipient = 1
remaining = start_number
power = 1
while remaining > 1:
new_remaining = remaining // 2
remaining_was_odd = remaining % 2
power *= 2
remaining = new_remaining
if remaining_was_odd:
recipient += power
return recipient
def solve_b(self, start_number):
elves = list(range(1, start_number + 1))
current_elf_index = 0
while len(elves) > 1:
jump_distance = len(elves) // 2
target_elf = jump_distance + current_elf_index
if target_elf >= len(elves):
del elves[target_elf - len(elves)]
current_elf_index -= 1
else:
del elves[target_elf]
current_elf_index += 1
current_elf_index %= len(elves)
return elves[current_elf_index]
| class Solver:
def __init__(self):
self.next_elves = {}
def solve(self, start_number):
recipient = 1
remaining = start_number
power = 1
while remaining > 1:
new_remaining = remaining // 2
remaining_was_odd = remaining % 2
power *= 2
remaining = new_remaining
if remaining_was_odd:
recipient += power
return recipient
def solve_b(self, start_number):
self.next_elves = {index: index + 1 for index in range(start_number)}
self.next_elves[start_number - 1] = 0
current_elf_index = 0
elves_remaining = start_number
while elves_remaining > 1:
target_elf = current_elf_index
jump_distance = elves_remaining // 2
for i in range(jump_distance):
previous_elf = target_elf
target_elf = self.next_elves[target_elf]
# remove target elf
self.delete_target_elf(previous_elf, target_elf)
current_elf_index = self.next_elves[current_elf_index]
elves_remaining -= 1
return current_elf_index + 1
def delete_target_elf(self, previous_elf, target_elf):
next_elf = self.next_elves[target_elf]
self.next_elves[previous_elf] = next_elf
target_elf %= len(self.next_elves)
| Refactor to use linked list | Refactor to use linked list
| Python | mit | tmct/adventOfCode2016 | class Solver:
+ def __init__(self):
+ self.next_elves = {}
+
def solve(self, start_number):
recipient = 1
remaining = start_number
power = 1
while remaining > 1:
new_remaining = remaining // 2
remaining_was_odd = remaining % 2
power *= 2
remaining = new_remaining
if remaining_was_odd:
recipient += power
return recipient
def solve_b(self, start_number):
- elves = list(range(1, start_number + 1))
+ self.next_elves = {index: index + 1 for index in range(start_number)}
+ self.next_elves[start_number - 1] = 0
current_elf_index = 0
+ elves_remaining = start_number
- while len(elves) > 1:
+ while elves_remaining > 1:
- jump_distance = len(elves) // 2
- target_elf = jump_distance + current_elf_index
+ target_elf = current_elf_index
+ jump_distance = elves_remaining // 2
+ for i in range(jump_distance):
+ previous_elf = target_elf
- if target_elf >= len(elves):
- del elves[target_elf - len(elves)]
- current_elf_index -= 1
- else:
- del elves[target_elf]
+ target_elf = self.next_elves[target_elf]
- current_elf_index += 1
- current_elf_index %= len(elves)
- return elves[current_elf_index]
+ # remove target elf
+ self.delete_target_elf(previous_elf, target_elf)
+ current_elf_index = self.next_elves[current_elf_index]
+ elves_remaining -= 1
+ return current_elf_index + 1
+
+ def delete_target_elf(self, previous_elf, target_elf):
+ next_elf = self.next_elves[target_elf]
+ self.next_elves[previous_elf] = next_elf
+ target_elf %= len(self.next_elves)
+ | Refactor to use linked list | ## Code Before:
class Solver:
def solve(self, start_number):
recipient = 1
remaining = start_number
power = 1
while remaining > 1:
new_remaining = remaining // 2
remaining_was_odd = remaining % 2
power *= 2
remaining = new_remaining
if remaining_was_odd:
recipient += power
return recipient
def solve_b(self, start_number):
elves = list(range(1, start_number + 1))
current_elf_index = 0
while len(elves) > 1:
jump_distance = len(elves) // 2
target_elf = jump_distance + current_elf_index
if target_elf >= len(elves):
del elves[target_elf - len(elves)]
current_elf_index -= 1
else:
del elves[target_elf]
current_elf_index += 1
current_elf_index %= len(elves)
return elves[current_elf_index]
## Instruction:
Refactor to use linked list
## Code After:
class Solver:
def __init__(self):
self.next_elves = {}
def solve(self, start_number):
recipient = 1
remaining = start_number
power = 1
while remaining > 1:
new_remaining = remaining // 2
remaining_was_odd = remaining % 2
power *= 2
remaining = new_remaining
if remaining_was_odd:
recipient += power
return recipient
def solve_b(self, start_number):
self.next_elves = {index: index + 1 for index in range(start_number)}
self.next_elves[start_number - 1] = 0
current_elf_index = 0
elves_remaining = start_number
while elves_remaining > 1:
target_elf = current_elf_index
jump_distance = elves_remaining // 2
for i in range(jump_distance):
previous_elf = target_elf
target_elf = self.next_elves[target_elf]
# remove target elf
self.delete_target_elf(previous_elf, target_elf)
current_elf_index = self.next_elves[current_elf_index]
elves_remaining -= 1
return current_elf_index + 1
def delete_target_elf(self, previous_elf, target_elf):
next_elf = self.next_elves[target_elf]
self.next_elves[previous_elf] = next_elf
target_elf %= len(self.next_elves)
| // ... existing code ...
class Solver:
def __init__(self):
self.next_elves = {}
def solve(self, start_number):
// ... modified code ...
def solve_b(self, start_number):
self.next_elves = {index: index + 1 for index in range(start_number)}
self.next_elves[start_number - 1] = 0
current_elf_index = 0
elves_remaining = start_number
while elves_remaining > 1:
target_elf = current_elf_index
jump_distance = elves_remaining // 2
for i in range(jump_distance):
previous_elf = target_elf
target_elf = self.next_elves[target_elf]
# remove target elf
self.delete_target_elf(previous_elf, target_elf)
current_elf_index = self.next_elves[current_elf_index]
elves_remaining -= 1
return current_elf_index + 1
def delete_target_elf(self, previous_elf, target_elf):
next_elf = self.next_elves[target_elf]
self.next_elves[previous_elf] = next_elf
target_elf %= len(self.next_elves)
// ... rest of the code ... |
220b6a9fee0f307d4de1e48b29093812f7dd10ec | var/spack/repos/builtin/packages/m4/package.py | var/spack/repos/builtin/packages/m4/package.py | from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
depends_on('libsigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
| from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
variant('sigsegv', default=True, description="Build the libsigsegv dependency")
depends_on('libsigsegv', when='+sigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
| Make libsigsegv an optional dependency | Make libsigsegv an optional dependency
| Python | lgpl-2.1 | lgarren/spack,mfherbst/spack,LLNL/spack,TheTimmy/spack,EmreAtes/spack,LLNL/spack,tmerrick1/spack,krafczyk/spack,TheTimmy/spack,TheTimmy/spack,lgarren/spack,skosukhin/spack,matthiasdiener/spack,TheTimmy/spack,mfherbst/spack,skosukhin/spack,krafczyk/spack,lgarren/spack,mfherbst/spack,matthiasdiener/spack,matthiasdiener/spack,mfherbst/spack,krafczyk/spack,iulian787/spack,iulian787/spack,matthiasdiener/spack,LLNL/spack,LLNL/spack,tmerrick1/spack,lgarren/spack,EmreAtes/spack,EmreAtes/spack,mfherbst/spack,lgarren/spack,LLNL/spack,TheTimmy/spack,iulian787/spack,krafczyk/spack,EmreAtes/spack,iulian787/spack,tmerrick1/spack,skosukhin/spack,krafczyk/spack,iulian787/spack,skosukhin/spack,tmerrick1/spack,tmerrick1/spack,skosukhin/spack,EmreAtes/spack,matthiasdiener/spack | from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
+ variant('sigsegv', default=True, description="Build the libsigsegv dependency")
+
- depends_on('libsigsegv')
+ depends_on('libsigsegv', when='+sigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
| Make libsigsegv an optional dependency | ## Code Before:
from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
depends_on('libsigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
## Instruction:
Make libsigsegv an optional dependency
## Code After:
from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
variant('sigsegv', default=True, description="Build the libsigsegv dependency")
depends_on('libsigsegv', when='+sigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
| # ... existing code ...
variant('sigsegv', default=True, description="Build the libsigsegv dependency")
depends_on('libsigsegv', when='+sigsegv')
# ... rest of the code ... |
bdcaaf4ab999c51a6633b7e72971d7594de0b66b | bin/clean_unused_headers.py | bin/clean_unused_headers.py | from __future__ import print_function
import sys
import os
import re
from subprocess import check_output
IMAGE_PATTERN = re.compile(
'linux-image-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
HEADER_PATTERN = re.compile(
'linux-headers-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
def get_all_packages():
for line in check_output(['dpkg', '-l']).split('\n'):
if line.startswith('ii'):
# print(line.split(' '))
yield line.split()[1]
def find_group(pattern, text):
matched = pattern.match(text)
if matched:
return '{version}-{rev}'.format(
version=matched.group('version'),
rev=matched.group('rev'))
return None
def main():
packages = list(get_all_packages())
header_pkgs = filter(lambda x: HEADER_PATTERN.match(x), packages)
image_pkgs = filter(lambda x: IMAGE_PATTERN.match(x), packages)
header_versions = map(lambda x: find_group(HEADER_PATTERN, x), header_pkgs)
image_versions = map(lambda x: find_group(IMAGE_PATTERN, x), image_pkgs)
print(header_pkgs)
print(image_pkgs)
print(header_versions)
print(image_versions)
if __name__ == "__main__":
main()
| from __future__ import print_function
import sys
import os
import re
from subprocess import check_output
IMAGE_PATTERN = re.compile(
'linux-image-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
HEADER_PATTERN = re.compile(
'linux-headers-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
def get_all_packages():
for line in check_output(['dpkg', '-l']).split('\n'):
if line.startswith('ii'):
# print(line.split(' '))
yield line.split()[1]
def find_group(pattern, text):
matched = pattern.match(text)
if matched:
return '{version}-{rev}'.format(
version=matched.group('version'),
rev=matched.group('rev'))
return None
def main():
packages = list(get_all_packages())
header_pkgs = filter(lambda x: HEADER_PATTERN.match(x), packages)
image_pkgs = filter(lambda x: IMAGE_PATTERN.match(x), packages)
header_versions = dict(map(
lambda x: (find_group(HEADER_PATTERN, x), x),
header_pkgs))
image_versions = dict(map(
lambda x: (find_group(IMAGE_PATTERN, x), x),
image_pkgs))
results = []
for version, pkg in header_versions.items():
if version not in image_versions:
results.append(pkg)
print(' '.join(results))
if __name__ == "__main__":
main()
| Add python script to find unused linux-headers packages | Add python script to find unused linux-headers packages
| Python | apache-2.0 | elleryq/oh-my-home,elleryq/oh-my-home,elleryq/oh-my-home | from __future__ import print_function
import sys
import os
import re
from subprocess import check_output
IMAGE_PATTERN = re.compile(
'linux-image-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
HEADER_PATTERN = re.compile(
'linux-headers-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
def get_all_packages():
for line in check_output(['dpkg', '-l']).split('\n'):
if line.startswith('ii'):
# print(line.split(' '))
yield line.split()[1]
def find_group(pattern, text):
matched = pattern.match(text)
if matched:
return '{version}-{rev}'.format(
version=matched.group('version'),
rev=matched.group('rev'))
return None
def main():
packages = list(get_all_packages())
header_pkgs = filter(lambda x: HEADER_PATTERN.match(x), packages)
image_pkgs = filter(lambda x: IMAGE_PATTERN.match(x), packages)
- header_versions = map(lambda x: find_group(HEADER_PATTERN, x), header_pkgs)
- image_versions = map(lambda x: find_group(IMAGE_PATTERN, x), image_pkgs)
- print(header_pkgs)
- print(image_pkgs)
+ header_versions = dict(map(
+ lambda x: (find_group(HEADER_PATTERN, x), x),
+ header_pkgs))
+ image_versions = dict(map(
+ lambda x: (find_group(IMAGE_PATTERN, x), x),
+ image_pkgs))
- print(header_versions)
- print(image_versions)
+ results = []
+ for version, pkg in header_versions.items():
+ if version not in image_versions:
+ results.append(pkg)
+ print(' '.join(results))
if __name__ == "__main__":
main()
| Add python script to find unused linux-headers packages | ## Code Before:
from __future__ import print_function
import sys
import os
import re
from subprocess import check_output
IMAGE_PATTERN = re.compile(
'linux-image-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
HEADER_PATTERN = re.compile(
'linux-headers-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
def get_all_packages():
for line in check_output(['dpkg', '-l']).split('\n'):
if line.startswith('ii'):
# print(line.split(' '))
yield line.split()[1]
def find_group(pattern, text):
matched = pattern.match(text)
if matched:
return '{version}-{rev}'.format(
version=matched.group('version'),
rev=matched.group('rev'))
return None
def main():
packages = list(get_all_packages())
header_pkgs = filter(lambda x: HEADER_PATTERN.match(x), packages)
image_pkgs = filter(lambda x: IMAGE_PATTERN.match(x), packages)
header_versions = map(lambda x: find_group(HEADER_PATTERN, x), header_pkgs)
image_versions = map(lambda x: find_group(IMAGE_PATTERN, x), image_pkgs)
print(header_pkgs)
print(image_pkgs)
print(header_versions)
print(image_versions)
if __name__ == "__main__":
main()
## Instruction:
Add python script to find unused linux-headers packages
## Code After:
from __future__ import print_function
import sys
import os
import re
from subprocess import check_output
IMAGE_PATTERN = re.compile(
'linux-image-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
HEADER_PATTERN = re.compile(
'linux-headers-(?P<version>[0-9\.]+)-(?P<rev>[0-9]{2})-generic')
def get_all_packages():
for line in check_output(['dpkg', '-l']).split('\n'):
if line.startswith('ii'):
# print(line.split(' '))
yield line.split()[1]
def find_group(pattern, text):
matched = pattern.match(text)
if matched:
return '{version}-{rev}'.format(
version=matched.group('version'),
rev=matched.group('rev'))
return None
def main():
packages = list(get_all_packages())
header_pkgs = filter(lambda x: HEADER_PATTERN.match(x), packages)
image_pkgs = filter(lambda x: IMAGE_PATTERN.match(x), packages)
header_versions = dict(map(
lambda x: (find_group(HEADER_PATTERN, x), x),
header_pkgs))
image_versions = dict(map(
lambda x: (find_group(IMAGE_PATTERN, x), x),
image_pkgs))
results = []
for version, pkg in header_versions.items():
if version not in image_versions:
results.append(pkg)
print(' '.join(results))
if __name__ == "__main__":
main()
| // ... existing code ...
image_pkgs = filter(lambda x: IMAGE_PATTERN.match(x), packages)
header_versions = dict(map(
lambda x: (find_group(HEADER_PATTERN, x), x),
header_pkgs))
image_versions = dict(map(
lambda x: (find_group(IMAGE_PATTERN, x), x),
image_pkgs))
results = []
for version, pkg in header_versions.items():
if version not in image_versions:
results.append(pkg)
print(' '.join(results))
// ... rest of the code ... |
09c24ac93b6e697b48c52b614fe92f7978fe2320 | linter.py | linter.py |
from SublimeLinter.lint import Linter
import sublime
class Iverilog(Linter):
# http://www.sublimelinter.com/en/stable/linter_attributes.html
name = "iverilog"
cmd = "iverilog ${args}"
tempfile_suffix = "verilog"
multiline = True
on_stderr = None
# fmt: off
defaults = {
"selector": "source.verilog | source.systemverilog",
"-t": "null",
"-g": 2012,
"-I +": [],
"-y +": [],
}
# fmt: on
# there is a ":" in the filepath under Windows like C:\DIR\FILE
if sublime.platform() == "windows":
filepath_regex = r"[^:]+:[^:]+"
else:
filepath_regex = r"[^:]+"
# what kind of messages should be caught?
regex = (
r"(?P<file>{0}):(?P<line>\d+):\s*"
r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*"
r"(?P<message>.*)".format(filepath_regex)
)
|
from SublimeLinter.lint import Linter
import sublime
class Iverilog(Linter):
# http://www.sublimelinter.com/en/stable/linter_attributes.html
name = "iverilog"
cmd = "iverilog ${args}"
tempfile_suffix = "verilog"
multiline = True
on_stderr = None
# fmt: off
defaults = {
"selector": "source.verilog | source.systemverilog",
# @see https://iverilog.fandom.com/wiki/Iverilog_Flags
"-t": "null",
"-g": 2012,
"-I +": [],
"-y +": [],
}
# fmt: on
# there is a ":" in the filepath under Windows like C:\DIR\FILE
if sublime.platform() == "windows":
filepath_regex = r"[^:]+:[^:]+"
else:
filepath_regex = r"[^:]+"
# what kind of messages should be caught?
regex = (
r"(?P<file>{0}):(?P<line>\d+):\s*"
r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*"
r"(?P<message>.*)".format(filepath_regex)
)
| Add iverilog flags reference URL | Add iverilog flags reference URL
Signed-off-by: Jack Cherng <[email protected]>
| Python | mit | jfcherng/SublimeLinter-contrib-iverilog,jfcherng/SublimeLinter-contrib-iverilog |
from SublimeLinter.lint import Linter
import sublime
class Iverilog(Linter):
# http://www.sublimelinter.com/en/stable/linter_attributes.html
name = "iverilog"
cmd = "iverilog ${args}"
tempfile_suffix = "verilog"
multiline = True
on_stderr = None
# fmt: off
defaults = {
"selector": "source.verilog | source.systemverilog",
+ # @see https://iverilog.fandom.com/wiki/Iverilog_Flags
"-t": "null",
"-g": 2012,
"-I +": [],
"-y +": [],
}
# fmt: on
# there is a ":" in the filepath under Windows like C:\DIR\FILE
if sublime.platform() == "windows":
filepath_regex = r"[^:]+:[^:]+"
else:
filepath_regex = r"[^:]+"
# what kind of messages should be caught?
regex = (
r"(?P<file>{0}):(?P<line>\d+):\s*"
r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*"
r"(?P<message>.*)".format(filepath_regex)
)
| Add iverilog flags reference URL | ## Code Before:
from SublimeLinter.lint import Linter
import sublime
class Iverilog(Linter):
# http://www.sublimelinter.com/en/stable/linter_attributes.html
name = "iverilog"
cmd = "iverilog ${args}"
tempfile_suffix = "verilog"
multiline = True
on_stderr = None
# fmt: off
defaults = {
"selector": "source.verilog | source.systemverilog",
"-t": "null",
"-g": 2012,
"-I +": [],
"-y +": [],
}
# fmt: on
# there is a ":" in the filepath under Windows like C:\DIR\FILE
if sublime.platform() == "windows":
filepath_regex = r"[^:]+:[^:]+"
else:
filepath_regex = r"[^:]+"
# what kind of messages should be caught?
regex = (
r"(?P<file>{0}):(?P<line>\d+):\s*"
r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*"
r"(?P<message>.*)".format(filepath_regex)
)
## Instruction:
Add iverilog flags reference URL
## Code After:
from SublimeLinter.lint import Linter
import sublime
class Iverilog(Linter):
# http://www.sublimelinter.com/en/stable/linter_attributes.html
name = "iverilog"
cmd = "iverilog ${args}"
tempfile_suffix = "verilog"
multiline = True
on_stderr = None
# fmt: off
defaults = {
"selector": "source.verilog | source.systemverilog",
# @see https://iverilog.fandom.com/wiki/Iverilog_Flags
"-t": "null",
"-g": 2012,
"-I +": [],
"-y +": [],
}
# fmt: on
# there is a ":" in the filepath under Windows like C:\DIR\FILE
if sublime.platform() == "windows":
filepath_regex = r"[^:]+:[^:]+"
else:
filepath_regex = r"[^:]+"
# what kind of messages should be caught?
regex = (
r"(?P<file>{0}):(?P<line>\d+):\s*"
r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*"
r"(?P<message>.*)".format(filepath_regex)
)
| ...
"selector": "source.verilog | source.systemverilog",
# @see https://iverilog.fandom.com/wiki/Iverilog_Flags
"-t": "null",
... |
3a9568b4d4de969b1e2031e8d2d3cdd7bd56824f | zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py | zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py | from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="[email protected]")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
if not Realm.objects.filter(string_id="zulip").exists():
# If the user renamed the `zulip` system bot realm (or deleted
# it), there's nothing for us to do.
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="[email protected]")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| Fix zulipinternal migration corner case. | migrations: Fix zulipinternal migration corner case.
It's theoretically possible to have configured a Zulip server where
the system bots live in the same realm as normal users (and may have
in fact been the default in early Zulip releases? Unclear.). We
should handle these without the migration intended to clean up naming
for the system bot realm crashing.
Fixes #13660.
| Python | apache-2.0 | brainwane/zulip,andersk/zulip,hackerkid/zulip,synicalsyntax/zulip,andersk/zulip,hackerkid/zulip,punchagan/zulip,shubhamdhama/zulip,showell/zulip,zulip/zulip,synicalsyntax/zulip,kou/zulip,rht/zulip,showell/zulip,brainwane/zulip,punchagan/zulip,shubhamdhama/zulip,hackerkid/zulip,andersk/zulip,kou/zulip,brainwane/zulip,brainwane/zulip,andersk/zulip,showell/zulip,shubhamdhama/zulip,kou/zulip,punchagan/zulip,zulip/zulip,kou/zulip,showell/zulip,brainwane/zulip,eeshangarg/zulip,timabbott/zulip,eeshangarg/zulip,hackerkid/zulip,shubhamdhama/zulip,zulip/zulip,timabbott/zulip,brainwane/zulip,eeshangarg/zulip,rht/zulip,zulip/zulip,timabbott/zulip,rht/zulip,synicalsyntax/zulip,andersk/zulip,showell/zulip,shubhamdhama/zulip,rht/zulip,hackerkid/zulip,rht/zulip,hackerkid/zulip,eeshangarg/zulip,kou/zulip,synicalsyntax/zulip,brainwane/zulip,shubhamdhama/zulip,eeshangarg/zulip,andersk/zulip,rht/zulip,timabbott/zulip,punchagan/zulip,showell/zulip,eeshangarg/zulip,synicalsyntax/zulip,punchagan/zulip,timabbott/zulip,zulip/zulip,andersk/zulip,punchagan/zulip,zulip/zulip,hackerkid/zulip,timabbott/zulip,synicalsyntax/zulip,zulip/zulip,showell/zulip,eeshangarg/zulip,kou/zulip,punchagan/zulip,synicalsyntax/zulip,rht/zulip,kou/zulip,timabbott/zulip,shubhamdhama/zulip | from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
+ return
+ if not Realm.objects.filter(string_id="zulip").exists():
+ # If the user renamed the `zulip` system bot realm (or deleted
+ # it), there's nothing for us to do.
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="[email protected]")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| Fix zulipinternal migration corner case. | ## Code Before:
from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="[email protected]")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
## Instruction:
Fix zulipinternal migration corner case.
## Code After:
from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
if not Realm.objects.filter(string_id="zulip").exists():
# If the user renamed the `zulip` system bot realm (or deleted
# it), there's nothing for us to do.
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="[email protected]")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| # ... existing code ...
if Realm.objects.filter(string_id="zulipinternal").exists():
return
if not Realm.objects.filter(string_id="zulip").exists():
# If the user renamed the `zulip` system bot realm (or deleted
# it), there's nothing for us to do.
return
# ... rest of the code ... |
e53c66f9ab12fe0c90c447176b083513cd3a4cf5 | store/urls.py | store/urls.py | from django.conf.urls import url
from .views import ProductCatalogue, ProductDetail, product_review
urlpatterns = [
url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'),
url(r'^(?P<slug>[\w\-]+)/$', ProductDetail.as_view(), name='detail'),
url(r'^review/$', product_review, name='review')
]
| from django.conf.urls import url
from .views import ProductCatalogue, ProductDetail, product_review
urlpatterns = [
url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'),
url(r'^review/$', product_review, name='review'),
url(r'^(?P<slug>[\w\-]+)/$', ProductDetail.as_view(), name='detail'),
]
| Move products:review URLConf above product:detail | Move products:review URLConf above product:detail
The product:detail view is greedy and previously caused the review
URLConf never to be resolved by the correct view
| Python | bsd-3-clause | kevgathuku/compshop,andela-kndungu/compshop,kevgathuku/compshop,kevgathuku/compshop,andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,andela-kndungu/compshop | from django.conf.urls import url
from .views import ProductCatalogue, ProductDetail, product_review
urlpatterns = [
url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'),
+ url(r'^review/$', product_review, name='review'),
url(r'^(?P<slug>[\w\-]+)/$', ProductDetail.as_view(), name='detail'),
- url(r'^review/$', product_review, name='review')
]
| Move products:review URLConf above product:detail | ## Code Before:
from django.conf.urls import url
from .views import ProductCatalogue, ProductDetail, product_review
urlpatterns = [
url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'),
url(r'^(?P<slug>[\w\-]+)/$', ProductDetail.as_view(), name='detail'),
url(r'^review/$', product_review, name='review')
]
## Instruction:
Move products:review URLConf above product:detail
## Code After:
from django.conf.urls import url
from .views import ProductCatalogue, ProductDetail, product_review
urlpatterns = [
url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'),
url(r'^review/$', product_review, name='review'),
url(r'^(?P<slug>[\w\-]+)/$', ProductDetail.as_view(), name='detail'),
]
| // ... existing code ...
url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'),
url(r'^review/$', product_review, name='review'),
url(r'^(?P<slug>[\w\-]+)/$', ProductDetail.as_view(), name='detail'),
]
// ... rest of the code ... |
8d7862a7045fbb52ce3a2499766ffa1ffef284af | tests/settings.py | tests/settings.py | from moztrap.settings.default import *
DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage"
ALLOW_ANONYMOUS_ACCESS = False
SITE_URL = "http://localhost:80"
USE_BROWSERID = True
| from moztrap.settings.default import *
DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage"
ALLOW_ANONYMOUS_ACCESS = False
SITE_URL = "http://localhost:80"
USE_BROWSERID = True
PASSWORD_HASHERS = ['django.contrib.auth.hashers.UnsaltedMD5PasswordHasher']
| Use faster password hashing in tests. | Use faster password hashing in tests.
| Python | bsd-2-clause | mccarrmb/moztrap,bobsilverberg/moztrap,mozilla/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,mozilla/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,mozilla/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,mozilla/moztrap,mozilla/moztrap | from moztrap.settings.default import *
DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage"
ALLOW_ANONYMOUS_ACCESS = False
SITE_URL = "http://localhost:80"
USE_BROWSERID = True
+ PASSWORD_HASHERS = ['django.contrib.auth.hashers.UnsaltedMD5PasswordHasher']
+ | Use faster password hashing in tests. | ## Code Before:
from moztrap.settings.default import *
DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage"
ALLOW_ANONYMOUS_ACCESS = False
SITE_URL = "http://localhost:80"
USE_BROWSERID = True
## Instruction:
Use faster password hashing in tests.
## Code After:
from moztrap.settings.default import *
DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage"
ALLOW_ANONYMOUS_ACCESS = False
SITE_URL = "http://localhost:80"
USE_BROWSERID = True
PASSWORD_HASHERS = ['django.contrib.auth.hashers.UnsaltedMD5PasswordHasher']
| # ... existing code ...
USE_BROWSERID = True
PASSWORD_HASHERS = ['django.contrib.auth.hashers.UnsaltedMD5PasswordHasher']
# ... rest of the code ... |
62b74e6d6452012f8ad68810446a3648749a3fee | collections/show-test/print-divs.py | collections/show-test/print-divs.py |
def printDivs(num):
for i in range(num):
print('<div class="item">Item ' + str(i+1) + '</div>')
printDivs(20) |
def printDivs(num):
for i in range(num):
print('<div class="item">Item ' + str(i+1) + ': Lorem ipsum dolor sic amet</div>')
printDivs(20) | Add dummy text to divs. | Add dummy text to divs.
| Python | apache-2.0 | scholarslab/takeback,scholarslab/takeback,scholarslab/takeback,scholarslab/takeback,scholarslab/takeback |
def printDivs(num):
for i in range(num):
- print('<div class="item">Item ' + str(i+1) + '</div>')
+ print('<div class="item">Item ' + str(i+1) + ': Lorem ipsum dolor sic amet</div>')
printDivs(20) | Add dummy text to divs. | ## Code Before:
def printDivs(num):
for i in range(num):
print('<div class="item">Item ' + str(i+1) + '</div>')
printDivs(20)
## Instruction:
Add dummy text to divs.
## Code After:
def printDivs(num):
for i in range(num):
print('<div class="item">Item ' + str(i+1) + ': Lorem ipsum dolor sic amet</div>')
printDivs(20) | ...
for i in range(num):
print('<div class="item">Item ' + str(i+1) + ': Lorem ipsum dolor sic amet</div>')
... |
7dd0c64b4503ab32cf79864f4c23016518b1cdbd | electionleaflets/apps/api/tests/test_create_leaflet.py | electionleaflets/apps/api/tests/test_create_leaflet.py | import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES]
class CreateLeafletTests(APITestCase):
def test_create_leaflet(self):
leaflet_url = reverse('leaflet-list')
leaflet_image_url = reverse('leafletimage-list')
response = self.client.post(leaflet_url, {}, format='json')
self.assertEqual(response.data['status'], 'draft')
leaflet_id = response.data['pk']
# Upload some images
for name, path in IMAGES:
data = {
'image': open(path),
'leaflet': leaflet_id
}
response = self.client.post(leaflet_image_url,
data, format='multipart')
response = self.client.get(leaflet_url+"1/", format='json')
self.assertEqual(len(response.data['images']), 6)
| import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES]
class CreateLeafletTests(APITestCase):
def test_create_leaflet(self):
leaflet_url = reverse('api:leaflet-list')
leaflet_image_url = reverse('api:leafletimage-list')
response = self.client.post(leaflet_url, {}, format='json')
self.assertEqual(response.data['status'], 'draft')
leaflet_id = response.data['pk']
self.assertEqual(leaflet_id, 1)
# import ipdb
# ipdb.set_trace()
# # Upload some images
# for name, path in IMAGES:
# data = {
# 'image': open(path),
# 'leaflet_id': leaflet_id
# }
#
# response = self.client.post(leaflet_image_url,
# data, format='multipart')
# response = self.client.get(leaflet_url+"1/", format='json')
# self.assertEqual(len(response.data['images']), 6)
| Remove some API tests for now | Remove some API tests for now
| Python | mit | JustinWingChungHui/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,JustinWingChungHui/electionleaflets,JustinWingChungHui/electionleaflets,JustinWingChungHui/electionleaflets | import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES]
class CreateLeafletTests(APITestCase):
def test_create_leaflet(self):
- leaflet_url = reverse('leaflet-list')
+ leaflet_url = reverse('api:leaflet-list')
- leaflet_image_url = reverse('leafletimage-list')
+ leaflet_image_url = reverse('api:leafletimage-list')
response = self.client.post(leaflet_url, {}, format='json')
self.assertEqual(response.data['status'], 'draft')
leaflet_id = response.data['pk']
+ self.assertEqual(leaflet_id, 1)
+ # import ipdb
+ # ipdb.set_trace()
+ # # Upload some images
+ # for name, path in IMAGES:
+ # data = {
+ # 'image': open(path),
+ # 'leaflet_id': leaflet_id
+ # }
+ #
+ # response = self.client.post(leaflet_image_url,
+ # data, format='multipart')
+ # response = self.client.get(leaflet_url+"1/", format='json')
+ # self.assertEqual(len(response.data['images']), 6)
- # Upload some images
- for name, path in IMAGES:
- data = {
- 'image': open(path),
- 'leaflet': leaflet_id
- }
- response = self.client.post(leaflet_image_url,
- data, format='multipart')
- response = self.client.get(leaflet_url+"1/", format='json')
- self.assertEqual(len(response.data['images']), 6)
- | Remove some API tests for now | ## Code Before:
import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES]
class CreateLeafletTests(APITestCase):
def test_create_leaflet(self):
leaflet_url = reverse('leaflet-list')
leaflet_image_url = reverse('leafletimage-list')
response = self.client.post(leaflet_url, {}, format='json')
self.assertEqual(response.data['status'], 'draft')
leaflet_id = response.data['pk']
# Upload some images
for name, path in IMAGES:
data = {
'image': open(path),
'leaflet': leaflet_id
}
response = self.client.post(leaflet_image_url,
data, format='multipart')
response = self.client.get(leaflet_url+"1/", format='json')
self.assertEqual(len(response.data['images']), 6)
## Instruction:
Remove some API tests for now
## Code After:
import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES]
class CreateLeafletTests(APITestCase):
def test_create_leaflet(self):
leaflet_url = reverse('api:leaflet-list')
leaflet_image_url = reverse('api:leafletimage-list')
response = self.client.post(leaflet_url, {}, format='json')
self.assertEqual(response.data['status'], 'draft')
leaflet_id = response.data['pk']
self.assertEqual(leaflet_id, 1)
# import ipdb
# ipdb.set_trace()
# # Upload some images
# for name, path in IMAGES:
# data = {
# 'image': open(path),
# 'leaflet_id': leaflet_id
# }
#
# response = self.client.post(leaflet_image_url,
# data, format='multipart')
# response = self.client.get(leaflet_url+"1/", format='json')
# self.assertEqual(len(response.data['images']), 6)
| // ... existing code ...
leaflet_url = reverse('api:leaflet-list')
leaflet_image_url = reverse('api:leafletimage-list')
// ... modified code ...
leaflet_id = response.data['pk']
self.assertEqual(leaflet_id, 1)
# import ipdb
# ipdb.set_trace()
# # Upload some images
# for name, path in IMAGES:
# data = {
# 'image': open(path),
# 'leaflet_id': leaflet_id
# }
#
# response = self.client.post(leaflet_image_url,
# data, format='multipart')
# response = self.client.get(leaflet_url+"1/", format='json')
# self.assertEqual(len(response.data['images']), 6)
// ... rest of the code ... |
8a61bd499e9a3cc538d7d83719c6d4231753925b | megalista_dataflow/uploaders/uploaders.py | megalista_dataflow/uploaders/uploaders.py |
import apache_beam as beam
from error.error_handling import ErrorHandler
from models.execution import Execution
class MegalistaUploader(beam.DoFn):
"""
General DoFn to be used as supper for DoFn uploaders.
Add error notification capabilities.
"""
def __init__(self, error_handler: ErrorHandler):
super().__init__()
self._error_handler = error_handler
def _add_error(self, execution: Execution, error_message: str):
self._error_handler.add_error(execution, error_message)
def teardown(self):
self._error_handler.notify_errors()
|
import apache_beam as beam
from error.error_handling import ErrorHandler
from models.execution import Execution
class MegalistaUploader(beam.DoFn):
"""
General DoFn to be used as supper for DoFn uploaders.
Add error notification capabilities.
"""
def __init__(self, error_handler: ErrorHandler):
super().__init__()
self._error_handler = error_handler
def _add_error(self, execution: Execution, error_message: str):
self._error_handler.add_error(execution, error_message)
def finish_bundle(self):
self._error_handler.notify_errors()
| Change the notifier to be sent on finish_bundle instead of teardown | Change the notifier to be sent on finish_bundle instead of teardown
Change-Id: I6b80b1d0431b0fe285a5b59e9a33199bf8bd3510
| Python | apache-2.0 | google/megalista,google/megalista |
import apache_beam as beam
from error.error_handling import ErrorHandler
from models.execution import Execution
class MegalistaUploader(beam.DoFn):
"""
General DoFn to be used as supper for DoFn uploaders.
Add error notification capabilities.
"""
def __init__(self, error_handler: ErrorHandler):
super().__init__()
self._error_handler = error_handler
def _add_error(self, execution: Execution, error_message: str):
self._error_handler.add_error(execution, error_message)
- def teardown(self):
+ def finish_bundle(self):
self._error_handler.notify_errors()
| Change the notifier to be sent on finish_bundle instead of teardown | ## Code Before:
import apache_beam as beam
from error.error_handling import ErrorHandler
from models.execution import Execution
class MegalistaUploader(beam.DoFn):
"""
General DoFn to be used as supper for DoFn uploaders.
Add error notification capabilities.
"""
def __init__(self, error_handler: ErrorHandler):
super().__init__()
self._error_handler = error_handler
def _add_error(self, execution: Execution, error_message: str):
self._error_handler.add_error(execution, error_message)
def teardown(self):
self._error_handler.notify_errors()
## Instruction:
Change the notifier to be sent on finish_bundle instead of teardown
## Code After:
import apache_beam as beam
from error.error_handling import ErrorHandler
from models.execution import Execution
class MegalistaUploader(beam.DoFn):
"""
General DoFn to be used as supper for DoFn uploaders.
Add error notification capabilities.
"""
def __init__(self, error_handler: ErrorHandler):
super().__init__()
self._error_handler = error_handler
def _add_error(self, execution: Execution, error_message: str):
self._error_handler.add_error(execution, error_message)
def finish_bundle(self):
self._error_handler.notify_errors()
| # ... existing code ...
def finish_bundle(self):
self._error_handler.notify_errors()
# ... rest of the code ... |
78977a0f976615e76db477b0ab7b35193b34d189 | api/__init__.py | api/__init__.py | from flask import Flask
app = Flask(__name__)
app.secret_key = ''
import api.userview
| from flask import Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension
# Use DictStore until the code is ready for production
store = DictStore()
app = Flask(__name__)
app.secret_key = ''
KVSessionExtension(store, app)
import api.userview
| Change so that kvsession (server side sessions) is used instead of flask default | Change so that kvsession (server side sessions) is used instead of flask default
| Python | isc | tobbez/lys-reader | from flask import Flask
+ from simplekv.memory import DictStore
+ from flaskext.kvsession import KVSessionExtension
+ # Use DictStore until the code is ready for production
+ store = DictStore()
app = Flask(__name__)
app.secret_key = ''
+ KVSessionExtension(store, app)
+
import api.userview
| Change so that kvsession (server side sessions) is used instead of flask default | ## Code Before:
from flask import Flask
app = Flask(__name__)
app.secret_key = ''
import api.userview
## Instruction:
Change so that kvsession (server side sessions) is used instead of flask default
## Code After:
from flask import Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension
# Use DictStore until the code is ready for production
store = DictStore()
app = Flask(__name__)
app.secret_key = ''
KVSessionExtension(store, app)
import api.userview
| # ... existing code ...
from flask import Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension
# Use DictStore until the code is ready for production
store = DictStore()
app = Flask(__name__)
# ... modified code ...
KVSessionExtension(store, app)
import api.userview
# ... rest of the code ... |
efc1988d704a7a1231046dea8af65dcdba7897fd | py/fbx_write.py | py/fbx_write.py |
import sys
import os
import bpy
for sysarg in sys.argv:
print(sysarg)
py_args = sys.argv[sys.argv.index('--') + 1]
py_args = py_args.split(' ')
for arg in py_args:
if (arg.startswith('basedir:')):
basedir = arg.split('basedir:')[1]
else:
# can supply filename(s) with or without extension
pdb_code = os.path.splitext(arg)[0]
abs_file_in = os.path.join(basedir, 'structures/wrl', pdb_code+'.wrl')
# This is the base directory, used for saving files
molecule = bpy.ops.import_scene.x3d(
filepath = abs_file_in
)
abs_file_out = os.path.join(basedir,'structures/fbx',pdb_code+'.fbx')
bpy.ops.export_scene.fbx(
filepath = abs_file_out
)
|
import sys
import os
import bpy
for sysarg in sys.argv:
print(sysarg)
py_args = sys.argv[sys.argv.index('--') + 1]
py_args = py_args.split(' ')
for arg in py_args:
if (arg.startswith('basedir:')):
basedir = arg.split('basedir:')[1]
else:
# can supply filename(s) with or without extension
pdb_code = os.path.splitext(arg)[0]
abs_file_in = os.path.join(basedir, 'structures/wrl', pdb_code+'.wrl')
# This is the base directory, used for saving files
molecule = bpy.ops.import_scene.x3d(
filepath = abs_file_in
)
abs_file_out = os.path.join(basedir,'structures/fbx',pdb_code+'.fbx')
bpy.ops.export_scene.fbx(
filepath = abs_file_out
)
bpy.ops.wm.quit_blender()
| Quit Blender after writing FBX | Quit Blender after writing FBX
| Python | mit | hackmcr15-code-a-la-mode/mol-vis-hack,hackmcr15-code-a-la-mode/mol-vis-hack |
import sys
import os
import bpy
for sysarg in sys.argv:
print(sysarg)
py_args = sys.argv[sys.argv.index('--') + 1]
py_args = py_args.split(' ')
for arg in py_args:
if (arg.startswith('basedir:')):
basedir = arg.split('basedir:')[1]
else:
# can supply filename(s) with or without extension
pdb_code = os.path.splitext(arg)[0]
abs_file_in = os.path.join(basedir, 'structures/wrl', pdb_code+'.wrl')
# This is the base directory, used for saving files
molecule = bpy.ops.import_scene.x3d(
filepath = abs_file_in
)
abs_file_out = os.path.join(basedir,'structures/fbx',pdb_code+'.fbx')
bpy.ops.export_scene.fbx(
filepath = abs_file_out
)
+ bpy.ops.wm.quit_blender()
| Quit Blender after writing FBX | ## Code Before:
import sys
import os
import bpy
for sysarg in sys.argv:
print(sysarg)
py_args = sys.argv[sys.argv.index('--') + 1]
py_args = py_args.split(' ')
for arg in py_args:
if (arg.startswith('basedir:')):
basedir = arg.split('basedir:')[1]
else:
# can supply filename(s) with or without extension
pdb_code = os.path.splitext(arg)[0]
abs_file_in = os.path.join(basedir, 'structures/wrl', pdb_code+'.wrl')
# This is the base directory, used for saving files
molecule = bpy.ops.import_scene.x3d(
filepath = abs_file_in
)
abs_file_out = os.path.join(basedir,'structures/fbx',pdb_code+'.fbx')
bpy.ops.export_scene.fbx(
filepath = abs_file_out
)
## Instruction:
Quit Blender after writing FBX
## Code After:
import sys
import os
import bpy
for sysarg in sys.argv:
print(sysarg)
py_args = sys.argv[sys.argv.index('--') + 1]
py_args = py_args.split(' ')
for arg in py_args:
if (arg.startswith('basedir:')):
basedir = arg.split('basedir:')[1]
else:
# can supply filename(s) with or without extension
pdb_code = os.path.splitext(arg)[0]
abs_file_in = os.path.join(basedir, 'structures/wrl', pdb_code+'.wrl')
# This is the base directory, used for saving files
molecule = bpy.ops.import_scene.x3d(
filepath = abs_file_in
)
abs_file_out = os.path.join(basedir,'structures/fbx',pdb_code+'.fbx')
bpy.ops.export_scene.fbx(
filepath = abs_file_out
)
bpy.ops.wm.quit_blender()
| ...
)
bpy.ops.wm.quit_blender()
... |
1290bc59774aac7756658c3480d6a5293c7a3467 | planner/models.py | planner/models.py | from django.db import models
# Route model
# Start and end locations with additional stop-overs
class Route(models.Model):
origin = models.CharField(max_length=63)
destination = models.CharField(max_length=63)
def __unicode__(self):
return "{} to {}".format(
self.origin,
self.destination
)
class Waypoint(models.Model):
waypoint = models.CharField(max_length=63)
route = models.ForeignKey(Route, related_name="waypoints")
def __unicode__(self):
return str(self.waypoint)
def __repr__(self):
return str(self.waypoint)
# TripDetail model
# Additional trip details, such as traveling with children or pets
class TripDetail(models.Model):
description = models.CharField(max_length=127)
def __unicode__(self):
return str(self.description)
# RoadTrip model
# Start and end dates, Route and TripDetails
class RoadTrip(models.Model):
start_date = models.DateField()
end_date = models.DateField()
route = models.OneToOneField(Route)
details = models.ManyToManyField(TripDetail)
def __unicode__(self):
return "{} from {} to {}".format(
self.route,
self.start_date,
self.end_date
)
| from django.db import models
# Route model
# Start and end locations with additional stop-overs
class Route(models.Model):
start = models.CharField(max_length=63)
end = models.CharField(max_length=63)
def __unicode__(self):
return "{} to {}".format(
self.start,
self.end
)
class Waypoint(models.Model):
waypoint = models.CharField(max_length=63)
route = models.ForeignKey(Route, related_name="waypoints")
def __unicode__(self):
return str(self.waypoint)
def __repr__(self):
return str(self.waypoint)
# TripDetail model
# Additional trip details, such as traveling with children or pets
class TripDetail(models.Model):
description = models.CharField(max_length=127)
def __unicode__(self):
return str(self.description)
# RoadTrip model
# Start and end dates, Route and TripDetails
class RoadTrip(models.Model):
start_date = models.DateField()
end_date = models.DateField()
route = models.OneToOneField(Route)
details = models.ManyToManyField(TripDetail)
def __unicode__(self):
return "{} from {} to {}".format(
self.route,
self.start_date,
self.end_date
)
| Rename Route model's start and end fields to be consistent with front end identification | Rename Route model's start and end fields to be consistent with front end identification
| Python | apache-2.0 | jwarren116/RoadTrip,jwarren116/RoadTrip,jwarren116/RoadTrip | from django.db import models
# Route model
# Start and end locations with additional stop-overs
class Route(models.Model):
+ start = models.CharField(max_length=63)
- origin = models.CharField(max_length=63)
+ end = models.CharField(max_length=63)
- destination = models.CharField(max_length=63)
def __unicode__(self):
return "{} to {}".format(
- self.origin,
- self.destination
+ self.start,
+ self.end
)
class Waypoint(models.Model):
waypoint = models.CharField(max_length=63)
route = models.ForeignKey(Route, related_name="waypoints")
def __unicode__(self):
return str(self.waypoint)
def __repr__(self):
return str(self.waypoint)
# TripDetail model
# Additional trip details, such as traveling with children or pets
class TripDetail(models.Model):
description = models.CharField(max_length=127)
def __unicode__(self):
return str(self.description)
# RoadTrip model
# Start and end dates, Route and TripDetails
class RoadTrip(models.Model):
start_date = models.DateField()
end_date = models.DateField()
route = models.OneToOneField(Route)
details = models.ManyToManyField(TripDetail)
def __unicode__(self):
return "{} from {} to {}".format(
self.route,
self.start_date,
self.end_date
)
| Rename Route model's start and end fields to be consistent with front end identification | ## Code Before:
from django.db import models
# Route model
# Start and end locations with additional stop-overs
class Route(models.Model):
origin = models.CharField(max_length=63)
destination = models.CharField(max_length=63)
def __unicode__(self):
return "{} to {}".format(
self.origin,
self.destination
)
class Waypoint(models.Model):
waypoint = models.CharField(max_length=63)
route = models.ForeignKey(Route, related_name="waypoints")
def __unicode__(self):
return str(self.waypoint)
def __repr__(self):
return str(self.waypoint)
# TripDetail model
# Additional trip details, such as traveling with children or pets
class TripDetail(models.Model):
description = models.CharField(max_length=127)
def __unicode__(self):
return str(self.description)
# RoadTrip model
# Start and end dates, Route and TripDetails
class RoadTrip(models.Model):
start_date = models.DateField()
end_date = models.DateField()
route = models.OneToOneField(Route)
details = models.ManyToManyField(TripDetail)
def __unicode__(self):
return "{} from {} to {}".format(
self.route,
self.start_date,
self.end_date
)
## Instruction:
Rename Route model's start and end fields to be consistent with front end identification
## Code After:
from django.db import models
# Route model
# Start and end locations with additional stop-overs
class Route(models.Model):
start = models.CharField(max_length=63)
end = models.CharField(max_length=63)
def __unicode__(self):
return "{} to {}".format(
self.start,
self.end
)
class Waypoint(models.Model):
waypoint = models.CharField(max_length=63)
route = models.ForeignKey(Route, related_name="waypoints")
def __unicode__(self):
return str(self.waypoint)
def __repr__(self):
return str(self.waypoint)
# TripDetail model
# Additional trip details, such as traveling with children or pets
class TripDetail(models.Model):
description = models.CharField(max_length=127)
def __unicode__(self):
return str(self.description)
# RoadTrip model
# Start and end dates, Route and TripDetails
class RoadTrip(models.Model):
start_date = models.DateField()
end_date = models.DateField()
route = models.OneToOneField(Route)
details = models.ManyToManyField(TripDetail)
def __unicode__(self):
return "{} from {} to {}".format(
self.route,
self.start_date,
self.end_date
)
| ...
class Route(models.Model):
start = models.CharField(max_length=63)
end = models.CharField(max_length=63)
...
return "{} to {}".format(
self.start,
self.end
)
... |
b190afa49a6b0939d692adcaee2396c619e632ff | setup.py | setup.py | from distutils.core import setup
import os
import inflect
here = os.path.dirname(__file__)
readme_path = os.path.join(here, 'README.rst')
readme = open(readme_path, 'rb').read().decode('utf-8')
setup(
name='inflect',
version=inflect.__version__,
description='Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words',
long_description=readme,
author='Paul Dyson',
author_email='[email protected]',
maintainer='Alex Gronholm',
maintainer_email='[email protected]',
url='http://pypi.python.org/pypi/inflect',
py_modules=['inflect'],
provides=['inflect'],
keywords=['plural', 'inflect', 'participle'],
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
]
)
| from distutils.core import setup
import os
import io
import inflect
here = os.path.dirname(__file__)
readme_path = os.path.join(here, 'README.rst')
readme = io.open(readme_path, encoding='utf-8').read()
setup(
name='inflect',
version=inflect.__version__,
description='Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words',
long_description=readme,
author='Paul Dyson',
author_email='[email protected]',
maintainer='Alex Gronholm',
maintainer_email='[email protected]',
url='http://pypi.python.org/pypi/inflect',
py_modules=['inflect'],
provides=['inflect'],
keywords=['plural', 'inflect', 'participle'],
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
]
)
| Use io module for simplicity and closer alignment to recommended usage. | Use io module for simplicity and closer alignment to recommended usage.
| Python | mit | hugovk/inflect.py,pwdyson/inflect.py,jazzband/inflect | from distutils.core import setup
import os
+ import io
import inflect
here = os.path.dirname(__file__)
readme_path = os.path.join(here, 'README.rst')
- readme = open(readme_path, 'rb').read().decode('utf-8')
+ readme = io.open(readme_path, encoding='utf-8').read()
setup(
name='inflect',
version=inflect.__version__,
description='Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words',
long_description=readme,
author='Paul Dyson',
author_email='[email protected]',
maintainer='Alex Gronholm',
maintainer_email='[email protected]',
url='http://pypi.python.org/pypi/inflect',
py_modules=['inflect'],
provides=['inflect'],
keywords=['plural', 'inflect', 'participle'],
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
]
)
| Use io module for simplicity and closer alignment to recommended usage. | ## Code Before:
from distutils.core import setup
import os
import inflect
here = os.path.dirname(__file__)
readme_path = os.path.join(here, 'README.rst')
readme = open(readme_path, 'rb').read().decode('utf-8')
setup(
name='inflect',
version=inflect.__version__,
description='Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words',
long_description=readme,
author='Paul Dyson',
author_email='[email protected]',
maintainer='Alex Gronholm',
maintainer_email='[email protected]',
url='http://pypi.python.org/pypi/inflect',
py_modules=['inflect'],
provides=['inflect'],
keywords=['plural', 'inflect', 'participle'],
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
]
)
## Instruction:
Use io module for simplicity and closer alignment to recommended usage.
## Code After:
from distutils.core import setup
import os
import io
import inflect
here = os.path.dirname(__file__)
readme_path = os.path.join(here, 'README.rst')
readme = io.open(readme_path, encoding='utf-8').read()
setup(
name='inflect',
version=inflect.__version__,
description='Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words',
long_description=readme,
author='Paul Dyson',
author_email='[email protected]',
maintainer='Alex Gronholm',
maintainer_email='[email protected]',
url='http://pypi.python.org/pypi/inflect',
py_modules=['inflect'],
provides=['inflect'],
keywords=['plural', 'inflect', 'participle'],
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Linguistic',
]
)
| # ... existing code ...
import os
import io
# ... modified code ...
readme_path = os.path.join(here, 'README.rst')
readme = io.open(readme_path, encoding='utf-8').read()
# ... rest of the code ... |
bc31bb2ddbf5b7f2e5d375a8b0d6e01f631d0aef | txircd/modules/extra/snotice_links.py | txircd/modules/extra/snotice_links.py | from twisted.plugin import IPlugin
from txircd.modbase import IModuleData, ModuleData
from zope.interface import implements
class SnoLinks(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeLinks"
def actions(self):
return [ ("serverconnect", 1, self.announceConnect),
("serverquit", 1, self.announceQuit),
("servernoticetype", 1, self.checkSnoType) ]
def announceConnect(self, server):
message = "Server {} ({}) connected (to {})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name)
self.ircd.runActionStandard("sendservernotice", "links", message)
def announceQuit(self, server, reason):
message = "Server {} ({}) disconnected (from {}) ({})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name, reason)
self.ircd.runActionStandard("sendservernotice", "links", message)
def checkSnoType(self, user, typename):
if typename == "links":
return True
return False
snoLinks = SnoLinks() | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoLinks(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeLinks"
def actions(self):
return [ ("serverconnect", 1, self.announceConnect),
("serverquit", 1, self.announceQuit),
("servernoticetype", 1, self.checkSnoType) ]
def announceConnect(self, server):
message = "Server {} ({}) connected (to {})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name)
self.ircd.runActionStandard("sendservernotice", "links", message)
def announceQuit(self, server, reason):
message = "Server {} ({}) disconnected (from {}) ({})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name, reason)
self.ircd.runActionStandard("sendservernotice", "links", message)
def checkSnoType(self, user, typename):
if typename == "links":
return True
return False
snoLinks = SnoLinks() | Fix module data import on links server notice | Fix module data import on links server notice
| Python | bsd-3-clause | Heufneutje/txircd | from twisted.plugin import IPlugin
- from txircd.modbase import IModuleData, ModuleData
+ from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoLinks(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeLinks"
def actions(self):
return [ ("serverconnect", 1, self.announceConnect),
("serverquit", 1, self.announceQuit),
("servernoticetype", 1, self.checkSnoType) ]
def announceConnect(self, server):
message = "Server {} ({}) connected (to {})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name)
self.ircd.runActionStandard("sendservernotice", "links", message)
def announceQuit(self, server, reason):
message = "Server {} ({}) disconnected (from {}) ({})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name, reason)
self.ircd.runActionStandard("sendservernotice", "links", message)
def checkSnoType(self, user, typename):
if typename == "links":
return True
return False
snoLinks = SnoLinks() | Fix module data import on links server notice | ## Code Before:
from twisted.plugin import IPlugin
from txircd.modbase import IModuleData, ModuleData
from zope.interface import implements
class SnoLinks(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeLinks"
def actions(self):
return [ ("serverconnect", 1, self.announceConnect),
("serverquit", 1, self.announceQuit),
("servernoticetype", 1, self.checkSnoType) ]
def announceConnect(self, server):
message = "Server {} ({}) connected (to {})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name)
self.ircd.runActionStandard("sendservernotice", "links", message)
def announceQuit(self, server, reason):
message = "Server {} ({}) disconnected (from {}) ({})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name, reason)
self.ircd.runActionStandard("sendservernotice", "links", message)
def checkSnoType(self, user, typename):
if typename == "links":
return True
return False
snoLinks = SnoLinks()
## Instruction:
Fix module data import on links server notice
## Code After:
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoLinks(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeLinks"
def actions(self):
return [ ("serverconnect", 1, self.announceConnect),
("serverquit", 1, self.announceQuit),
("servernoticetype", 1, self.checkSnoType) ]
def announceConnect(self, server):
message = "Server {} ({}) connected (to {})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name)
self.ircd.runActionStandard("sendservernotice", "links", message)
def announceQuit(self, server, reason):
message = "Server {} ({}) disconnected (from {}) ({})".format(server.name, server.serverID, self.ircd.name if server.nextClosest == self.ircd.serverID else self.ircd.servers[server.nextClosest].name, reason)
self.ircd.runActionStandard("sendservernotice", "links", message)
def checkSnoType(self, user, typename):
if typename == "links":
return True
return False
snoLinks = SnoLinks() | ...
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
... |
373ce0f89a9253065114c757d3484849349a716d | tests/data_context/test_data_context_utils.py | tests/data_context/test_data_context_utils.py | import pytest
import os
from great_expectations.data_context.util import (
safe_mmkdir,
)
def test_safe_mmkdir(tmp_path_factory):
project_path = str(tmp_path_factory.mktemp('empty_dir'))
first_path = os.path.join(project_path,"first_path")
safe_mmkdir(first_path)
assert os.path.isdir(first_path)
with pytest.raises(TypeError):
safe_mmkdir(1)
#This should trigger python 2
second_path = os.path.join(project_path,"second_path")
print(second_path)
print(type(second_path))
safe_mmkdir(os.path.dirname(second_path))
| import pytest
import os
import six
from great_expectations.data_context.util import (
safe_mmkdir,
)
def test_safe_mmkdir(tmp_path_factory):
project_path = str(tmp_path_factory.mktemp('empty_dir'))
first_path = os.path.join(project_path,"first_path")
safe_mmkdir(first_path)
assert os.path.isdir(first_path)
with pytest.raises(TypeError):
safe_mmkdir(1)
#This should trigger python 2
if six.PY2:
with pytest.raises(TypeError) as e:
next_project_path = tmp_path_factory.mktemp('test_safe_mmkdir__dir_b')
safe_mmkdir(next_project_path)
assert e.value.message == "directory must be of type str, not {'directory_type': \"<class 'pathlib2.PosixPath'>\"}"
| Add test for the intended use case | Add test for the intended use case
| Python | apache-2.0 | great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations | import pytest
import os
+ import six
from great_expectations.data_context.util import (
safe_mmkdir,
)
def test_safe_mmkdir(tmp_path_factory):
project_path = str(tmp_path_factory.mktemp('empty_dir'))
first_path = os.path.join(project_path,"first_path")
safe_mmkdir(first_path)
assert os.path.isdir(first_path)
with pytest.raises(TypeError):
safe_mmkdir(1)
#This should trigger python 2
- second_path = os.path.join(project_path,"second_path")
- print(second_path)
- print(type(second_path))
- safe_mmkdir(os.path.dirname(second_path))
+ if six.PY2:
+ with pytest.raises(TypeError) as e:
+ next_project_path = tmp_path_factory.mktemp('test_safe_mmkdir__dir_b')
+ safe_mmkdir(next_project_path)
+ assert e.value.message == "directory must be of type str, not {'directory_type': \"<class 'pathlib2.PosixPath'>\"}"
+ | Add test for the intended use case | ## Code Before:
import pytest
import os
from great_expectations.data_context.util import (
safe_mmkdir,
)
def test_safe_mmkdir(tmp_path_factory):
project_path = str(tmp_path_factory.mktemp('empty_dir'))
first_path = os.path.join(project_path,"first_path")
safe_mmkdir(first_path)
assert os.path.isdir(first_path)
with pytest.raises(TypeError):
safe_mmkdir(1)
#This should trigger python 2
second_path = os.path.join(project_path,"second_path")
print(second_path)
print(type(second_path))
safe_mmkdir(os.path.dirname(second_path))
## Instruction:
Add test for the intended use case
## Code After:
import pytest
import os
import six
from great_expectations.data_context.util import (
safe_mmkdir,
)
def test_safe_mmkdir(tmp_path_factory):
project_path = str(tmp_path_factory.mktemp('empty_dir'))
first_path = os.path.join(project_path,"first_path")
safe_mmkdir(first_path)
assert os.path.isdir(first_path)
with pytest.raises(TypeError):
safe_mmkdir(1)
#This should trigger python 2
if six.PY2:
with pytest.raises(TypeError) as e:
next_project_path = tmp_path_factory.mktemp('test_safe_mmkdir__dir_b')
safe_mmkdir(next_project_path)
assert e.value.message == "directory must be of type str, not {'directory_type': \"<class 'pathlib2.PosixPath'>\"}"
| # ... existing code ...
import os
import six
# ... modified code ...
#This should trigger python 2
if six.PY2:
with pytest.raises(TypeError) as e:
next_project_path = tmp_path_factory.mktemp('test_safe_mmkdir__dir_b')
safe_mmkdir(next_project_path)
assert e.value.message == "directory must be of type str, not {'directory_type': \"<class 'pathlib2.PosixPath'>\"}"
# ... rest of the code ... |
04fec1c50ac81c1b80c22f37bd43845a0e08c1a3 | fancypages/assets/models.py | fancypages/assets/models.py | from django.db import models
from django.utils.translation import ugettext as _
class AbstractAsset(models.Model):
name = models.CharField(_("Name"), max_length=255)
date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
date_modified = models.DateTimeField(_("Date modified"), auto_now=True)
description = models.TextField(_("Description"), default="")
creator = models.ForeignKey('auth.User', verbose_name=_("Creator"))
def __unicode__(self):
return self.name
class Meta:
abstract = True
class ImageAsset(AbstractAsset):
image = models.ImageField(
upload_to='asset/images/%Y/%m',
width_field='width',
height_field='height',
verbose_name=_("Image")
)
width = models.IntegerField(_("Width"), blank=True)
height = models.IntegerField(_("Height"), blank=True)
size = models.IntegerField(_("Size"), blank=True, null=True) # Bytes
@property
def asset_type(self):
return self._meta.object_name.lower()
def get_absolute_url(self):
return self.image.url
| from django.db import models
from django.utils.translation import ugettext as _
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
class AbstractAsset(models.Model):
name = models.CharField(_("Name"), max_length=255)
date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
date_modified = models.DateTimeField(_("Date modified"), auto_now=True)
description = models.TextField(_("Description"), default="")
creator = models.ForeignKey(User, verbose_name=_("Creator"))
def __unicode__(self):
return self.name
class Meta:
abstract = True
class ImageAsset(AbstractAsset):
image = models.ImageField(
upload_to='asset/images/%Y/%m',
width_field='width',
height_field='height',
verbose_name=_("Image")
)
width = models.IntegerField(_("Width"), blank=True)
height = models.IntegerField(_("Height"), blank=True)
size = models.IntegerField(_("Size"), blank=True, null=True) # Bytes
@property
def asset_type(self):
return self._meta.object_name.lower()
def get_absolute_url(self):
return self.image.url
| Add support for custom user model (Django 1.5+) | Add support for custom user model (Django 1.5+)
| Python | bsd-3-clause | socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages | from django.db import models
from django.utils.translation import ugettext as _
+
+ try:
+ from django.contrib.auth import get_user_model
+ User = get_user_model()
+ except ImportError:
+ from django.contrib.auth.models import User
class AbstractAsset(models.Model):
name = models.CharField(_("Name"), max_length=255)
date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
date_modified = models.DateTimeField(_("Date modified"), auto_now=True)
description = models.TextField(_("Description"), default="")
- creator = models.ForeignKey('auth.User', verbose_name=_("Creator"))
+ creator = models.ForeignKey(User, verbose_name=_("Creator"))
def __unicode__(self):
return self.name
class Meta:
abstract = True
class ImageAsset(AbstractAsset):
image = models.ImageField(
upload_to='asset/images/%Y/%m',
width_field='width',
height_field='height',
verbose_name=_("Image")
)
width = models.IntegerField(_("Width"), blank=True)
height = models.IntegerField(_("Height"), blank=True)
size = models.IntegerField(_("Size"), blank=True, null=True) # Bytes
@property
def asset_type(self):
return self._meta.object_name.lower()
def get_absolute_url(self):
return self.image.url
| Add support for custom user model (Django 1.5+) | ## Code Before:
from django.db import models
from django.utils.translation import ugettext as _
class AbstractAsset(models.Model):
name = models.CharField(_("Name"), max_length=255)
date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
date_modified = models.DateTimeField(_("Date modified"), auto_now=True)
description = models.TextField(_("Description"), default="")
creator = models.ForeignKey('auth.User', verbose_name=_("Creator"))
def __unicode__(self):
return self.name
class Meta:
abstract = True
class ImageAsset(AbstractAsset):
image = models.ImageField(
upload_to='asset/images/%Y/%m',
width_field='width',
height_field='height',
verbose_name=_("Image")
)
width = models.IntegerField(_("Width"), blank=True)
height = models.IntegerField(_("Height"), blank=True)
size = models.IntegerField(_("Size"), blank=True, null=True) # Bytes
@property
def asset_type(self):
return self._meta.object_name.lower()
def get_absolute_url(self):
return self.image.url
## Instruction:
Add support for custom user model (Django 1.5+)
## Code After:
from django.db import models
from django.utils.translation import ugettext as _
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
class AbstractAsset(models.Model):
name = models.CharField(_("Name"), max_length=255)
date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
date_modified = models.DateTimeField(_("Date modified"), auto_now=True)
description = models.TextField(_("Description"), default="")
creator = models.ForeignKey(User, verbose_name=_("Creator"))
def __unicode__(self):
return self.name
class Meta:
abstract = True
class ImageAsset(AbstractAsset):
image = models.ImageField(
upload_to='asset/images/%Y/%m',
width_field='width',
height_field='height',
verbose_name=_("Image")
)
width = models.IntegerField(_("Width"), blank=True)
height = models.IntegerField(_("Height"), blank=True)
size = models.IntegerField(_("Size"), blank=True, null=True) # Bytes
@property
def asset_type(self):
return self._meta.object_name.lower()
def get_absolute_url(self):
return self.image.url
| // ... existing code ...
from django.utils.translation import ugettext as _
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
// ... modified code ...
description = models.TextField(_("Description"), default="")
creator = models.ForeignKey(User, verbose_name=_("Creator"))
// ... rest of the code ... |
da516d06ab294dc2dde4bb671ab16653b1421314 | tests/performance.py | tests/performance.py | """Script to run performance check."""
import time
from examples.game_of_life import GameOfLife, GOLExperiment
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
]
NUM_STEPS = 10000
if __name__ == "__main__":
for name, model, experiment in MODELS:
ca = model(experiment)
start_time = time.time()
for j in range(NUM_STEPS):
ca.step()
time_passed = time.time() - start_time
speed = NUM_STEPS * ca.cells_num // time_passed
print("%s: %s cells/s" % (name, sizeof_fmt(speed)))
del ca
| """Script to run performance check."""
import time
from examples.game_of_life import (
GameOfLife, GOLExperiment
)
from examples.shifting_sands import (
ShiftingSands, ShiftingSandsExperiment
)
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
("Shifting Sands", ShiftingSands, ShiftingSandsExperiment),
]
NUM_STEPS = 10000
if __name__ == "__main__":
for name, model, experiment in MODELS:
ca = model(experiment)
start_time = time.time()
for j in range(NUM_STEPS):
ca.step()
time_passed = time.time() - start_time
speed = NUM_STEPS * ca.cells_num // time_passed
print("%s: %s cells/s" % (name, sizeof_fmt(speed)))
del ca
| Add Shifting Sands to benchmark tests | Add Shifting Sands to benchmark tests
| Python | mit | a5kin/hecate,a5kin/hecate | """Script to run performance check."""
import time
- from examples.game_of_life import GameOfLife, GOLExperiment
+ from examples.game_of_life import (
+ GameOfLife, GOLExperiment
+ )
+ from examples.shifting_sands import (
+ ShiftingSands, ShiftingSandsExperiment
+ )
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
+ ("Shifting Sands", ShiftingSands, ShiftingSandsExperiment),
]
NUM_STEPS = 10000
if __name__ == "__main__":
for name, model, experiment in MODELS:
ca = model(experiment)
start_time = time.time()
for j in range(NUM_STEPS):
ca.step()
time_passed = time.time() - start_time
speed = NUM_STEPS * ca.cells_num // time_passed
print("%s: %s cells/s" % (name, sizeof_fmt(speed)))
del ca
| Add Shifting Sands to benchmark tests | ## Code Before:
"""Script to run performance check."""
import time
from examples.game_of_life import GameOfLife, GOLExperiment
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
]
NUM_STEPS = 10000
if __name__ == "__main__":
for name, model, experiment in MODELS:
ca = model(experiment)
start_time = time.time()
for j in range(NUM_STEPS):
ca.step()
time_passed = time.time() - start_time
speed = NUM_STEPS * ca.cells_num // time_passed
print("%s: %s cells/s" % (name, sizeof_fmt(speed)))
del ca
## Instruction:
Add Shifting Sands to benchmark tests
## Code After:
"""Script to run performance check."""
import time
from examples.game_of_life import (
GameOfLife, GOLExperiment
)
from examples.shifting_sands import (
ShiftingSands, ShiftingSandsExperiment
)
from xentica.utils.formatters import sizeof_fmt
MODELS = [
("Conway's Life", GameOfLife, GOLExperiment),
("Shifting Sands", ShiftingSands, ShiftingSandsExperiment),
]
NUM_STEPS = 10000
if __name__ == "__main__":
for name, model, experiment in MODELS:
ca = model(experiment)
start_time = time.time()
for j in range(NUM_STEPS):
ca.step()
time_passed = time.time() - start_time
speed = NUM_STEPS * ca.cells_num // time_passed
print("%s: %s cells/s" % (name, sizeof_fmt(speed)))
del ca
| // ... existing code ...
from examples.game_of_life import (
GameOfLife, GOLExperiment
)
from examples.shifting_sands import (
ShiftingSands, ShiftingSandsExperiment
)
from xentica.utils.formatters import sizeof_fmt
// ... modified code ...
("Conway's Life", GameOfLife, GOLExperiment),
("Shifting Sands", ShiftingSands, ShiftingSandsExperiment),
]
// ... rest of the code ... |
64732e7dd32f23b9431bd69fecd757af1772053e | local_test_settings.py | local_test_settings.py | from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
UNICORE_DISTRIBUTE_API = 'http://testserver:6543'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
| from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
| Remove UNICORE_DISTRIBUTE_API from test settings | Remove UNICORE_DISTRIBUTE_API from test settings
This stopped being used in 11457e0fa578f09e7e8a4fd0f1595b4e47ab109c
| Python | bsd-2-clause | praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo | from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
- UNICORE_DISTRIBUTE_API = 'http://testserver:6543'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
| Remove UNICORE_DISTRIBUTE_API from test settings | ## Code Before:
from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
UNICORE_DISTRIBUTE_API = 'http://testserver:6543'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
## Instruction:
Remove UNICORE_DISTRIBUTE_API from test settings
## Code After:
from testapp.settings.base import *
ENABLE_SSO = True
MIDDLEWARE_CLASSES += (
'molo.core.middleware.MoloCASMiddleware',
'molo.core.middleware.Custom403Middleware',
)
AUTHENTICATION_BACKENDS = (
'molo.profiles.backends.MoloProfilesModelBackend',
'molo.core.backends.MoloModelBackend',
'django.contrib.auth.backends.ModelBackend',
'molo.core.backends.MoloCASBackend',
)
CAS_SERVER_URL = 'http://testcasserver'
CAS_ADMIN_PREFIX = '/admin/'
LOGIN_URL = '/accounts/login/'
CAS_VERSION = '3'
CELERY_ALWAYS_EAGER = True
DEAFULT_SITE_PORT = 8000
INSTALLED_APPS = INSTALLED_APPS + [
'import_export',
]
| # ... existing code ...
CELERY_ALWAYS_EAGER = True
# ... rest of the code ... |
eb1c913a0800e2d5eabf34e7abce96c8f4096d79 | marble/tests/test_neighbourhoods.py | marble/tests/test_neighbourhoods.py | """ Tests for the extraction of neighbourhoods """
from nose.tools import *
import marble as mb
# Test that for a grid, corners are not neighbours (.touch might have to go)
# Test clustering on a situation
| """ Tests for the extraction of neighbourhoods """
from nose.tools import *
import itertools
from shapely.geometry import Polygon
import marble as mb
from marble.neighbourhoods import _adjacency
#
# Synthetic data for tests
#
def grid():
au = [i*3+j for i,j in itertools.product(range(3), repeat=2)]
units = {a:Polygon([(a%3, a/3),
(a%3, 1+a/3),
(1+a%3, 1+a/3),
(1+a%3, a/3)]) for a in au}
return units
class TestNeighbourhoods(object):
def test_adjacency(test):
""" Test the extraction of the adjacency list """
units = grid()
adj = _adjacency(units)
adj_answer = {0:[1,3],
1:[0,4,2],
2:[1,5],
3:[0,4,6],
4:[1,3,5,7],
5:[2,4,8],
6:[3,7],
7:[4,6,8],
8:[5,7]}
for au in adj:
assert set(adj[au]) == set(adj_answer[au])
# Test that for a grid, corners are not neighbours (.touch might have to go)
# Test clustering on a situation
| Test the adjacency matrix finder | Test the adjacency matrix finder
| Python | bsd-3-clause | scities/marble,walkerke/marble | """ Tests for the extraction of neighbourhoods """
from nose.tools import *
+ import itertools
+ from shapely.geometry import Polygon
import marble as mb
+ from marble.neighbourhoods import _adjacency
+
+
+ #
+ # Synthetic data for tests
+ #
+ def grid():
+ au = [i*3+j for i,j in itertools.product(range(3), repeat=2)]
+ units = {a:Polygon([(a%3, a/3),
+ (a%3, 1+a/3),
+ (1+a%3, 1+a/3),
+ (1+a%3, a/3)]) for a in au}
+ return units
+
+
+
+ class TestNeighbourhoods(object):
+
+ def test_adjacency(test):
+ """ Test the extraction of the adjacency list """
+ units = grid()
+ adj = _adjacency(units)
+ adj_answer = {0:[1,3],
+ 1:[0,4,2],
+ 2:[1,5],
+ 3:[0,4,6],
+ 4:[1,3,5,7],
+ 5:[2,4,8],
+ 6:[3,7],
+ 7:[4,6,8],
+ 8:[5,7]}
+
+ for au in adj:
+ assert set(adj[au]) == set(adj_answer[au])
# Test that for a grid, corners are not neighbours (.touch might have to go)
# Test clustering on a situation
| Test the adjacency matrix finder | ## Code Before:
""" Tests for the extraction of neighbourhoods """
from nose.tools import *
import marble as mb
# Test that for a grid, corners are not neighbours (.touch might have to go)
# Test clustering on a situation
## Instruction:
Test the adjacency matrix finder
## Code After:
""" Tests for the extraction of neighbourhoods """
from nose.tools import *
import itertools
from shapely.geometry import Polygon
import marble as mb
from marble.neighbourhoods import _adjacency
#
# Synthetic data for tests
#
def grid():
au = [i*3+j for i,j in itertools.product(range(3), repeat=2)]
units = {a:Polygon([(a%3, a/3),
(a%3, 1+a/3),
(1+a%3, 1+a/3),
(1+a%3, a/3)]) for a in au}
return units
class TestNeighbourhoods(object):
def test_adjacency(test):
""" Test the extraction of the adjacency list """
units = grid()
adj = _adjacency(units)
adj_answer = {0:[1,3],
1:[0,4,2],
2:[1,5],
3:[0,4,6],
4:[1,3,5,7],
5:[2,4,8],
6:[3,7],
7:[4,6,8],
8:[5,7]}
for au in adj:
assert set(adj[au]) == set(adj_answer[au])
# Test that for a grid, corners are not neighbours (.touch might have to go)
# Test clustering on a situation
| ...
from nose.tools import *
import itertools
from shapely.geometry import Polygon
import marble as mb
from marble.neighbourhoods import _adjacency
#
# Synthetic data for tests
#
def grid():
au = [i*3+j for i,j in itertools.product(range(3), repeat=2)]
units = {a:Polygon([(a%3, a/3),
(a%3, 1+a/3),
(1+a%3, 1+a/3),
(1+a%3, a/3)]) for a in au}
return units
class TestNeighbourhoods(object):
def test_adjacency(test):
""" Test the extraction of the adjacency list """
units = grid()
adj = _adjacency(units)
adj_answer = {0:[1,3],
1:[0,4,2],
2:[1,5],
3:[0,4,6],
4:[1,3,5,7],
5:[2,4,8],
6:[3,7],
7:[4,6,8],
8:[5,7]}
for au in adj:
assert set(adj[au]) == set(adj_answer[au])
... |
8b7aef341aadefb859790684f41453f561813083 | tmi/views/__init__.py | tmi/views/__init__.py | from flask import g
from flask.ext.login import current_user
from tmi.core import app
from tmi.assets import assets # noqa
from tmi.views.ui import ui # noqa
from tmi.views.auth import login, logout # noqa
from tmi.views.admin import admin # noqa
from tmi.views.cards_api import blueprint as cards_api
@app.before_request
def before_request():
g.user = current_user
app.register_blueprint(cards_api)
| from flask import g, request
from flask.ext.login import current_user
from werkzeug.exceptions import HTTPException
from tmi.core import app
from tmi.forms import Invalid
from tmi.util import jsonify
from tmi.assets import assets # noqa
from tmi.views.ui import ui # noqa
from tmi.views.auth import login, logout # noqa
from tmi.views.admin import admin # noqa
from tmi.views.cards_api import blueprint as cards_api
@app.before_request
def before_request():
g.user = current_user
app.register_blueprint(cards_api)
@app.errorhandler(401)
@app.errorhandler(403)
@app.errorhandler(404)
@app.errorhandler(410)
@app.errorhandler(500)
def handle_exceptions(exc):
if isinstance(exc, HTTPException):
message = exc.get_description(request.environ)
message = message.replace('<p>', '').replace('</p>', '')
body = {
'status': exc.code,
'name': exc.name,
'message': message
}
headers = exc.get_headers(request.environ)
else:
body = {
'status': 500,
'name': exc.__class__.__name__,
'message': unicode(exc)
}
headers = {}
return jsonify(body, status=body.get('status'),
headers=headers)
@app.errorhandler(Invalid)
def handle_invalid(exc):
body = {
'status': 400,
'name': 'Invalid Data',
'message': unicode(exc),
'errors': exc.asdict()
}
return jsonify(body, status=400)
| Handle errors with JSON messages. | Handle errors with JSON messages. | Python | mit | pudo/storyweb,pudo/storyweb | - from flask import g
+ from flask import g, request
from flask.ext.login import current_user
+ from werkzeug.exceptions import HTTPException
from tmi.core import app
+ from tmi.forms import Invalid
+ from tmi.util import jsonify
from tmi.assets import assets # noqa
from tmi.views.ui import ui # noqa
from tmi.views.auth import login, logout # noqa
from tmi.views.admin import admin # noqa
from tmi.views.cards_api import blueprint as cards_api
@app.before_request
def before_request():
g.user = current_user
app.register_blueprint(cards_api)
+
+ @app.errorhandler(401)
+ @app.errorhandler(403)
+ @app.errorhandler(404)
+ @app.errorhandler(410)
+ @app.errorhandler(500)
+ def handle_exceptions(exc):
+ if isinstance(exc, HTTPException):
+ message = exc.get_description(request.environ)
+ message = message.replace('<p>', '').replace('</p>', '')
+ body = {
+ 'status': exc.code,
+ 'name': exc.name,
+ 'message': message
+ }
+ headers = exc.get_headers(request.environ)
+ else:
+ body = {
+ 'status': 500,
+ 'name': exc.__class__.__name__,
+ 'message': unicode(exc)
+ }
+ headers = {}
+ return jsonify(body, status=body.get('status'),
+ headers=headers)
+
+
+ @app.errorhandler(Invalid)
+ def handle_invalid(exc):
+ body = {
+ 'status': 400,
+ 'name': 'Invalid Data',
+ 'message': unicode(exc),
+ 'errors': exc.asdict()
+ }
+ return jsonify(body, status=400)
+ | Handle errors with JSON messages. | ## Code Before:
from flask import g
from flask.ext.login import current_user
from tmi.core import app
from tmi.assets import assets # noqa
from tmi.views.ui import ui # noqa
from tmi.views.auth import login, logout # noqa
from tmi.views.admin import admin # noqa
from tmi.views.cards_api import blueprint as cards_api
@app.before_request
def before_request():
g.user = current_user
app.register_blueprint(cards_api)
## Instruction:
Handle errors with JSON messages.
## Code After:
from flask import g, request
from flask.ext.login import current_user
from werkzeug.exceptions import HTTPException
from tmi.core import app
from tmi.forms import Invalid
from tmi.util import jsonify
from tmi.assets import assets # noqa
from tmi.views.ui import ui # noqa
from tmi.views.auth import login, logout # noqa
from tmi.views.admin import admin # noqa
from tmi.views.cards_api import blueprint as cards_api
@app.before_request
def before_request():
g.user = current_user
app.register_blueprint(cards_api)
@app.errorhandler(401)
@app.errorhandler(403)
@app.errorhandler(404)
@app.errorhandler(410)
@app.errorhandler(500)
def handle_exceptions(exc):
if isinstance(exc, HTTPException):
message = exc.get_description(request.environ)
message = message.replace('<p>', '').replace('</p>', '')
body = {
'status': exc.code,
'name': exc.name,
'message': message
}
headers = exc.get_headers(request.environ)
else:
body = {
'status': 500,
'name': exc.__class__.__name__,
'message': unicode(exc)
}
headers = {}
return jsonify(body, status=body.get('status'),
headers=headers)
@app.errorhandler(Invalid)
def handle_invalid(exc):
body = {
'status': 400,
'name': 'Invalid Data',
'message': unicode(exc),
'errors': exc.asdict()
}
return jsonify(body, status=400)
| ...
from flask import g, request
from flask.ext.login import current_user
from werkzeug.exceptions import HTTPException
...
from tmi.core import app
from tmi.forms import Invalid
from tmi.util import jsonify
from tmi.assets import assets # noqa
...
app.register_blueprint(cards_api)
@app.errorhandler(401)
@app.errorhandler(403)
@app.errorhandler(404)
@app.errorhandler(410)
@app.errorhandler(500)
def handle_exceptions(exc):
if isinstance(exc, HTTPException):
message = exc.get_description(request.environ)
message = message.replace('<p>', '').replace('</p>', '')
body = {
'status': exc.code,
'name': exc.name,
'message': message
}
headers = exc.get_headers(request.environ)
else:
body = {
'status': 500,
'name': exc.__class__.__name__,
'message': unicode(exc)
}
headers = {}
return jsonify(body, status=body.get('status'),
headers=headers)
@app.errorhandler(Invalid)
def handle_invalid(exc):
body = {
'status': 400,
'name': 'Invalid Data',
'message': unicode(exc),
'errors': exc.asdict()
}
return jsonify(body, status=400)
... |
ba2f2d7e53f0ffc58c882d78f1b8bc9a468eb164 | predicates.py | predicates.py | class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(self.members)
def oneof(*members):
return OneOf(members)
class InRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __call__(self, candidate):
if self.start <= candidate <= self.end:
return True
return "%s not between %s and %s" % (candidate, self.start, self.end)
def __repr__(self):
return "between %s and %s" % (self.start, self.end)
def inrange(start, end):
return InRange(start, end)
| class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(map(repr, self.members))
def oneof(*members):
return OneOf(members)
class InRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __call__(self, candidate):
if self.start <= candidate <= self.end:
return True
return "%s not between %s and %s" % (candidate, self.start, self.end)
def __repr__(self):
return "between %s and %s" % (self.start, self.end)
def inrange(start, end):
return InRange(start, end)
| Fix problem rendering oneof() predicate when the members aren't strings | Fix problem rendering oneof() predicate when the members aren't strings
| Python | mit | mrozekma/pytypecheck | class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
- return "one of %s" % ', '.join(self.members)
+ return "one of %s" % ', '.join(map(repr, self.members))
def oneof(*members):
return OneOf(members)
class InRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __call__(self, candidate):
if self.start <= candidate <= self.end:
return True
return "%s not between %s and %s" % (candidate, self.start, self.end)
def __repr__(self):
return "between %s and %s" % (self.start, self.end)
def inrange(start, end):
return InRange(start, end)
| Fix problem rendering oneof() predicate when the members aren't strings | ## Code Before:
class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(self.members)
def oneof(*members):
return OneOf(members)
class InRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __call__(self, candidate):
if self.start <= candidate <= self.end:
return True
return "%s not between %s and %s" % (candidate, self.start, self.end)
def __repr__(self):
return "between %s and %s" % (self.start, self.end)
def inrange(start, end):
return InRange(start, end)
## Instruction:
Fix problem rendering oneof() predicate when the members aren't strings
## Code After:
class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(map(repr, self.members))
def oneof(*members):
return OneOf(members)
class InRange:
def __init__(self, start, end):
self.start = start
self.end = end
def __call__(self, candidate):
if self.start <= candidate <= self.end:
return True
return "%s not between %s and %s" % (candidate, self.start, self.end)
def __repr__(self):
return "between %s and %s" % (self.start, self.end)
def inrange(start, end):
return InRange(start, end)
| ...
def __repr__(self):
return "one of %s" % ', '.join(map(repr, self.members))
... |
ffd429281ed6695457304646467a6d9e0a0301a4 | src/nyc_trees/apps/core/tasks.py | src/nyc_trees/apps/core/tasks.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from celery import task
from django.core.files.storage import default_storage
@task(bind=True, max_retries=15, default_retry_delay=2)
def wait_for_default_storage_file(self, filename):
if default_storage.exists(filename):
return filename
else:
self.retry()
| from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from celery import task
from django.core.files.storage import default_storage
@task(bind=True, max_retries=15, default_retry_delay=2)
def wait_for_default_storage_file(self, filename):
if default_storage.exists(filename):
return filename
elif self.request.retries < self.max_retries:
self.retry()
else:
return None
| Send RSVP email even if PDF doesn't exist | Send RSVP email even if PDF doesn't exist
If the PDF can't be found on the disk after the maximum number of
retries, return None, instead of raising an exception. This ensures that
the RSVP email notification still sends even without the PDF attachment.
Refs #1655
| Python | agpl-3.0 | azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,azavea/nyc-trees,kdeloach/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from celery import task
from django.core.files.storage import default_storage
@task(bind=True, max_retries=15, default_retry_delay=2)
def wait_for_default_storage_file(self, filename):
if default_storage.exists(filename):
return filename
+ elif self.request.retries < self.max_retries:
+ self.retry()
else:
- self.retry()
+ return None
| Send RSVP email even if PDF doesn't exist | ## Code Before:
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from celery import task
from django.core.files.storage import default_storage
@task(bind=True, max_retries=15, default_retry_delay=2)
def wait_for_default_storage_file(self, filename):
if default_storage.exists(filename):
return filename
else:
self.retry()
## Instruction:
Send RSVP email even if PDF doesn't exist
## Code After:
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from celery import task
from django.core.files.storage import default_storage
@task(bind=True, max_retries=15, default_retry_delay=2)
def wait_for_default_storage_file(self, filename):
if default_storage.exists(filename):
return filename
elif self.request.retries < self.max_retries:
self.retry()
else:
return None
| # ... existing code ...
return filename
elif self.request.retries < self.max_retries:
self.retry()
else:
return None
# ... rest of the code ... |
d0ec3ee9b974fb6956c32e8dfdd6d20ea4da7cff | pwndbg/inthook.py | pwndbg/inthook.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import gdb
import pwndbg.typeinfo
if sys.version_info < (3,0):
import __builtin__ as builtins
_int = builtins.int
# We need this class to get isinstance(7, xint) to return True
class IsAnInt(type):
def __instancecheck__(self, other):
return isinstance(other, _int)
class xint(builtins.int):
__metaclass__ = IsAnInt
def __new__(cls, value, *a, **kw):
if isinstance(value, gdb.Value):
if pwndbg.typeinfo.is_pointer(value):
value = value.cast(pwndbg.typeinfo.ulong)
else:
value = value.cast(pwndbg.typeinfo.long)
return _int(_int(value, *a, **kw))
builtins.int = xint
globals()['int'] = xint
# Additionally, we need to compensate for Python2
else:
import builtins
builtins.long = int
globals()['long'] = int
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import gdb
import pwndbg.typeinfo
if sys.version_info < (3,0):
import __builtin__ as builtins
else:
import builtins
_int = builtins.int
# We need this class to get isinstance(7, xint) to return True
class IsAnInt(type):
def __instancecheck__(self, other):
return isinstance(other, _int)
class xint(builtins.int):
__metaclass__ = IsAnInt
def __new__(cls, value, *a, **kw):
if isinstance(value, gdb.Value):
if pwndbg.typeinfo.is_pointer(value):
value = value.cast(pwndbg.typeinfo.ulong)
else:
value = value.cast(pwndbg.typeinfo.long)
return _int(_int(value, *a, **kw))
builtins.int = xint
globals()['int'] = xint
if sys.version_info >= (3,0):
builtins.long = xint
globals()['long'] = xint
| Add int hook to Python3 | Add int hook to Python3
Fixes #120
| Python | mit | pwndbg/pwndbg,cebrusfs/217gdb,cebrusfs/217gdb,pwndbg/pwndbg,cebrusfs/217gdb,chubbymaggie/pwndbg,disconnect3d/pwndbg,disconnect3d/pwndbg,pwndbg/pwndbg,0xddaa/pwndbg,zachriggle/pwndbg,0xddaa/pwndbg,disconnect3d/pwndbg,anthraxx/pwndbg,chubbymaggie/pwndbg,0xddaa/pwndbg,cebrusfs/217gdb,anthraxx/pwndbg,zachriggle/pwndbg,anthraxx/pwndbg,pwndbg/pwndbg,anthraxx/pwndbg | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import gdb
import pwndbg.typeinfo
if sys.version_info < (3,0):
import __builtin__ as builtins
- _int = builtins.int
-
- # We need this class to get isinstance(7, xint) to return True
- class IsAnInt(type):
- def __instancecheck__(self, other):
- return isinstance(other, _int)
-
- class xint(builtins.int):
- __metaclass__ = IsAnInt
- def __new__(cls, value, *a, **kw):
- if isinstance(value, gdb.Value):
- if pwndbg.typeinfo.is_pointer(value):
- value = value.cast(pwndbg.typeinfo.ulong)
- else:
- value = value.cast(pwndbg.typeinfo.long)
- return _int(_int(value, *a, **kw))
-
- builtins.int = xint
- globals()['int'] = xint
-
- # Additionally, we need to compensate for Python2
else:
import builtins
- builtins.long = int
- globals()['long'] = int
+ _int = builtins.int
+
+ # We need this class to get isinstance(7, xint) to return True
+ class IsAnInt(type):
+ def __instancecheck__(self, other):
+ return isinstance(other, _int)
+
+ class xint(builtins.int):
+ __metaclass__ = IsAnInt
+ def __new__(cls, value, *a, **kw):
+ if isinstance(value, gdb.Value):
+ if pwndbg.typeinfo.is_pointer(value):
+ value = value.cast(pwndbg.typeinfo.ulong)
+ else:
+ value = value.cast(pwndbg.typeinfo.long)
+ return _int(_int(value, *a, **kw))
+
+ builtins.int = xint
+ globals()['int'] = xint
+
+ if sys.version_info >= (3,0):
+ builtins.long = xint
+ globals()['long'] = xint
+
+ | Add int hook to Python3 | ## Code Before:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import gdb
import pwndbg.typeinfo
if sys.version_info < (3,0):
import __builtin__ as builtins
_int = builtins.int
# We need this class to get isinstance(7, xint) to return True
class IsAnInt(type):
def __instancecheck__(self, other):
return isinstance(other, _int)
class xint(builtins.int):
__metaclass__ = IsAnInt
def __new__(cls, value, *a, **kw):
if isinstance(value, gdb.Value):
if pwndbg.typeinfo.is_pointer(value):
value = value.cast(pwndbg.typeinfo.ulong)
else:
value = value.cast(pwndbg.typeinfo.long)
return _int(_int(value, *a, **kw))
builtins.int = xint
globals()['int'] = xint
# Additionally, we need to compensate for Python2
else:
import builtins
builtins.long = int
globals()['long'] = int
## Instruction:
Add int hook to Python3
## Code After:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import gdb
import pwndbg.typeinfo
if sys.version_info < (3,0):
import __builtin__ as builtins
else:
import builtins
_int = builtins.int
# We need this class to get isinstance(7, xint) to return True
class IsAnInt(type):
def __instancecheck__(self, other):
return isinstance(other, _int)
class xint(builtins.int):
__metaclass__ = IsAnInt
def __new__(cls, value, *a, **kw):
if isinstance(value, gdb.Value):
if pwndbg.typeinfo.is_pointer(value):
value = value.cast(pwndbg.typeinfo.ulong)
else:
value = value.cast(pwndbg.typeinfo.long)
return _int(_int(value, *a, **kw))
builtins.int = xint
globals()['int'] = xint
if sys.version_info >= (3,0):
builtins.long = xint
globals()['long'] = xint
| // ... existing code ...
import __builtin__ as builtins
else:
// ... modified code ...
import builtins
_int = builtins.int
# We need this class to get isinstance(7, xint) to return True
class IsAnInt(type):
def __instancecheck__(self, other):
return isinstance(other, _int)
class xint(builtins.int):
__metaclass__ = IsAnInt
def __new__(cls, value, *a, **kw):
if isinstance(value, gdb.Value):
if pwndbg.typeinfo.is_pointer(value):
value = value.cast(pwndbg.typeinfo.ulong)
else:
value = value.cast(pwndbg.typeinfo.long)
return _int(_int(value, *a, **kw))
builtins.int = xint
globals()['int'] = xint
if sys.version_info >= (3,0):
builtins.long = xint
globals()['long'] = xint
// ... rest of the code ... |
d611eb18b234c7d85371d38d8c875aaae447c231 | testing/urls.py | testing/urls.py |
from django.conf.urls import patterns, include, url
from django.views.generic import View
urlpatterns = patterns('',
url(r'foo$', View.as_view(), name="foo"),
)
|
from django.conf.urls import url
from django.views.generic import View
urlpatterns = [
url(r'foo$', View.as_view(), name="foo"),
]
| Fix tests remove unneccessary imports | Fix tests remove unneccessary imports
| Python | bsd-3-clause | niwinz/django-sites,niwinz/django-sites |
- from django.conf.urls import patterns, include, url
+ from django.conf.urls import url
from django.views.generic import View
- urlpatterns = patterns('',
+ urlpatterns = [
url(r'foo$', View.as_view(), name="foo"),
- )
+ ]
| Fix tests remove unneccessary imports | ## Code Before:
from django.conf.urls import patterns, include, url
from django.views.generic import View
urlpatterns = patterns('',
url(r'foo$', View.as_view(), name="foo"),
)
## Instruction:
Fix tests remove unneccessary imports
## Code After:
from django.conf.urls import url
from django.views.generic import View
urlpatterns = [
url(r'foo$', View.as_view(), name="foo"),
]
| # ... existing code ...
from django.conf.urls import url
from django.views.generic import View
# ... modified code ...
urlpatterns = [
url(r'foo$', View.as_view(), name="foo"),
]
# ... rest of the code ... |
6d2f6df3543bc287e59151e823b7a62c245c27b0 | .gitlab/linters/check-cpp.py | .gitlab/linters/check-cpp.py |
from linter import run_linters, RegexpLinter
linters = [
RegexpLinter(r'ASSERT\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'ASSERT2\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'#ifdef\s+',
message='`#if defined(x)` is preferred to `#ifdef x`'),
RegexpLinter(r'#if\s+defined\s+',
message='`#if defined(x)` is preferred to `#if defined x`'),
RegexpLinter(r'#ifndef\s+',
message='`#if !defined(x)` is preferred to `#ifndef x`'),
]
if __name__ == '__main__':
run_linters(linters)
|
from linter import run_linters, RegexpLinter
linters = [
RegexpLinter(r'WARN\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'ASSERT\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'ASSERT2\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'#ifdef\s+',
message='`#if defined(x)` is preferred to `#ifdef x`'),
RegexpLinter(r'#if\s+defined\s+',
message='`#if defined(x)` is preferred to `#if defined x`'),
RegexpLinter(r'#ifndef\s+',
message='`#if !defined(x)` is preferred to `#ifndef x`'),
]
if __name__ == '__main__':
run_linters(linters)
| Check for WARN macro with space separating it from its paren | linters: Check for WARN macro with space separating it from its paren
| Python | bsd-3-clause | sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc |
from linter import run_linters, RegexpLinter
linters = [
+ RegexpLinter(r'WARN\s+\(',
+ message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'ASSERT\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'ASSERT2\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'#ifdef\s+',
message='`#if defined(x)` is preferred to `#ifdef x`'),
RegexpLinter(r'#if\s+defined\s+',
message='`#if defined(x)` is preferred to `#if defined x`'),
RegexpLinter(r'#ifndef\s+',
message='`#if !defined(x)` is preferred to `#ifndef x`'),
]
if __name__ == '__main__':
run_linters(linters)
| Check for WARN macro with space separating it from its paren | ## Code Before:
from linter import run_linters, RegexpLinter
linters = [
RegexpLinter(r'ASSERT\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'ASSERT2\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'#ifdef\s+',
message='`#if defined(x)` is preferred to `#ifdef x`'),
RegexpLinter(r'#if\s+defined\s+',
message='`#if defined(x)` is preferred to `#if defined x`'),
RegexpLinter(r'#ifndef\s+',
message='`#if !defined(x)` is preferred to `#ifndef x`'),
]
if __name__ == '__main__':
run_linters(linters)
## Instruction:
Check for WARN macro with space separating it from its paren
## Code After:
from linter import run_linters, RegexpLinter
linters = [
RegexpLinter(r'WARN\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'ASSERT\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'ASSERT2\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'#ifdef\s+',
message='`#if defined(x)` is preferred to `#ifdef x`'),
RegexpLinter(r'#if\s+defined\s+',
message='`#if defined(x)` is preferred to `#if defined x`'),
RegexpLinter(r'#ifndef\s+',
message='`#if !defined(x)` is preferred to `#ifndef x`'),
]
if __name__ == '__main__':
run_linters(linters)
| # ... existing code ...
linters = [
RegexpLinter(r'WARN\s+\(',
message='CPP macros should not have a space between the macro name and their argument list'),
RegexpLinter(r'ASSERT\s+\(',
# ... rest of the code ... |
a802501943757dd85ce66a11fcd7ae40c0239462 | datastructures.py | datastructures.py |
class Triangle:
"""A class structure for storing and minipulating a triangle.
The trianlge is represented as a 3-tuple of points. Each point is
represented as a 2-tuple of floats, the first element being the
x-coordinate and the second element being the y-coordinate.
Several useful operations can be applied to a triangle such as, rotate,
translate, split across altitude, and rectanglify.
The Triangle (and underlying tuple) should be treated as an immutable
data structure. All methods return a new triangle and do not modify the
existing one."""
def __init__(self, tpl):
"""tpl is a 3-tuple of coordinates"""
self.points = tpl
class Shape:
"""A class structure for representing and minipulating arbitary shapes.
A shape is defines as a list of triangles (see Triangle). Several
operations can be applied to a shape such as rotation, translation and
splitting the shape into two.
This object should be treated as an immutable data structure. All methods
return new shapes and do not modify the existing one."""
def __init__(self, triangle_list):
"""triangle_list is a list of triangles"""
self.triangles = triangle_list
|
import math
class Triangle:
"""A class structure for storing and minipulating a triangle.
The trianlge is represented as a 3-tuple of points. Each point is
represented as a 2-tuple of floats, the first element being the
x-coordinate and the second element being the y-coordinate.
Several useful operations can be applied to a triangle such as, rotate,
translate, split across altitude, and rectanglify.
The Triangle (and underlying tuple) should be treated as an immutable
data structure. All methods return a new triangle and do not modify the
existing one."""
def __init__(self, tpl):
"""tpl is a 3-tuple of coordinates"""
self.points = tpl
def rotate(self, pivot, rangle):
"""Return a new triangle rotate clockwise (by angle) around pivot.
pivot -- A coordinate pair
rangle -- The angle to rotate by in radians"""
new_points = list()
px, py = pivot
for x, y in self.points:
dx, dy = x - px, y - py
current_angle = math.atan2(dy, dx)
total_angle = current_angle + rangle
r = math.hypot(dx, dy)
nx = r*math.cos(total_angle) + px
ny = r*math.sin(total_angle) + py
new_points.append((nx, ny))
return Triangle(tuple(new_points))
class Shape:
"""A class structure for representing and minipulating arbitary shapes.
A shape is defines as a list of triangles (see Triangle). Several
operations can be applied to a shape such as rotation, translation and
splitting the shape into two.
This object should be treated as an immutable data structure. All methods
return new shapes and do not modify the existing one."""
def __init__(self, triangle_list):
"""triangle_list is a list of triangles"""
self.triangles = triangle_list
| Add method to rotate triangle | Add method to rotate triangle
| Python | mit | moyamo/polygon2square | +
+ import math
class Triangle:
"""A class structure for storing and minipulating a triangle.
The trianlge is represented as a 3-tuple of points. Each point is
represented as a 2-tuple of floats, the first element being the
x-coordinate and the second element being the y-coordinate.
Several useful operations can be applied to a triangle such as, rotate,
translate, split across altitude, and rectanglify.
The Triangle (and underlying tuple) should be treated as an immutable
data structure. All methods return a new triangle and do not modify the
existing one."""
def __init__(self, tpl):
"""tpl is a 3-tuple of coordinates"""
self.points = tpl
+
+ def rotate(self, pivot, rangle):
+ """Return a new triangle rotate clockwise (by angle) around pivot.
+ pivot -- A coordinate pair
+ rangle -- The angle to rotate by in radians"""
+ new_points = list()
+ px, py = pivot
+ for x, y in self.points:
+ dx, dy = x - px, y - py
+ current_angle = math.atan2(dy, dx)
+ total_angle = current_angle + rangle
+ r = math.hypot(dx, dy)
+ nx = r*math.cos(total_angle) + px
+ ny = r*math.sin(total_angle) + py
+ new_points.append((nx, ny))
+ return Triangle(tuple(new_points))
+
class Shape:
"""A class structure for representing and minipulating arbitary shapes.
A shape is defines as a list of triangles (see Triangle). Several
operations can be applied to a shape such as rotation, translation and
splitting the shape into two.
This object should be treated as an immutable data structure. All methods
return new shapes and do not modify the existing one."""
def __init__(self, triangle_list):
"""triangle_list is a list of triangles"""
self.triangles = triangle_list
| Add method to rotate triangle | ## Code Before:
class Triangle:
"""A class structure for storing and minipulating a triangle.
The trianlge is represented as a 3-tuple of points. Each point is
represented as a 2-tuple of floats, the first element being the
x-coordinate and the second element being the y-coordinate.
Several useful operations can be applied to a triangle such as, rotate,
translate, split across altitude, and rectanglify.
The Triangle (and underlying tuple) should be treated as an immutable
data structure. All methods return a new triangle and do not modify the
existing one."""
def __init__(self, tpl):
"""tpl is a 3-tuple of coordinates"""
self.points = tpl
class Shape:
"""A class structure for representing and minipulating arbitary shapes.
A shape is defines as a list of triangles (see Triangle). Several
operations can be applied to a shape such as rotation, translation and
splitting the shape into two.
This object should be treated as an immutable data structure. All methods
return new shapes and do not modify the existing one."""
def __init__(self, triangle_list):
"""triangle_list is a list of triangles"""
self.triangles = triangle_list
## Instruction:
Add method to rotate triangle
## Code After:
import math
class Triangle:
"""A class structure for storing and minipulating a triangle.
The trianlge is represented as a 3-tuple of points. Each point is
represented as a 2-tuple of floats, the first element being the
x-coordinate and the second element being the y-coordinate.
Several useful operations can be applied to a triangle such as, rotate,
translate, split across altitude, and rectanglify.
The Triangle (and underlying tuple) should be treated as an immutable
data structure. All methods return a new triangle and do not modify the
existing one."""
def __init__(self, tpl):
"""tpl is a 3-tuple of coordinates"""
self.points = tpl
def rotate(self, pivot, rangle):
"""Return a new triangle rotate clockwise (by angle) around pivot.
pivot -- A coordinate pair
rangle -- The angle to rotate by in radians"""
new_points = list()
px, py = pivot
for x, y in self.points:
dx, dy = x - px, y - py
current_angle = math.atan2(dy, dx)
total_angle = current_angle + rangle
r = math.hypot(dx, dy)
nx = r*math.cos(total_angle) + px
ny = r*math.sin(total_angle) + py
new_points.append((nx, ny))
return Triangle(tuple(new_points))
class Shape:
"""A class structure for representing and minipulating arbitary shapes.
A shape is defines as a list of triangles (see Triangle). Several
operations can be applied to a shape such as rotation, translation and
splitting the shape into two.
This object should be treated as an immutable data structure. All methods
return new shapes and do not modify the existing one."""
def __init__(self, triangle_list):
"""triangle_list is a list of triangles"""
self.triangles = triangle_list
| // ... existing code ...
import math
// ... modified code ...
self.points = tpl
def rotate(self, pivot, rangle):
"""Return a new triangle rotate clockwise (by angle) around pivot.
pivot -- A coordinate pair
rangle -- The angle to rotate by in radians"""
new_points = list()
px, py = pivot
for x, y in self.points:
dx, dy = x - px, y - py
current_angle = math.atan2(dy, dx)
total_angle = current_angle + rangle
r = math.hypot(dx, dy)
nx = r*math.cos(total_angle) + px
ny = r*math.sin(total_angle) + py
new_points.append((nx, ny))
return Triangle(tuple(new_points))
// ... rest of the code ... |
c0512873d1f558768c174c64faf419e03b63e24b | pijobs/flashjob.py | pijobs/flashjob.py | import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class FlashJob(ScrollphatJob):
def run(self):
scrollphat.clear()
for i in range(int(self.options['loop'])):
scrollphat.set_pixels(lambda x, y: True, True)
self.sleep_interval()
scrollphat.clear()
self.sleep_interval()
self.sleep()
| import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class FlashJob(ScrollphatJob):
def run(self):
scrollphat.clear()
for i in range(int(self.options['loop'])):
scrollphat.set_pixels(lambda x, y: True, True)
self.sleep_interval()
scrollphat.clear()
self.sleep_interval()
self.sleep()
def default_options(self):
return {
'loop': 5,
'brightness': 10,
'interval': 0.2,
}
| Add default options for FlashJob. | Add default options for FlashJob.
| Python | mit | ollej/piapi,ollej/piapi | import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class FlashJob(ScrollphatJob):
def run(self):
scrollphat.clear()
for i in range(int(self.options['loop'])):
scrollphat.set_pixels(lambda x, y: True, True)
self.sleep_interval()
scrollphat.clear()
self.sleep_interval()
self.sleep()
+ def default_options(self):
+ return {
+ 'loop': 5,
+ 'brightness': 10,
+ 'interval': 0.2,
+ }
| Add default options for FlashJob. | ## Code Before:
import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class FlashJob(ScrollphatJob):
def run(self):
scrollphat.clear()
for i in range(int(self.options['loop'])):
scrollphat.set_pixels(lambda x, y: True, True)
self.sleep_interval()
scrollphat.clear()
self.sleep_interval()
self.sleep()
## Instruction:
Add default options for FlashJob.
## Code After:
import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class FlashJob(ScrollphatJob):
def run(self):
scrollphat.clear()
for i in range(int(self.options['loop'])):
scrollphat.set_pixels(lambda x, y: True, True)
self.sleep_interval()
scrollphat.clear()
self.sleep_interval()
self.sleep()
def default_options(self):
return {
'loop': 5,
'brightness': 10,
'interval': 0.2,
}
| # ... existing code ...
def default_options(self):
return {
'loop': 5,
'brightness': 10,
'interval': 0.2,
}
# ... rest of the code ... |
4a07beaf945ce26186fa80f3114cb4c7dc0dd697 | tests/app/test_rest.py | tests/app/test_rest.py | import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
| import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
def it_shows_db_error(self, mocker, client, db):
mocker.patch('app.rest.db.session.execute', side_effect=Exception('db error'))
response = client.get(
url_for('.get_info')
)
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == 'Database error, check logs'
| Add test for info when db error | Add test for info when db error
| Python | mit | NewAcropolis/api,NewAcropolis/api,NewAcropolis/api | import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
+ def it_shows_db_error(self, mocker, client, db):
+ mocker.patch('app.rest.db.session.execute', side_effect=Exception('db error'))
+ response = client.get(
+ url_for('.get_info')
+ )
+ json_resp = json.loads(response.get_data(as_text=True))['info']
+ assert response.status_code == 200
+ assert json_resp == 'Database error, check logs'
+ | Add test for info when db error | ## Code Before:
import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
## Instruction:
Add test for info when db error
## Code After:
import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
def it_shows_db_error(self, mocker, client, db):
mocker.patch('app.rest.db.session.execute', side_effect=Exception('db error'))
response = client.get(
url_for('.get_info')
)
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == 'Database error, check logs'
| ...
assert json_resp == version_from_db
def it_shows_db_error(self, mocker, client, db):
mocker.patch('app.rest.db.session.execute', side_effect=Exception('db error'))
response = client.get(
url_for('.get_info')
)
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == 'Database error, check logs'
... |
2611476df6f362cd59e4aad38a243fc8f6cbf8a8 | devincachu/purger.py | devincachu/purger.py | import roan
from django.contrib.flatpages import models
from palestras import models as pmodels
def connect():
flatpages = models.FlatPage.objects.all()
for f in flatpages:
roan.purge(f.url).on_save(models.FlatPage)
palestras = pmodels.Palestra.objects.all()
for p in palestras:
roan.purge(p.get_absolute_url_and_link_title()['url']).on_save(pmodels.Palestra)
roan.purge(p.get_absolute_url_and_link_title()['url']).on_delete(pmodels.Palestra)
| import roan
from django.contrib.flatpages import models
from palestras import models as pmodels
def connect():
flatpages = models.FlatPage.objects.all()
for f in flatpages:
roan.purge(f.url).on_save(models.FlatPage)
palestras = pmodels.Palestra.objects.all()
for p in palestras:
roan.purge(p.get_absolute_url_and_link_title()['url']).on_save(pmodels.Palestra)
roan.purge(p.get_absolute_url_and_link_title()['url']).on_delete(pmodels.Palestra)
roan.purge(p.get_absolute_url_and_link_title()['url']).on_save(pmodels.Palestrante)
roan.purge(p.get_absolute_url_and_link_title()['url']).on_delete(pmodels.Palestrante)
| Purge da página de palestra quando salva palestrante | Purge da página de palestra quando salva palestrante
| Python | bsd-2-clause | devincachu/devincachu-2013,devincachu/devincachu-2013,devincachu/devincachu-2014,devincachu/devincachu-2014,devincachu/devincachu-2014,devincachu/devincachu-2013,devincachu/devincachu-2013 | import roan
from django.contrib.flatpages import models
from palestras import models as pmodels
def connect():
flatpages = models.FlatPage.objects.all()
for f in flatpages:
roan.purge(f.url).on_save(models.FlatPage)
palestras = pmodels.Palestra.objects.all()
for p in palestras:
roan.purge(p.get_absolute_url_and_link_title()['url']).on_save(pmodels.Palestra)
roan.purge(p.get_absolute_url_and_link_title()['url']).on_delete(pmodels.Palestra)
+ roan.purge(p.get_absolute_url_and_link_title()['url']).on_save(pmodels.Palestrante)
+ roan.purge(p.get_absolute_url_and_link_title()['url']).on_delete(pmodels.Palestrante)
| Purge da página de palestra quando salva palestrante | ## Code Before:
import roan
from django.contrib.flatpages import models
from palestras import models as pmodels
def connect():
flatpages = models.FlatPage.objects.all()
for f in flatpages:
roan.purge(f.url).on_save(models.FlatPage)
palestras = pmodels.Palestra.objects.all()
for p in palestras:
roan.purge(p.get_absolute_url_and_link_title()['url']).on_save(pmodels.Palestra)
roan.purge(p.get_absolute_url_and_link_title()['url']).on_delete(pmodels.Palestra)
## Instruction:
Purge da página de palestra quando salva palestrante
## Code After:
import roan
from django.contrib.flatpages import models
from palestras import models as pmodels
def connect():
flatpages = models.FlatPage.objects.all()
for f in flatpages:
roan.purge(f.url).on_save(models.FlatPage)
palestras = pmodels.Palestra.objects.all()
for p in palestras:
roan.purge(p.get_absolute_url_and_link_title()['url']).on_save(pmodels.Palestra)
roan.purge(p.get_absolute_url_and_link_title()['url']).on_delete(pmodels.Palestra)
roan.purge(p.get_absolute_url_and_link_title()['url']).on_save(pmodels.Palestrante)
roan.purge(p.get_absolute_url_and_link_title()['url']).on_delete(pmodels.Palestrante)
| ...
roan.purge(p.get_absolute_url_and_link_title()['url']).on_delete(pmodels.Palestra)
roan.purge(p.get_absolute_url_and_link_title()['url']).on_save(pmodels.Palestrante)
roan.purge(p.get_absolute_url_and_link_title()['url']).on_delete(pmodels.Palestrante)
... |
7264db6b160d27f5b9eeb5571acad254f427ab7e | skan/__init__.py | skan/__init__.py | from .csr import skeleton_to_csgraph, branch_statistics, summarise
__version__ = '0.8.0-dev'
__all__ = ['skeleton_to_csgraph',
'branch_statistics',
'summarise']
| from .csr import skeleton_to_csgraph, branch_statistics, summarise, Skeleton
__version__ = '0.8.0-dev'
__all__ = ['skeleton_to_csgraph',
'branch_statistics',
'summarise']
| Add Skeleton class to package namespace | Add Skeleton class to package namespace
| Python | bsd-3-clause | jni/skan | - from .csr import skeleton_to_csgraph, branch_statistics, summarise
+ from .csr import skeleton_to_csgraph, branch_statistics, summarise, Skeleton
__version__ = '0.8.0-dev'
__all__ = ['skeleton_to_csgraph',
'branch_statistics',
'summarise']
| Add Skeleton class to package namespace | ## Code Before:
from .csr import skeleton_to_csgraph, branch_statistics, summarise
__version__ = '0.8.0-dev'
__all__ = ['skeleton_to_csgraph',
'branch_statistics',
'summarise']
## Instruction:
Add Skeleton class to package namespace
## Code After:
from .csr import skeleton_to_csgraph, branch_statistics, summarise, Skeleton
__version__ = '0.8.0-dev'
__all__ = ['skeleton_to_csgraph',
'branch_statistics',
'summarise']
| // ... existing code ...
from .csr import skeleton_to_csgraph, branch_statistics, summarise, Skeleton
// ... rest of the code ... |
f2012869d3e16f0a610e18021e6ec8967eddf635 | tests/sqltypes_test.py | tests/sqltypes_test.py | import enum
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer
from cliche.sqltypes import EnumType
from cliche.orm import Base
class Color(enum.Enum):
red = 1
green = 2
blue = 3
class ColorTable(Base):
__tablename__ = 'color_table'
id = Column(Integer, primary_key=True)
test_col = Column(EnumType(Color))
def test_enum_type(fx_session):
red_obj = ColorTable(test_col=Color.red)
green_obj = ColorTable(test_col=Color.green)
blue_obj = ColorTable(test_col=Color.blue)
fx_session.add(red_obj)
fx_session.add(green_obj)
fx_session.add(blue_obj)
fx_session.flush()
result_obj = fx_session.query(ColorTable) \
.filter(ColorTable.test_col == Color.green) \
.one()
assert green_obj is result_obj
| import enum
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer
from cliche.sqltypes import EnumType
from cliche.orm import Base
class Color(enum.Enum):
red = 1
green = 2
blue = 3
class ColorTable(Base):
__tablename__ = 'color_table'
id = Column(Integer, primary_key=True)
color = Column(EnumType(Color, name='color'))
def test_enum_type(fx_session):
red_obj = ColorTable(color=Color.red)
green_obj = ColorTable(color=Color.green)
blue_obj = ColorTable(color=Color.blue)
fx_session.add(red_obj)
fx_session.add(green_obj)
fx_session.add(blue_obj)
fx_session.flush()
result_obj = fx_session.query(ColorTable) \
.filter(ColorTable.color == Color.green) \
.one()
assert green_obj is result_obj
| Add name to EnumType in test since pgsql needs it. | Add name to EnumType in test since pgsql needs it.
| Python | mit | item4/cliche,clicheio/cliche,item4/cliche,clicheio/cliche,clicheio/cliche | import enum
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer
from cliche.sqltypes import EnumType
from cliche.orm import Base
class Color(enum.Enum):
red = 1
green = 2
blue = 3
class ColorTable(Base):
__tablename__ = 'color_table'
id = Column(Integer, primary_key=True)
- test_col = Column(EnumType(Color))
+ color = Column(EnumType(Color, name='color'))
def test_enum_type(fx_session):
- red_obj = ColorTable(test_col=Color.red)
+ red_obj = ColorTable(color=Color.red)
- green_obj = ColorTable(test_col=Color.green)
+ green_obj = ColorTable(color=Color.green)
- blue_obj = ColorTable(test_col=Color.blue)
+ blue_obj = ColorTable(color=Color.blue)
fx_session.add(red_obj)
fx_session.add(green_obj)
fx_session.add(blue_obj)
fx_session.flush()
result_obj = fx_session.query(ColorTable) \
- .filter(ColorTable.test_col == Color.green) \
+ .filter(ColorTable.color == Color.green) \
.one()
assert green_obj is result_obj
| Add name to EnumType in test since pgsql needs it. | ## Code Before:
import enum
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer
from cliche.sqltypes import EnumType
from cliche.orm import Base
class Color(enum.Enum):
red = 1
green = 2
blue = 3
class ColorTable(Base):
__tablename__ = 'color_table'
id = Column(Integer, primary_key=True)
test_col = Column(EnumType(Color))
def test_enum_type(fx_session):
red_obj = ColorTable(test_col=Color.red)
green_obj = ColorTable(test_col=Color.green)
blue_obj = ColorTable(test_col=Color.blue)
fx_session.add(red_obj)
fx_session.add(green_obj)
fx_session.add(blue_obj)
fx_session.flush()
result_obj = fx_session.query(ColorTable) \
.filter(ColorTable.test_col == Color.green) \
.one()
assert green_obj is result_obj
## Instruction:
Add name to EnumType in test since pgsql needs it.
## Code After:
import enum
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer
from cliche.sqltypes import EnumType
from cliche.orm import Base
class Color(enum.Enum):
red = 1
green = 2
blue = 3
class ColorTable(Base):
__tablename__ = 'color_table'
id = Column(Integer, primary_key=True)
color = Column(EnumType(Color, name='color'))
def test_enum_type(fx_session):
red_obj = ColorTable(color=Color.red)
green_obj = ColorTable(color=Color.green)
blue_obj = ColorTable(color=Color.blue)
fx_session.add(red_obj)
fx_session.add(green_obj)
fx_session.add(blue_obj)
fx_session.flush()
result_obj = fx_session.query(ColorTable) \
.filter(ColorTable.color == Color.green) \
.one()
assert green_obj is result_obj
| // ... existing code ...
id = Column(Integer, primary_key=True)
color = Column(EnumType(Color, name='color'))
// ... modified code ...
def test_enum_type(fx_session):
red_obj = ColorTable(color=Color.red)
green_obj = ColorTable(color=Color.green)
blue_obj = ColorTable(color=Color.blue)
fx_session.add(red_obj)
...
result_obj = fx_session.query(ColorTable) \
.filter(ColorTable.color == Color.green) \
.one()
// ... rest of the code ... |
3aeab31830469bea9d470fc13d1906b7a755d6d3 | tests/pytasa_tests.py | tests/pytasa_tests.py | from nose.tools import *
import pytasa
def test_basic():
print "nothing to test"
| from __future__ import print_function
from nose.tools import *
import pytasa
def test_basic():
print("nothing to test")
| Print needs to be python 3 and python 2 compatible | Print needs to be python 3 and python 2 compatible
| Python | mit | alanfbaird/PyTASA | + from __future__ import print_function
from nose.tools import *
import pytasa
def test_basic():
- print "nothing to test"
+ print("nothing to test")
| Print needs to be python 3 and python 2 compatible | ## Code Before:
from nose.tools import *
import pytasa
def test_basic():
print "nothing to test"
## Instruction:
Print needs to be python 3 and python 2 compatible
## Code After:
from __future__ import print_function
from nose.tools import *
import pytasa
def test_basic():
print("nothing to test")
| // ... existing code ...
from __future__ import print_function
from nose.tools import *
// ... modified code ...
def test_basic():
print("nothing to test")
// ... rest of the code ... |
f4d703fb38c8d4efbff709a6e3c7478b7cf96db2 | code/conditional_switch_as_else_if.py | code/conditional_switch_as_else_if.py | score = 76
if score < 60:
grade = 'F'
elif score < 70:
grade = 'D'
elif score < 80:
grade = 'C'
elif score < 90:
grade = 'B'
else:
grade = 'A'
print(grade)
| score = 76
grades = [
(60, 'F'),
(70, 'D'),
(80, 'C'),
(90, 'B'),
]
print(next((g for x, g in grades if score < x), 'A'))
| Replace swith statement with a mapping | Replace swith statement with a mapping
Official Python documentation explains [1], that switch statement can be
replaced by `if .. elif .. else` or by a mapping.
In first example with varying condtitions `if .. elif .. else` was used, and in
this example a mapping is much better fitted way of doing a switch statement
logic.
Since this is an official and documented way of doing switch statement logic in
Python, am adding it here.
[1] https://docs.python.org/3/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python
| Python | mit | evmorov/lang-compare,evmorov/lang-compare,evmorov/lang-compare,Evmorov/ruby-coffeescript,Evmorov/ruby-coffeescript,Evmorov/ruby-coffeescript,evmorov/lang-compare,evmorov/lang-compare,evmorov/lang-compare | score = 76
+ grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+ ]
+ print(next((g for x, g in grades if score < x), 'A'))
- if score < 60:
- grade = 'F'
- elif score < 70:
- grade = 'D'
- elif score < 80:
- grade = 'C'
- elif score < 90:
- grade = 'B'
- else:
- grade = 'A'
- print(grade)
| Replace swith statement with a mapping | ## Code Before:
score = 76
if score < 60:
grade = 'F'
elif score < 70:
grade = 'D'
elif score < 80:
grade = 'C'
elif score < 90:
grade = 'B'
else:
grade = 'A'
print(grade)
## Instruction:
Replace swith statement with a mapping
## Code After:
score = 76
grades = [
(60, 'F'),
(70, 'D'),
(80, 'C'),
(90, 'B'),
]
print(next((g for x, g in grades if score < x), 'A'))
| # ... existing code ...
score = 76
grades = [
(60, 'F'),
(70, 'D'),
(80, 'C'),
(90, 'B'),
]
print(next((g for x, g in grades if score < x), 'A'))
# ... rest of the code ... |
bbfb09205974efa969fc636b6e1079a84dad3619 | mcstatus/application.py | mcstatus/application.py | from flask import Flask
from minecraft_query import MinecraftQuery
app = Flask(__name__)
@app.route('/mcstatus')
def returnStatus():
try:
query = MinecraftQuery("mc.voltaire.sh", 25565, 10, 3)
basicQuery = query.get_status()
fullQuery = query.get_rules()
except socket.error as e:
if not options.quiet:
return "Server is down or unreachable:\n" + e.message
if not options.quiet:
numOnline = 'The server has %d players filling %d total slots. There are %d free slots.' % (basicQuery['numplayers'], basicQuery['maxplayers'], basicQuery['maxplayers'] - basic_status['numplayers'])
playersOnline = 'Online now: %s' % (fullQuery['players'])
return numOnline + "\n" + playersOnline
return "ermahgerd"
if __name__ == '__main__':
app.run() | from flask import Flask
from minecraft_query import MinecraftQuery
app = Flask(__name__)
@app.route('/mcstatus')
def returnStatus():
query = MinecraftQuery("142.54.162.42", 25565)
basic_status = query.get_status()
all_status = query.get_rules()
server_info = 'The server has %d / %d players.' % (basic_status['numplayers'], basic_status['maxplayers'])
status_info = 'Online now: %s' % (all_status['players'])
return "<pre>" + server_info + "\n" + status_info + "</pre>"
if __name__ == '__main__':
app.run()
| Revert "check for connection failure" | Revert "check for connection failure"
This reverts commit cf4bd49e150f5542a5a7abba908ca81ebe1b9e75.
| Python | bsd-3-clause | voltaire/minecraft-site-old,voltaire/minecraft-site-old | from flask import Flask
from minecraft_query import MinecraftQuery
app = Flask(__name__)
@app.route('/mcstatus')
-
def returnStatus():
+ query = MinecraftQuery("142.54.162.42", 25565)
-
- try:
- query = MinecraftQuery("mc.voltaire.sh", 25565, 10, 3)
- basicQuery = query.get_status()
+ basic_status = query.get_status()
- fullQuery = query.get_rules()
+ all_status = query.get_rules()
+ server_info = 'The server has %d / %d players.' % (basic_status['numplayers'], basic_status['maxplayers'])
+ status_info = 'Online now: %s' % (all_status['players'])
+ return "<pre>" + server_info + "\n" + status_info + "</pre>"
-
- except socket.error as e:
- if not options.quiet:
- return "Server is down or unreachable:\n" + e.message
-
- if not options.quiet:
- numOnline = 'The server has %d players filling %d total slots. There are %d free slots.' % (basicQuery['numplayers'], basicQuery['maxplayers'], basicQuery['maxplayers'] - basic_status['numplayers'])
- playersOnline = 'Online now: %s' % (fullQuery['players'])
- return numOnline + "\n" + playersOnline
-
- return "ermahgerd"
if __name__ == '__main__':
app.run()
+ | Revert "check for connection failure" | ## Code Before:
from flask import Flask
from minecraft_query import MinecraftQuery
app = Flask(__name__)
@app.route('/mcstatus')
def returnStatus():
try:
query = MinecraftQuery("mc.voltaire.sh", 25565, 10, 3)
basicQuery = query.get_status()
fullQuery = query.get_rules()
except socket.error as e:
if not options.quiet:
return "Server is down or unreachable:\n" + e.message
if not options.quiet:
numOnline = 'The server has %d players filling %d total slots. There are %d free slots.' % (basicQuery['numplayers'], basicQuery['maxplayers'], basicQuery['maxplayers'] - basic_status['numplayers'])
playersOnline = 'Online now: %s' % (fullQuery['players'])
return numOnline + "\n" + playersOnline
return "ermahgerd"
if __name__ == '__main__':
app.run()
## Instruction:
Revert "check for connection failure"
## Code After:
from flask import Flask
from minecraft_query import MinecraftQuery
app = Flask(__name__)
@app.route('/mcstatus')
def returnStatus():
query = MinecraftQuery("142.54.162.42", 25565)
basic_status = query.get_status()
all_status = query.get_rules()
server_info = 'The server has %d / %d players.' % (basic_status['numplayers'], basic_status['maxplayers'])
status_info = 'Online now: %s' % (all_status['players'])
return "<pre>" + server_info + "\n" + status_info + "</pre>"
if __name__ == '__main__':
app.run()
| ...
@app.route('/mcstatus')
def returnStatus():
query = MinecraftQuery("142.54.162.42", 25565)
basic_status = query.get_status()
all_status = query.get_rules()
server_info = 'The server has %d / %d players.' % (basic_status['numplayers'], basic_status['maxplayers'])
status_info = 'Online now: %s' % (all_status['players'])
return "<pre>" + server_info + "\n" + status_info + "</pre>"
... |
beeae2daf35da275d5f9e1ad01516c917319bf00 | gapipy/resources/geo/state.py | gapipy/resources/geo/state.py | from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [('country', 'Country')]
@enforce_string_type
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, self.name)
| from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [
('country', 'Country'),
('place', 'Place'),
]
@enforce_string_type
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, self.name)
| Add Place reference to State model | Add Place reference to State model
| Python | mit | gadventures/gapipy | from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
- _resource_fields = [('country', 'Country')]
+ _resource_fields = [
+ ('country', 'Country'),
+ ('place', 'Place'),
+ ]
@enforce_string_type
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, self.name)
| Add Place reference to State model | ## Code Before:
from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [('country', 'Country')]
@enforce_string_type
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, self.name)
## Instruction:
Add Place reference to State model
## Code After:
from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [
('country', 'Country'),
('place', 'Place'),
]
@enforce_string_type
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, self.name)
| // ... existing code ...
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [
('country', 'Country'),
('place', 'Place'),
]
// ... rest of the code ... |
7bfa9d24f7af811746bbb0336b5e75a592cff186 | aws_eis/lib/checks.py | aws_eis/lib/checks.py | import json
import sys
import requests
def py_version():
if sys.version_info < (3, 0, 0):
print(sys.version)
print('You must use Python 3.x to run this application.')
sys.exit(1)
def get_version(endpoint):
r = requests.get('https://{}'.format(endpoint))
es_version = json.loads(r.text)['version']['number']
return es_version
def test_con(endpoint):
r = requests.get('https://{}'.format(endpoint))
es_version = get_version(endpoint)
if r.status_code == 200:
print('ESVersion: {}'.format(es_version))
print('Connection: OK')
print('Status: {}\n'.format(r.status_code))
else:
print(json.loads(msg)['Message'])
print('Status: {}'.format(status_code))
sys.exit(1)
| import json
import sys
import requests
def py_version():
if sys.version_info < (3, 0, 0):
print(sys.version)
print('You must use Python 3.x to run this application.')
sys.exit(1)
def get_version(endpoint):
r = requests.get('https://{}'.format(endpoint))
es_version = json.loads(r.text)['version']['number']
return es_version
def test_con(endpoint):
r = requests.get('https://{}'.format(endpoint))
try:
es_version = get_version(endpoint)
except KeyError:
print('Status: {}'.format(r.status_code))
sys.exit(1)
else:
if r.status_code == 200:
print('ESVersion: {}'.format(es_version))
print('Connection: OK')
print('Status: {}\n'.format(r.status_code))
| Fix KeyError: 'version' due to 403 Forbidden error | Fix KeyError: 'version' due to 403 Forbidden error
| Python | mit | jpdoria/aws_eis | import json
import sys
import requests
def py_version():
if sys.version_info < (3, 0, 0):
print(sys.version)
print('You must use Python 3.x to run this application.')
sys.exit(1)
def get_version(endpoint):
r = requests.get('https://{}'.format(endpoint))
es_version = json.loads(r.text)['version']['number']
return es_version
def test_con(endpoint):
r = requests.get('https://{}'.format(endpoint))
- es_version = get_version(endpoint)
- if r.status_code == 200:
- print('ESVersion: {}'.format(es_version))
- print('Connection: OK')
+ try:
+ es_version = get_version(endpoint)
+ except KeyError:
- print('Status: {}\n'.format(r.status_code))
+ print('Status: {}'.format(r.status_code))
+ sys.exit(1)
else:
- print(json.loads(msg)['Message'])
+ if r.status_code == 200:
+ print('ESVersion: {}'.format(es_version))
+ print('Connection: OK')
- print('Status: {}'.format(status_code))
+ print('Status: {}\n'.format(r.status_code))
- sys.exit(1)
| Fix KeyError: 'version' due to 403 Forbidden error | ## Code Before:
import json
import sys
import requests
def py_version():
if sys.version_info < (3, 0, 0):
print(sys.version)
print('You must use Python 3.x to run this application.')
sys.exit(1)
def get_version(endpoint):
r = requests.get('https://{}'.format(endpoint))
es_version = json.loads(r.text)['version']['number']
return es_version
def test_con(endpoint):
r = requests.get('https://{}'.format(endpoint))
es_version = get_version(endpoint)
if r.status_code == 200:
print('ESVersion: {}'.format(es_version))
print('Connection: OK')
print('Status: {}\n'.format(r.status_code))
else:
print(json.loads(msg)['Message'])
print('Status: {}'.format(status_code))
sys.exit(1)
## Instruction:
Fix KeyError: 'version' due to 403 Forbidden error
## Code After:
import json
import sys
import requests
def py_version():
if sys.version_info < (3, 0, 0):
print(sys.version)
print('You must use Python 3.x to run this application.')
sys.exit(1)
def get_version(endpoint):
r = requests.get('https://{}'.format(endpoint))
es_version = json.loads(r.text)['version']['number']
return es_version
def test_con(endpoint):
r = requests.get('https://{}'.format(endpoint))
try:
es_version = get_version(endpoint)
except KeyError:
print('Status: {}'.format(r.status_code))
sys.exit(1)
else:
if r.status_code == 200:
print('ESVersion: {}'.format(es_version))
print('Connection: OK')
print('Status: {}\n'.format(r.status_code))
| ...
r = requests.get('https://{}'.format(endpoint))
try:
es_version = get_version(endpoint)
except KeyError:
print('Status: {}'.format(r.status_code))
sys.exit(1)
else:
if r.status_code == 200:
print('ESVersion: {}'.format(es_version))
print('Connection: OK')
print('Status: {}\n'.format(r.status_code))
... |
a34c594a13a79a864d1b747d84a0074e7711dd42 | testanalyzer/pythonanalyzer.py | testanalyzer/pythonanalyzer.py | import re
from fileanalyzer import FileAnalyzer
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("class [a-zA-Z0-9_]+\(?[a-zA-Z0-9_, ]*\)?:", content))
def get_function_count(self, content):
return len(
re.findall("def [a-zA-Z0-9_]+\([a-zA-Z0-9_, ]*\):", content))
| import re
from fileanalyzer import FileAnalyzer
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:", content))
def get_function_count(self, content):
return len(
re.findall("def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:", content))
| Update regex to allow spaces | Update regex to allow spaces
| Python | mpl-2.0 | CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer | import re
from fileanalyzer import FileAnalyzer
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
- re.findall("class [a-zA-Z0-9_]+\(?[a-zA-Z0-9_, ]*\)?:", content))
+ re.findall("class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:", content))
def get_function_count(self, content):
return len(
- re.findall("def [a-zA-Z0-9_]+\([a-zA-Z0-9_, ]*\):", content))
+ re.findall("def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:", content))
| Update regex to allow spaces | ## Code Before:
import re
from fileanalyzer import FileAnalyzer
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("class [a-zA-Z0-9_]+\(?[a-zA-Z0-9_, ]*\)?:", content))
def get_function_count(self, content):
return len(
re.findall("def [a-zA-Z0-9_]+\([a-zA-Z0-9_, ]*\):", content))
## Instruction:
Update regex to allow spaces
## Code After:
import re
from fileanalyzer import FileAnalyzer
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:", content))
def get_function_count(self, content):
return len(
re.findall("def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:", content))
| # ... existing code ...
return len(
re.findall("class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:", content))
# ... modified code ...
return len(
re.findall("def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:", content))
# ... rest of the code ... |
d4e5af537be36bd50405e60fdb46f31b88537916 | src/commoner_i/views.py | src/commoner_i/views.py | from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
| from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.free:
# return a 404 for FREE profiles
raise Http404
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
| Raise a 404 when for FREE profile badge requests | Raise a 404 when for FREE profile badge requests
| Python | agpl-3.0 | cc-archive/commoner,cc-archive/commoner | from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
- from django.http import HttpResponse
+ from django.http import HttpResponse, Http404
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
+ if profile.free:
+ # return a 404 for FREE profiles
+ raise Http404
+
if profile.active:
- # serve the active badge
+ # serve the active badge
- filename = 'images/badge%s/active.png' % size
+ filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
| Raise a 404 when for FREE profile badge requests | ## Code Before:
from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
## Instruction:
Raise a 404 when for FREE profile badge requests
## Code After:
from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.free:
# return a 404 for FREE profiles
raise Http404
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
| // ... existing code ...
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
// ... modified code ...
if profile.free:
# return a 404 for FREE profiles
raise Http404
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
// ... rest of the code ... |
fb58ecee7e3e71f0dbb202f7284c3af20ccbcdaa | shared/logger.py | shared/logger.py | import os
import logging
from datetime import datetime
log_name = '{}/../logs/{}.log'.format(os.path.dirname(os.path.abspath(__file__)),
datetime.now().strftime('%Y.%m.%d.%H.%M.%S'))
logger = logging.getLogger('main')
logger.setLevel(logging.INFO)
logging.basicConfig(format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p', filename=log_name)
def info(component, message):
if component:
logger.info('[{}] {}'.format(component, message))
else:
logger.info(message)
def error(component, message):
if component:
logger.error('[{}] {}'.format(component, message))
else:
logger.error(message)
| import os
import logging
from datetime import datetime
log_name = '{}/../logs/{}.log'.format(os.path.dirname(os.path.abspath(__file__)),
datetime.now().strftime('%Y.%m.%d.%H.%M.%S'))
logger = logging.getLogger('main')
logger.setLevel(logging.INFO)
console = logging.StreamHandler()
logger.addHandler(console)
logging.basicConfig(format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p', filename=log_name)
def info(component, message):
if component:
logger.info('[{}] {}'.format(component, message))
else:
logger.info(message)
def error(component, message):
if component:
logger.error('[{}] {}'.format(component, message))
else:
logger.error(message)
| Allow logging to console as well as disk | Allow logging to console as well as disk
| Python | mit | Mo-Talha/Nomad,Mo-Talha/Nomad,Mo-Talha/Nomad,Mo-Talha/Nomad | import os
import logging
from datetime import datetime
log_name = '{}/../logs/{}.log'.format(os.path.dirname(os.path.abspath(__file__)),
datetime.now().strftime('%Y.%m.%d.%H.%M.%S'))
logger = logging.getLogger('main')
logger.setLevel(logging.INFO)
+
+ console = logging.StreamHandler()
+ logger.addHandler(console)
logging.basicConfig(format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p', filename=log_name)
def info(component, message):
if component:
logger.info('[{}] {}'.format(component, message))
else:
logger.info(message)
def error(component, message):
if component:
logger.error('[{}] {}'.format(component, message))
else:
logger.error(message)
| Allow logging to console as well as disk | ## Code Before:
import os
import logging
from datetime import datetime
log_name = '{}/../logs/{}.log'.format(os.path.dirname(os.path.abspath(__file__)),
datetime.now().strftime('%Y.%m.%d.%H.%M.%S'))
logger = logging.getLogger('main')
logger.setLevel(logging.INFO)
logging.basicConfig(format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p', filename=log_name)
def info(component, message):
if component:
logger.info('[{}] {}'.format(component, message))
else:
logger.info(message)
def error(component, message):
if component:
logger.error('[{}] {}'.format(component, message))
else:
logger.error(message)
## Instruction:
Allow logging to console as well as disk
## Code After:
import os
import logging
from datetime import datetime
log_name = '{}/../logs/{}.log'.format(os.path.dirname(os.path.abspath(__file__)),
datetime.now().strftime('%Y.%m.%d.%H.%M.%S'))
logger = logging.getLogger('main')
logger.setLevel(logging.INFO)
console = logging.StreamHandler()
logger.addHandler(console)
logging.basicConfig(format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p', filename=log_name)
def info(component, message):
if component:
logger.info('[{}] {}'.format(component, message))
else:
logger.info(message)
def error(component, message):
if component:
logger.error('[{}] {}'.format(component, message))
else:
logger.error(message)
| ...
logger.setLevel(logging.INFO)
console = logging.StreamHandler()
logger.addHandler(console)
... |
701402c4a51474b244ff28dd2d5c9a0731440308 | mozcal/events/api.py | mozcal/events/api.py | from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
| from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
filtering = {
"title": ('startswith',),
} | Allow filtering of event by title | Allow filtering of event by title
| Python | bsd-3-clause | ppapadeas/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents,ppapadeas/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents | from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
-
+ filtering = {
+ "title": ('startswith',),
+ } | Allow filtering of event by title | ## Code Before:
from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
## Instruction:
Allow filtering of event by title
## Code After:
from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
filtering = {
"title": ('startswith',),
} | # ... existing code ...
queryset = Event.objects.all()
filtering = {
"title": ('startswith',),
}
# ... rest of the code ... |
ea3deb560aaddab4d66a84e840e10854cfad581d | nass/__init__.py | nass/__init__.py |
__author__ = 'Nick Frost'
__version__ = '0.1.1'
__license__ = 'MIT'
from .api import NassApi
|
from .api import NassApi
__author__ = 'Nick Frost'
__version__ = '0.1.1'
__license__ = 'MIT'
| Make package-level import at the top (pep8) | Make package-level import at the top (pep8)
| Python | mit | nickfrostatx/nass | +
+ from .api import NassApi
__author__ = 'Nick Frost'
__version__ = '0.1.1'
__license__ = 'MIT'
- from .api import NassApi
- | Make package-level import at the top (pep8) | ## Code Before:
__author__ = 'Nick Frost'
__version__ = '0.1.1'
__license__ = 'MIT'
from .api import NassApi
## Instruction:
Make package-level import at the top (pep8)
## Code After:
from .api import NassApi
__author__ = 'Nick Frost'
__version__ = '0.1.1'
__license__ = 'MIT'
| ...
from .api import NassApi
...
__license__ = 'MIT'
... |
bd1a244aa3d9126a12365611372e6449e47e5693 | pelicanconf.py | pelicanconf.py | from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
| from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
| Add links to Android/iOS apps | Add links to Android/iOS apps
| Python | mit | paulgreg/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source,Mappy/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source | from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
+ ('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
+ ('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
| Add links to Android/iOS apps | ## Code Before:
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
## Instruction:
Add links to Android/iOS apps
## Code After:
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
| // ... existing code ...
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
// ... rest of the code ... |
842cfc631949831053f4310f586e7b2a83ff7cde | notifications_utils/timezones.py | notifications_utils/timezones.py | from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string or a naive datetime
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
| from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string, naive UTC datetime or an aware UTC datetime
Returns an aware London datetime, essentially the time you'd see on your clock
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
"""
Takes a naive UTC datetime and returns a naive London datetime
"""
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
"""
Takes a naive London datetime and returns a naive UTC datetime
"""
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
| Add descriptions to timezone functions | Add descriptions to timezone functions
These are quite complex things and benefit from having better descriptions.
Note, we weren't quite happy with the names of the functions.
`aware_gmt_datetime` should really be `aware_london_datetime` and
the other two functions could have more verbose names (mentioning
that they convert from naive to naive) but we decided not to change
these as will involve lots of changes around the codebase.
| Python | mit | alphagov/notifications-utils | from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
- Date can either be a string or a naive datetime
+ Date can either be a string, naive UTC datetime or an aware UTC datetime
+ Returns an aware London datetime, essentially the time you'd see on your clock
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
+ """
+ Takes a naive UTC datetime and returns a naive London datetime
+ """
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
+ """
+ Takes a naive London datetime and returns a naive UTC datetime
+ """
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
| Add descriptions to timezone functions | ## Code Before:
from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string or a naive datetime
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
## Instruction:
Add descriptions to timezone functions
## Code After:
from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string, naive UTC datetime or an aware UTC datetime
Returns an aware London datetime, essentially the time you'd see on your clock
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
"""
Takes a naive UTC datetime and returns a naive London datetime
"""
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
"""
Takes a naive London datetime and returns a naive UTC datetime
"""
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
| // ... existing code ...
"""
Date can either be a string, naive UTC datetime or an aware UTC datetime
Returns an aware London datetime, essentially the time you'd see on your clock
"""
// ... modified code ...
def convert_utc_to_bst(utc_dt):
"""
Takes a naive UTC datetime and returns a naive London datetime
"""
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
...
def convert_bst_to_utc(date):
"""
Takes a naive London datetime and returns a naive UTC datetime
"""
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
// ... rest of the code ... |
98b0eb3d492cb816db7ffa7ad062dde36a1feadf | tests/unit/test_gettext.py | tests/unit/test_gettext.py |
import logging
import unittest
from openstack.common.gettextutils import _
LOG = logging.getLogger(__name__)
class GettextTest(unittest.TestCase):
def test_gettext_does_not_blow_up(self):
LOG.info(_('test'))
|
import logging
import testtools
from openstack.common.gettextutils import _
LOG = logging.getLogger(__name__)
class GettextTest(testtools.TestCase):
def test_gettext_does_not_blow_up(self):
LOG.info(_('test'))
| Use testtools as test base class. | Use testtools as test base class.
On the path to testr migration, we need to replace the unittest base classes
with testtools.
Replace tearDown with addCleanup, addCleanup is more resilient than tearDown.
The fixtures library has excellent support for managing and cleaning
tempfiles. Use it.
Replace skip_ with testtools.skipTest
Part of blueprint grizzly-testtools.
Change-Id: I45e11bbb1ff9b31f3278d3b016737dcb7850cd98
| Python | apache-2.0 | varunarya10/oslo.i18n,openstack/oslo.i18n |
import logging
- import unittest
+ import testtools
from openstack.common.gettextutils import _
LOG = logging.getLogger(__name__)
- class GettextTest(unittest.TestCase):
+ class GettextTest(testtools.TestCase):
def test_gettext_does_not_blow_up(self):
LOG.info(_('test'))
| Use testtools as test base class. | ## Code Before:
import logging
import unittest
from openstack.common.gettextutils import _
LOG = logging.getLogger(__name__)
class GettextTest(unittest.TestCase):
def test_gettext_does_not_blow_up(self):
LOG.info(_('test'))
## Instruction:
Use testtools as test base class.
## Code After:
import logging
import testtools
from openstack.common.gettextutils import _
LOG = logging.getLogger(__name__)
class GettextTest(testtools.TestCase):
def test_gettext_does_not_blow_up(self):
LOG.info(_('test'))
| // ... existing code ...
import logging
import testtools
// ... modified code ...
class GettextTest(testtools.TestCase):
// ... rest of the code ... |
b0029cffae96e25611d7387e699774de4d9682d3 | corehq/apps/es/tests/utils.py | corehq/apps/es/tests/utils.py | import json
from nose.plugins.attrib import attr
class ElasticTestMixin(object):
def checkQuery(self, query, json_output, is_raw_query=False):
if is_raw_query:
raw_query = query
else:
raw_query = query.raw_query
msg = "Expected Query:\n{}\nGenerated Query:\n{}".format(
json.dumps(json_output, indent=4),
json.dumps(raw_query, indent=4),
)
# NOTE: This method thinks [a, b, c] != [b, c, a]
self.assertEqual(raw_query, json_output, msg=msg)
def es_test(test):
"""Decorator for tagging ElasticSearch tests
:param test: A test class, method, or function.
"""
return attr(es_test=True)(test)
| import json
from nose.plugins.attrib import attr
from nose.tools import nottest
class ElasticTestMixin(object):
def checkQuery(self, query, json_output, is_raw_query=False):
if is_raw_query:
raw_query = query
else:
raw_query = query.raw_query
msg = "Expected Query:\n{}\nGenerated Query:\n{}".format(
json.dumps(json_output, indent=4),
json.dumps(raw_query, indent=4),
)
# NOTE: This method thinks [a, b, c] != [b, c, a]
self.assertEqual(raw_query, json_output, msg=msg)
@nottest
def es_test(test):
"""Decorator for tagging ElasticSearch tests
:param test: A test class, method, or function.
"""
return attr(es_test=True)(test)
| Mark es_test decorator as nottest | Mark es_test decorator as nottest
Second try... | Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | import json
from nose.plugins.attrib import attr
+ from nose.tools import nottest
class ElasticTestMixin(object):
def checkQuery(self, query, json_output, is_raw_query=False):
if is_raw_query:
raw_query = query
else:
raw_query = query.raw_query
msg = "Expected Query:\n{}\nGenerated Query:\n{}".format(
json.dumps(json_output, indent=4),
json.dumps(raw_query, indent=4),
)
# NOTE: This method thinks [a, b, c] != [b, c, a]
self.assertEqual(raw_query, json_output, msg=msg)
+ @nottest
def es_test(test):
"""Decorator for tagging ElasticSearch tests
:param test: A test class, method, or function.
"""
return attr(es_test=True)(test)
| Mark es_test decorator as nottest | ## Code Before:
import json
from nose.plugins.attrib import attr
class ElasticTestMixin(object):
def checkQuery(self, query, json_output, is_raw_query=False):
if is_raw_query:
raw_query = query
else:
raw_query = query.raw_query
msg = "Expected Query:\n{}\nGenerated Query:\n{}".format(
json.dumps(json_output, indent=4),
json.dumps(raw_query, indent=4),
)
# NOTE: This method thinks [a, b, c] != [b, c, a]
self.assertEqual(raw_query, json_output, msg=msg)
def es_test(test):
"""Decorator for tagging ElasticSearch tests
:param test: A test class, method, or function.
"""
return attr(es_test=True)(test)
## Instruction:
Mark es_test decorator as nottest
## Code After:
import json
from nose.plugins.attrib import attr
from nose.tools import nottest
class ElasticTestMixin(object):
def checkQuery(self, query, json_output, is_raw_query=False):
if is_raw_query:
raw_query = query
else:
raw_query = query.raw_query
msg = "Expected Query:\n{}\nGenerated Query:\n{}".format(
json.dumps(json_output, indent=4),
json.dumps(raw_query, indent=4),
)
# NOTE: This method thinks [a, b, c] != [b, c, a]
self.assertEqual(raw_query, json_output, msg=msg)
@nottest
def es_test(test):
"""Decorator for tagging ElasticSearch tests
:param test: A test class, method, or function.
"""
return attr(es_test=True)(test)
| // ... existing code ...
from nose.plugins.attrib import attr
from nose.tools import nottest
// ... modified code ...
@nottest
def es_test(test):
// ... rest of the code ... |
10b58658f76c0d51c0ae091788db78de5204a284 | example.py | example.py | import generation
import show
""" Choose the excitation signal which you want to generate and fill in
the parameters xxx_sweep(fstart, fstop, sweep_time, fs),
where:
fstart is the start frequency
fstop is the stop frequency
sweep_time is the total length of sweep
fs is the sampling frequency
Note that the stop frequency must not be greater than half the
sampling frequency (Nyquist-Shannon sampling theorem)
Save the return value in a new variable which is the sweep vector.
"""
# For example
x = generation.log_sweep(1, 1000, 2, 44100)
"""We created a vector which sweeps from 1 Hz to 1000 Hz in 2
seconds at a sampling frequency of 44.1 kHz and save the vector in x.
Now it is possible to figure the sweep vector in both the time and
frequency domain simultaneously, using the 'show' function:
show.sweep(x, sweep_time, fs).
Note that 'sweep_time' and 'fs' have the same values as in
'generation' function. """
# For example
show.sweep(x, 2, 44100)
| import generation
import show
# For example
"""Save the return value in a new variable which is the sweep
vector. """
x = generation.log_sweep(1, 1000, 2, 44100)
"""We created a vector which sweeps from 1 Hz to 1000 Hz in 2
seconds at a sampling frequency of 44.1 kHz.
"""
show.sweep(x, 2, 44100, "tfdomain")
| Make executable and edit some docstrings | Make executable and edit some docstrings
| Python | mit | spatialaudio/sweep,franzpl/sweep | import generation
import show
+ # For example
- """ Choose the excitation signal which you want to generate and fill in
- the parameters xxx_sweep(fstart, fstop, sweep_time, fs),
- where:
- fstart is the start frequency
- fstop is the stop frequency
- sweep_time is the total length of sweep
- fs is the sampling frequency
-
- Note that the stop frequency must not be greater than half the
- sampling frequency (Nyquist-Shannon sampling theorem)
-
- Save the return value in a new variable which is the sweep vector.
+ """Save the return value in a new variable which is the sweep
+ vector. """
- """
- # For example
x = generation.log_sweep(1, 1000, 2, 44100)
"""We created a vector which sweeps from 1 Hz to 1000 Hz in 2
- seconds at a sampling frequency of 44.1 kHz and save the vector in x.
+ seconds at a sampling frequency of 44.1 kHz.
+ """
+ show.sweep(x, 2, 44100, "tfdomain")
- Now it is possible to figure the sweep vector in both the time and
- frequency domain simultaneously, using the 'show' function:
- show.sweep(x, sweep_time, fs).
- Note that 'sweep_time' and 'fs' have the same values as in
- 'generation' function. """
- # For example
-
- show.sweep(x, 2, 44100)
- | Make executable and edit some docstrings | ## Code Before:
import generation
import show
""" Choose the excitation signal which you want to generate and fill in
the parameters xxx_sweep(fstart, fstop, sweep_time, fs),
where:
fstart is the start frequency
fstop is the stop frequency
sweep_time is the total length of sweep
fs is the sampling frequency
Note that the stop frequency must not be greater than half the
sampling frequency (Nyquist-Shannon sampling theorem)
Save the return value in a new variable which is the sweep vector.
"""
# For example
x = generation.log_sweep(1, 1000, 2, 44100)
"""We created a vector which sweeps from 1 Hz to 1000 Hz in 2
seconds at a sampling frequency of 44.1 kHz and save the vector in x.
Now it is possible to figure the sweep vector in both the time and
frequency domain simultaneously, using the 'show' function:
show.sweep(x, sweep_time, fs).
Note that 'sweep_time' and 'fs' have the same values as in
'generation' function. """
# For example
show.sweep(x, 2, 44100)
## Instruction:
Make executable and edit some docstrings
## Code After:
import generation
import show
# For example
"""Save the return value in a new variable which is the sweep
vector. """
x = generation.log_sweep(1, 1000, 2, 44100)
"""We created a vector which sweeps from 1 Hz to 1000 Hz in 2
seconds at a sampling frequency of 44.1 kHz.
"""
show.sweep(x, 2, 44100, "tfdomain")
| // ... existing code ...
# For example
"""Save the return value in a new variable which is the sweep
vector. """
// ... modified code ...
"""We created a vector which sweeps from 1 Hz to 1000 Hz in 2
seconds at a sampling frequency of 44.1 kHz.
"""
show.sweep(x, 2, 44100, "tfdomain")
// ... rest of the code ... |
b3670094a44fc0fb07a91e1dc0ffb1a17001f855 | botcommands/vimtips.py | botcommands/vimtips.py | import requests
from redis_wrap import get_hash
from rq.decorators import job
def vimtips(msg=None):
try:
existing_tips = get_hash('vimtips')
_len = len(existing_tips)
if _len > 0:
_index = randint(0, _len - 1)
_k = existing_tips.keys()[_index]
_v = existing_tips[_k]
tip = {
'Content': _k,
'Comment': _v
}
else:
tip = requests.get('http://vim-tips.com/random_tips/json').json()
existing_tips.update({
tip['Content']: tip['Comment']
})
collect_tip()
except Exception as e:
return u'哦,不小心玩坏了……'
return u'%s\n%s' % (tip['Content'], tip['Comment'], )
@job('default')
def collect_tip():
tip = requests.get('http://vim-tips.com/random_tips/json').json()
get_hash('vimtips').update({
tip['Content']: tip['Comment']
})
| from random import randint
import requests
from redis_wrap import get_hash, SYSTEMS
from rq.decorators import job
def vimtips(msg=None):
try:
existing_tips = get_hash('vimtips')
_len = len(existing_tips)
if _len > 0:
_index = randint(0, _len - 1)
_k = existing_tips.keys()[_index]
_v = existing_tips[_k]
tip = {
'Content': _k,
'Comment': _v
}
else:
tip = requests.get('http://vim-tips.com/random_tips/json').json()
existing_tips.update({
tip['Content']: tip['Comment']
})
collect_tip.delay()
except Exception as e:
return '哦,不小心玩坏了……'
return '%s\n%s' % (tip['Content'], tip['Comment'], )
# Fetch a new tip in RQ queue
@job('default', connection=SYSTEMS['default'], result_ttl=5)
def collect_tip():
tip = requests.get('http://vim-tips.com/random_tips/json').json()
get_hash('vimtips').update({
tip['Content']: tip['Comment']
})
| Fix import and use queue the right way | Fix import and use queue the right way
| Python | bsd-2-clause | JokerQyou/bot | + from random import randint
+
import requests
- from redis_wrap import get_hash
+ from redis_wrap import get_hash, SYSTEMS
from rq.decorators import job
def vimtips(msg=None):
try:
existing_tips = get_hash('vimtips')
_len = len(existing_tips)
if _len > 0:
_index = randint(0, _len - 1)
_k = existing_tips.keys()[_index]
_v = existing_tips[_k]
tip = {
'Content': _k,
'Comment': _v
}
else:
tip = requests.get('http://vim-tips.com/random_tips/json').json()
existing_tips.update({
tip['Content']: tip['Comment']
})
- collect_tip()
+ collect_tip.delay()
except Exception as e:
- return u'哦,不小心玩坏了……'
+ return '哦,不小心玩坏了……'
- return u'%s\n%s' % (tip['Content'], tip['Comment'], )
+ return '%s\n%s' % (tip['Content'], tip['Comment'], )
- @job('default')
+ # Fetch a new tip in RQ queue
+ @job('default', connection=SYSTEMS['default'], result_ttl=5)
def collect_tip():
tip = requests.get('http://vim-tips.com/random_tips/json').json()
get_hash('vimtips').update({
tip['Content']: tip['Comment']
})
| Fix import and use queue the right way | ## Code Before:
import requests
from redis_wrap import get_hash
from rq.decorators import job
def vimtips(msg=None):
try:
existing_tips = get_hash('vimtips')
_len = len(existing_tips)
if _len > 0:
_index = randint(0, _len - 1)
_k = existing_tips.keys()[_index]
_v = existing_tips[_k]
tip = {
'Content': _k,
'Comment': _v
}
else:
tip = requests.get('http://vim-tips.com/random_tips/json').json()
existing_tips.update({
tip['Content']: tip['Comment']
})
collect_tip()
except Exception as e:
return u'哦,不小心玩坏了……'
return u'%s\n%s' % (tip['Content'], tip['Comment'], )
@job('default')
def collect_tip():
tip = requests.get('http://vim-tips.com/random_tips/json').json()
get_hash('vimtips').update({
tip['Content']: tip['Comment']
})
## Instruction:
Fix import and use queue the right way
## Code After:
from random import randint
import requests
from redis_wrap import get_hash, SYSTEMS
from rq.decorators import job
def vimtips(msg=None):
try:
existing_tips = get_hash('vimtips')
_len = len(existing_tips)
if _len > 0:
_index = randint(0, _len - 1)
_k = existing_tips.keys()[_index]
_v = existing_tips[_k]
tip = {
'Content': _k,
'Comment': _v
}
else:
tip = requests.get('http://vim-tips.com/random_tips/json').json()
existing_tips.update({
tip['Content']: tip['Comment']
})
collect_tip.delay()
except Exception as e:
return '哦,不小心玩坏了……'
return '%s\n%s' % (tip['Content'], tip['Comment'], )
# Fetch a new tip in RQ queue
@job('default', connection=SYSTEMS['default'], result_ttl=5)
def collect_tip():
tip = requests.get('http://vim-tips.com/random_tips/json').json()
get_hash('vimtips').update({
tip['Content']: tip['Comment']
})
| # ... existing code ...
from random import randint
import requests
from redis_wrap import get_hash, SYSTEMS
from rq.decorators import job
# ... modified code ...
})
collect_tip.delay()
except Exception as e:
return '哦,不小心玩坏了……'
return '%s\n%s' % (tip['Content'], tip['Comment'], )
# Fetch a new tip in RQ queue
@job('default', connection=SYSTEMS['default'], result_ttl=5)
def collect_tip():
# ... rest of the code ... |
3131f282d6ad1a703939c91c0d7dc0b3e4e54046 | iati/versions.py | iati/versions.py | """A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number."""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
| """A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number.
Args:
version_string (str): A string representation of an IATI version number.
Raises:
TypeError: If an attempt to pass something that is not a string is made.
ValueError: If a provided string is not a version number.
"""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
| Document the current state of the Version class. | Document the current state of the Version class.
| Python | mit | IATI/iati.core,IATI/iati.core | """A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
- """Initialise a Version Number."""
+ """Initialise a Version Number.
+
+ Args:
+ version_string (str): A string representation of an IATI version number.
+
+ Raises:
+ TypeError: If an attempt to pass something that is not a string is made.
+ ValueError: If a provided string is not a version number.
+
+ """
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
| Document the current state of the Version class. | ## Code Before:
"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number."""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
## Instruction:
Document the current state of the Version class.
## Code After:
"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number.
Args:
version_string (str): A string representation of an IATI version number.
Raises:
TypeError: If an attempt to pass something that is not a string is made.
ValueError: If a provided string is not a version number.
"""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
| ...
def __init__(self, version_string):
"""Initialise a Version Number.
Args:
version_string (str): A string representation of an IATI version number.
Raises:
TypeError: If an attempt to pass something that is not a string is made.
ValueError: If a provided string is not a version number.
"""
if not isinstance(version_string, str):
... |
90d079928eaf48e370d21417e4d6e649ec0f5f6f | taskwiki/taskwiki.py | taskwiki/taskwiki.py | import sys
import re
import vim
from tasklib.task import TaskWarrior, Task
# Insert the taskwiki on the python path
sys.path.insert(0, vim.eval("s:plugin_path") + '/taskwiki')
from regexp import *
from task import VimwikiTask
from cache import TaskCache
"""
How this plugin works:
1.) On startup, it reads all the tasks and syncs info TW -> Vimwiki file. Task is identified by their
uuid.
2.) When saving, the opposite sync is performed (Vimwiki -> TW direction).
a) if task is marked as subtask by indentation, the dependency is created between
"""
tw = TaskWarrior()
cache = TaskCache(tw)
def update_from_tw():
"""
Updates all the incomplete tasks in the vimwiki file if the info from TW is different.
"""
cache.load_buffer()
cache.update_tasks()
cache.update_buffer()
cache.evaluate_viewports()
def update_to_tw():
"""
Updates all tasks that differ from their TaskWarrior representation.
"""
cache.reset()
cache.load_buffer()
cache.save_tasks()
cache.update_buffer()
if __name__ == '__main__':
update_from_tw()
| import sys
import re
import vim
from tasklib.task import TaskWarrior, Task
# Insert the taskwiki on the python path
sys.path.insert(0, vim.eval("s:plugin_path") + '/taskwiki')
from regexp import *
from task import VimwikiTask
from cache import TaskCache
"""
How this plugin works:
1.) On startup, it reads all the tasks and syncs info TW -> Vimwiki file. Task is identified by their
uuid.
2.) When saving, the opposite sync is performed (Vimwiki -> TW direction).
a) if task is marked as subtask by indentation, the dependency is created between
"""
tw = TaskWarrior()
cache = TaskCache(tw)
def update_from_tw():
"""
Updates all the incomplete tasks in the vimwiki file if the info from TW is different.
"""
cache.load_buffer()
cache.update_tasks()
cache.update_buffer()
cache.evaluate_viewports()
def update_to_tw():
"""
Updates all tasks that differ from their TaskWarrior representation.
"""
cache.reset()
cache.load_buffer()
cache.update_tasks()
cache.save_tasks()
cache.update_buffer()
cache.evaluate_viewports()
if __name__ == '__main__':
update_from_tw()
| Update tasks and evaluate viewports on saving | Taskwiki: Update tasks and evaluate viewports on saving
| Python | mit | phha/taskwiki,Spirotot/taskwiki | import sys
import re
import vim
from tasklib.task import TaskWarrior, Task
# Insert the taskwiki on the python path
sys.path.insert(0, vim.eval("s:plugin_path") + '/taskwiki')
from regexp import *
from task import VimwikiTask
from cache import TaskCache
"""
How this plugin works:
1.) On startup, it reads all the tasks and syncs info TW -> Vimwiki file. Task is identified by their
uuid.
2.) When saving, the opposite sync is performed (Vimwiki -> TW direction).
a) if task is marked as subtask by indentation, the dependency is created between
"""
tw = TaskWarrior()
cache = TaskCache(tw)
def update_from_tw():
"""
Updates all the incomplete tasks in the vimwiki file if the info from TW is different.
"""
cache.load_buffer()
cache.update_tasks()
cache.update_buffer()
cache.evaluate_viewports()
def update_to_tw():
"""
Updates all tasks that differ from their TaskWarrior representation.
"""
cache.reset()
cache.load_buffer()
+ cache.update_tasks()
cache.save_tasks()
cache.update_buffer()
+ cache.evaluate_viewports()
if __name__ == '__main__':
update_from_tw()
| Update tasks and evaluate viewports on saving | ## Code Before:
import sys
import re
import vim
from tasklib.task import TaskWarrior, Task
# Insert the taskwiki on the python path
sys.path.insert(0, vim.eval("s:plugin_path") + '/taskwiki')
from regexp import *
from task import VimwikiTask
from cache import TaskCache
"""
How this plugin works:
1.) On startup, it reads all the tasks and syncs info TW -> Vimwiki file. Task is identified by their
uuid.
2.) When saving, the opposite sync is performed (Vimwiki -> TW direction).
a) if task is marked as subtask by indentation, the dependency is created between
"""
tw = TaskWarrior()
cache = TaskCache(tw)
def update_from_tw():
"""
Updates all the incomplete tasks in the vimwiki file if the info from TW is different.
"""
cache.load_buffer()
cache.update_tasks()
cache.update_buffer()
cache.evaluate_viewports()
def update_to_tw():
"""
Updates all tasks that differ from their TaskWarrior representation.
"""
cache.reset()
cache.load_buffer()
cache.save_tasks()
cache.update_buffer()
if __name__ == '__main__':
update_from_tw()
## Instruction:
Update tasks and evaluate viewports on saving
## Code After:
import sys
import re
import vim
from tasklib.task import TaskWarrior, Task
# Insert the taskwiki on the python path
sys.path.insert(0, vim.eval("s:plugin_path") + '/taskwiki')
from regexp import *
from task import VimwikiTask
from cache import TaskCache
"""
How this plugin works:
1.) On startup, it reads all the tasks and syncs info TW -> Vimwiki file. Task is identified by their
uuid.
2.) When saving, the opposite sync is performed (Vimwiki -> TW direction).
a) if task is marked as subtask by indentation, the dependency is created between
"""
tw = TaskWarrior()
cache = TaskCache(tw)
def update_from_tw():
"""
Updates all the incomplete tasks in the vimwiki file if the info from TW is different.
"""
cache.load_buffer()
cache.update_tasks()
cache.update_buffer()
cache.evaluate_viewports()
def update_to_tw():
"""
Updates all tasks that differ from their TaskWarrior representation.
"""
cache.reset()
cache.load_buffer()
cache.update_tasks()
cache.save_tasks()
cache.update_buffer()
cache.evaluate_viewports()
if __name__ == '__main__':
update_from_tw()
| # ... existing code ...
cache.load_buffer()
cache.update_tasks()
cache.save_tasks()
# ... modified code ...
cache.update_buffer()
cache.evaluate_viewports()
# ... rest of the code ... |
4f94e7bc314e31f322c912762339fda047d04688 | src/gpio-shutdown.py | src/gpio-shutdown.py |
import RPIO
import subprocess
PIN_MODE = RPIO.BCM
SHUTDOWN_BTN_PIN = 4
PIN_PULL = RPIO.PUD_DOWN
EDGE_DETECT = 'rising'
def main():
RPIO.setmode(PIN_MODE)
RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL)
RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN,
shutdown_callback,
edge=EDGE_DETECT,
pull_up_down=PIN_PULL,
debounce_timeout_ms=33)
def shutdown_callback(gpio_id, value):
subprocess.call('shutdown now')
if __name__ == '__main__':
main()
|
import RPIO
import subprocess
import time
PIN_MODE = RPIO.BCM
SHUTDOWN_BTN_PIN = 4
PIN_PULL = RPIO.PUD_DOWN
EDGE_DETECT = 'rising'
def main():
RPIO.setmode(PIN_MODE)
RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL)
RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN,
shutdown_callback,
edge=EDGE_DETECT,
pull_up_down=PIN_PULL,
debounce_timeout_ms=33)
def shutdown_callback(gpio_id, value):
subprocess.call('shutdown now')
if __name__ == '__main__':
main()
# do an efficient spin-lock here so that we can continue waiting for an
# interrupt
while True:
# this sleep() is an attempt to prevent the CPU from staying at 100%
time.sleep(10)
| Add sleeping spin-wait to listener script | Add sleeping spin-wait to listener script
This will prevent the script from exiting, thus defeating the entire purpose of
using a separate GPIO button to shutdown
| Python | epl-1.0 | MSOE-Supermileage/datacollector,MSOE-Supermileage/datacollector,MSOE-Supermileage/datacollector |
import RPIO
import subprocess
+ import time
PIN_MODE = RPIO.BCM
SHUTDOWN_BTN_PIN = 4
PIN_PULL = RPIO.PUD_DOWN
EDGE_DETECT = 'rising'
def main():
RPIO.setmode(PIN_MODE)
RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL)
RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN,
shutdown_callback,
edge=EDGE_DETECT,
pull_up_down=PIN_PULL,
debounce_timeout_ms=33)
def shutdown_callback(gpio_id, value):
subprocess.call('shutdown now')
if __name__ == '__main__':
main()
+ # do an efficient spin-lock here so that we can continue waiting for an
+ # interrupt
+ while True:
+ # this sleep() is an attempt to prevent the CPU from staying at 100%
+ time.sleep(10)
+
+ | Add sleeping spin-wait to listener script | ## Code Before:
import RPIO
import subprocess
PIN_MODE = RPIO.BCM
SHUTDOWN_BTN_PIN = 4
PIN_PULL = RPIO.PUD_DOWN
EDGE_DETECT = 'rising'
def main():
RPIO.setmode(PIN_MODE)
RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL)
RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN,
shutdown_callback,
edge=EDGE_DETECT,
pull_up_down=PIN_PULL,
debounce_timeout_ms=33)
def shutdown_callback(gpio_id, value):
subprocess.call('shutdown now')
if __name__ == '__main__':
main()
## Instruction:
Add sleeping spin-wait to listener script
## Code After:
import RPIO
import subprocess
import time
PIN_MODE = RPIO.BCM
SHUTDOWN_BTN_PIN = 4
PIN_PULL = RPIO.PUD_DOWN
EDGE_DETECT = 'rising'
def main():
RPIO.setmode(PIN_MODE)
RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL)
RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN,
shutdown_callback,
edge=EDGE_DETECT,
pull_up_down=PIN_PULL,
debounce_timeout_ms=33)
def shutdown_callback(gpio_id, value):
subprocess.call('shutdown now')
if __name__ == '__main__':
main()
# do an efficient spin-lock here so that we can continue waiting for an
# interrupt
while True:
# this sleep() is an attempt to prevent the CPU from staying at 100%
time.sleep(10)
| // ... existing code ...
import subprocess
import time
// ... modified code ...
main()
# do an efficient spin-lock here so that we can continue waiting for an
# interrupt
while True:
# this sleep() is an attempt to prevent the CPU from staying at 100%
time.sleep(10)
// ... rest of the code ... |
68fe680266f705bea2b33e614d7aac2ae13b46a2 | url_shortener/forms.py | url_shortener/forms.py | from flask_wtf import Form
from wtforms import StringField, validators
from .validation import not_spam
class ShortenedUrlForm(Form):
url = StringField(
'Url to be shortened',
[
validators.DataRequired(),
validators.URL(message="A valid url is required"),
not_spam
]
)
| from flask_wtf import Form
from wtforms import StringField, validators
from .validation import not_blacklisted_nor_spam
class ShortenedUrlForm(Form):
url = StringField(
'Url to be shortened',
[
validators.DataRequired(),
validators.URL(message="A valid url is required"),
not_blacklisted_nor_spam
]
)
| Replace not_spam validator with not_blacklisted_nor_spam in form class | Replace not_spam validator with not_blacklisted_nor_spam in form class
| Python | mit | piotr-rusin/url-shortener,piotr-rusin/url-shortener | from flask_wtf import Form
from wtforms import StringField, validators
- from .validation import not_spam
+ from .validation import not_blacklisted_nor_spam
class ShortenedUrlForm(Form):
url = StringField(
'Url to be shortened',
[
validators.DataRequired(),
validators.URL(message="A valid url is required"),
- not_spam
+ not_blacklisted_nor_spam
]
)
| Replace not_spam validator with not_blacklisted_nor_spam in form class | ## Code Before:
from flask_wtf import Form
from wtforms import StringField, validators
from .validation import not_spam
class ShortenedUrlForm(Form):
url = StringField(
'Url to be shortened',
[
validators.DataRequired(),
validators.URL(message="A valid url is required"),
not_spam
]
)
## Instruction:
Replace not_spam validator with not_blacklisted_nor_spam in form class
## Code After:
from flask_wtf import Form
from wtforms import StringField, validators
from .validation import not_blacklisted_nor_spam
class ShortenedUrlForm(Form):
url = StringField(
'Url to be shortened',
[
validators.DataRequired(),
validators.URL(message="A valid url is required"),
not_blacklisted_nor_spam
]
)
| // ... existing code ...
from .validation import not_blacklisted_nor_spam
// ... modified code ...
validators.URL(message="A valid url is required"),
not_blacklisted_nor_spam
]
// ... rest of the code ... |
fab561da9c54e278e7762380bf043a2fe03e39da | xerox/darwin.py | xerox/darwin.py |
import subprocess
import commands
from .base import *
def copy(string):
"""Copy given string into system clipboard."""
try:
subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string)))
except OSError as why:
raise XcodeNotFound
return
def paste():
"""Returns system clipboard contents."""
try:
return unicode(commands.getoutput('pbpaste'))
except OSError as why:
raise XcodeNotFound
|
import subprocess
from .base import *
def copy(string):
"""Copy given string into system clipboard."""
try:
subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string)))
except OSError as why:
raise XcodeNotFound
return
def paste():
"""Returns system clipboard contents."""
try:
return unicode(subprocess.check_output('pbpaste'))
except OSError as why:
raise XcodeNotFound
| Use `subprocess.check_output` rather than `commands.getoutput`. | Use `subprocess.check_output` rather than `commands.getoutput`.
`commands` is deprecated.
| Python | mit | solarce/xerox,kennethreitz/xerox |
import subprocess
- import commands
from .base import *
def copy(string):
"""Copy given string into system clipboard."""
try:
subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string)))
except OSError as why:
raise XcodeNotFound
return
def paste():
"""Returns system clipboard contents."""
try:
- return unicode(commands.getoutput('pbpaste'))
+ return unicode(subprocess.check_output('pbpaste'))
except OSError as why:
raise XcodeNotFound
| Use `subprocess.check_output` rather than `commands.getoutput`. | ## Code Before:
import subprocess
import commands
from .base import *
def copy(string):
"""Copy given string into system clipboard."""
try:
subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string)))
except OSError as why:
raise XcodeNotFound
return
def paste():
"""Returns system clipboard contents."""
try:
return unicode(commands.getoutput('pbpaste'))
except OSError as why:
raise XcodeNotFound
## Instruction:
Use `subprocess.check_output` rather than `commands.getoutput`.
## Code After:
import subprocess
from .base import *
def copy(string):
"""Copy given string into system clipboard."""
try:
subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string)))
except OSError as why:
raise XcodeNotFound
return
def paste():
"""Returns system clipboard contents."""
try:
return unicode(subprocess.check_output('pbpaste'))
except OSError as why:
raise XcodeNotFound
| ...
import subprocess
...
try:
return unicode(subprocess.check_output('pbpaste'))
except OSError as why:
... |
53a1c2ccbd43a8fcb90d8d9b7814c8ed129c0635 | thumbor_botornado/s3_http_loader.py | thumbor_botornado/s3_http_loader.py | from botornado.s3.bucket import AsyncBucket
from botornado.s3.connection import AsyncS3Connection
from botornado.s3.key import AsyncKey
from thumbor_botornado.s3_loader import S3Loader
from thumbor.loaders.http_loader import HttpLoader
def load(context, url, callback):
p = re.compile('/^https?:/i')
m = p.match(url)
if m:
HttpLoader.load(context, url, callback)
else:
S3Loader.load(context, url, callback)
| import thumbor_botornado.s3_loader as S3Loader
import thumbor.loaders.http_loader as HttpLoader
import re
def load(context, url, callback):
if re.match('https?:', url, re.IGNORECASE):
HttpLoader.load(context, url, callback)
else:
S3Loader.load(context, url, callback)
| Add s3-http loader which delegates based on the uri | Add s3-http loader which delegates based on the uri
| Python | mit | 99designs/thumbor_botornado,Jimdo/thumbor_botornado,99designs/thumbor_botornado,Jimdo/thumbor_botornado | - from botornado.s3.bucket import AsyncBucket
- from botornado.s3.connection import AsyncS3Connection
- from botornado.s3.key import AsyncKey
-
- from thumbor_botornado.s3_loader import S3Loader
+ import thumbor_botornado.s3_loader as S3Loader
- from thumbor.loaders.http_loader import HttpLoader
+ import thumbor.loaders.http_loader as HttpLoader
+ import re
def load(context, url, callback):
+ if re.match('https?:', url, re.IGNORECASE):
- p = re.compile('/^https?:/i')
- m = p.match(url)
- if m:
HttpLoader.load(context, url, callback)
else:
S3Loader.load(context, url, callback)
| Add s3-http loader which delegates based on the uri | ## Code Before:
from botornado.s3.bucket import AsyncBucket
from botornado.s3.connection import AsyncS3Connection
from botornado.s3.key import AsyncKey
from thumbor_botornado.s3_loader import S3Loader
from thumbor.loaders.http_loader import HttpLoader
def load(context, url, callback):
p = re.compile('/^https?:/i')
m = p.match(url)
if m:
HttpLoader.load(context, url, callback)
else:
S3Loader.load(context, url, callback)
## Instruction:
Add s3-http loader which delegates based on the uri
## Code After:
import thumbor_botornado.s3_loader as S3Loader
import thumbor.loaders.http_loader as HttpLoader
import re
def load(context, url, callback):
if re.match('https?:', url, re.IGNORECASE):
HttpLoader.load(context, url, callback)
else:
S3Loader.load(context, url, callback)
| # ... existing code ...
import thumbor_botornado.s3_loader as S3Loader
import thumbor.loaders.http_loader as HttpLoader
import re
# ... modified code ...
def load(context, url, callback):
if re.match('https?:', url, re.IGNORECASE):
HttpLoader.load(context, url, callback)
# ... rest of the code ... |
210be14772b403e8fb5938e4e2cd391d43275ab1 | tests/test_ot_propagators.py | tests/test_ot_propagators.py | import instana.http_propagator as ihp
import opentracing as ot
from instana import tracer, options, util
from nose.tools import assert_equals
import inspect
def test_basics():
inspect.isclass(ihp.HTTPPropagator)
inject_func = getattr(ihp.HTTPPropagator, "inject", None)
assert inject_func
assert inspect.ismethod(inject_func)
extract_func = getattr(ihp.HTTPPropagator, "extract", None)
assert extract_func
assert inspect.ismethod(extract_func)
def test_inject():
opts = options.Options()
ot.global_tracer = tracer.InstanaTracer(opts)
carrier = {}
span = ot.global_tracer.start_span("nosetests")
ot.global_tracer.inject(span.context, ot.Format.HTTP_HEADERS, carrier)
assert 'X-Instana-T' in carrier
assert_equals(carrier['X-Instana-T'], util.id_to_header(span.context.trace_id))
assert 'X-Instana-S' in carrier
assert_equals(carrier['X-Instana-S'], util.id_to_header(span.context.span_id))
assert 'X-Instana-L' in carrier
assert_equals(carrier['X-Instana-L'], "1")
| import instana.http_propagator as ihp
import opentracing as ot
from instana import tracer, options, util
from nose.tools import assert_equals
import inspect
def test_basics():
inspect.isclass(ihp.HTTPPropagator)
inject_func = getattr(ihp.HTTPPropagator, "inject", None)
assert inject_func
assert callable(inject_func)
extract_func = getattr(ihp.HTTPPropagator, "extract", None)
assert extract_func
assert callable(extract_func)
def test_inject():
opts = options.Options()
ot.global_tracer = tracer.InstanaTracer(opts)
carrier = {}
span = ot.global_tracer.start_span("nosetests")
ot.global_tracer.inject(span.context, ot.Format.HTTP_HEADERS, carrier)
assert 'X-Instana-T' in carrier
assert_equals(carrier['X-Instana-T'], util.id_to_header(span.context.trace_id))
assert 'X-Instana-S' in carrier
assert_equals(carrier['X-Instana-S'], util.id_to_header(span.context.span_id))
assert 'X-Instana-L' in carrier
assert_equals(carrier['X-Instana-L'], "1")
| Fix function test to work on both Py 2 + 3 | Fix function test to work on both Py 2 + 3
| Python | mit | instana/python-sensor,instana/python-sensor | import instana.http_propagator as ihp
import opentracing as ot
from instana import tracer, options, util
from nose.tools import assert_equals
import inspect
def test_basics():
inspect.isclass(ihp.HTTPPropagator)
inject_func = getattr(ihp.HTTPPropagator, "inject", None)
assert inject_func
- assert inspect.ismethod(inject_func)
+ assert callable(inject_func)
extract_func = getattr(ihp.HTTPPropagator, "extract", None)
assert extract_func
- assert inspect.ismethod(extract_func)
+ assert callable(extract_func)
def test_inject():
opts = options.Options()
ot.global_tracer = tracer.InstanaTracer(opts)
carrier = {}
span = ot.global_tracer.start_span("nosetests")
ot.global_tracer.inject(span.context, ot.Format.HTTP_HEADERS, carrier)
assert 'X-Instana-T' in carrier
assert_equals(carrier['X-Instana-T'], util.id_to_header(span.context.trace_id))
assert 'X-Instana-S' in carrier
assert_equals(carrier['X-Instana-S'], util.id_to_header(span.context.span_id))
assert 'X-Instana-L' in carrier
assert_equals(carrier['X-Instana-L'], "1")
| Fix function test to work on both Py 2 + 3 | ## Code Before:
import instana.http_propagator as ihp
import opentracing as ot
from instana import tracer, options, util
from nose.tools import assert_equals
import inspect
def test_basics():
inspect.isclass(ihp.HTTPPropagator)
inject_func = getattr(ihp.HTTPPropagator, "inject", None)
assert inject_func
assert inspect.ismethod(inject_func)
extract_func = getattr(ihp.HTTPPropagator, "extract", None)
assert extract_func
assert inspect.ismethod(extract_func)
def test_inject():
opts = options.Options()
ot.global_tracer = tracer.InstanaTracer(opts)
carrier = {}
span = ot.global_tracer.start_span("nosetests")
ot.global_tracer.inject(span.context, ot.Format.HTTP_HEADERS, carrier)
assert 'X-Instana-T' in carrier
assert_equals(carrier['X-Instana-T'], util.id_to_header(span.context.trace_id))
assert 'X-Instana-S' in carrier
assert_equals(carrier['X-Instana-S'], util.id_to_header(span.context.span_id))
assert 'X-Instana-L' in carrier
assert_equals(carrier['X-Instana-L'], "1")
## Instruction:
Fix function test to work on both Py 2 + 3
## Code After:
import instana.http_propagator as ihp
import opentracing as ot
from instana import tracer, options, util
from nose.tools import assert_equals
import inspect
def test_basics():
inspect.isclass(ihp.HTTPPropagator)
inject_func = getattr(ihp.HTTPPropagator, "inject", None)
assert inject_func
assert callable(inject_func)
extract_func = getattr(ihp.HTTPPropagator, "extract", None)
assert extract_func
assert callable(extract_func)
def test_inject():
opts = options.Options()
ot.global_tracer = tracer.InstanaTracer(opts)
carrier = {}
span = ot.global_tracer.start_span("nosetests")
ot.global_tracer.inject(span.context, ot.Format.HTTP_HEADERS, carrier)
assert 'X-Instana-T' in carrier
assert_equals(carrier['X-Instana-T'], util.id_to_header(span.context.trace_id))
assert 'X-Instana-S' in carrier
assert_equals(carrier['X-Instana-S'], util.id_to_header(span.context.span_id))
assert 'X-Instana-L' in carrier
assert_equals(carrier['X-Instana-L'], "1")
| # ... existing code ...
assert inject_func
assert callable(inject_func)
# ... modified code ...
assert extract_func
assert callable(extract_func)
# ... rest of the code ... |
cb3f208e2727cd1adea20c529ece5bd766f5e43d | users/models.py | users/models.py | from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from settings.models import VotingSystem
# Create your models here.
class Admin(models.Model):
user = models.ForeignKey(User)
system = models.ForeignKey(VotingSystem)
def __unicode__(self):
return u'[%s] %s' % (self.system.machine_name, self.user)
class SuperAdmin(models.Model):
user = models.ForeignKey(User)
def __unicode__(self):
return u'%s' % (self.user)
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name="profile")
details = models.TextField()
def __unicode__(self):
return u'[Profile] %s' % (self.user.username)
admin.site.register(Admin)
admin.site.register(SuperAdmin)
admin.site.register(UserProfile)
| from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.contrib import admin
from settings.models import VotingSystem
import json
# Create your models here.
class Admin(models.Model):
user = models.ForeignKey(User)
system = models.ForeignKey(VotingSystem)
def __unicode__(self):
return u'[%s] %s' % (self.system.machine_name, self.user)
class SuperAdmin(models.Model):
user = models.ForeignKey(User)
def __unicode__(self):
return u'%s' % (self.user)
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name="profile")
details = models.TextField()
def __unicode__(self):
return u'[Profile] %s' % (self.user.username)
def clean(self):
# make sure that the details are a valid json object
try:
json.loads(self.details)
except:
raise ValidationError({
'details': ValidationError('Details needs to be a valid JSON object', code='invalid')
})
admin.site.register(Admin)
admin.site.register(SuperAdmin)
admin.site.register(UserProfile)
| Make sure that user details are valid JSON | Make sure that user details are valid JSON
| Python | mit | kuboschek/jay,OpenJUB/jay,OpenJUB/jay,OpenJUB/jay,kuboschek/jay,kuboschek/jay | from django.db import models
from django.contrib.auth.models import User
+
+ from django.core.exceptions import ValidationError
from django.contrib import admin
from settings.models import VotingSystem
+
+ import json
# Create your models here.
class Admin(models.Model):
user = models.ForeignKey(User)
system = models.ForeignKey(VotingSystem)
def __unicode__(self):
return u'[%s] %s' % (self.system.machine_name, self.user)
class SuperAdmin(models.Model):
user = models.ForeignKey(User)
def __unicode__(self):
return u'%s' % (self.user)
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name="profile")
details = models.TextField()
def __unicode__(self):
return u'[Profile] %s' % (self.user.username)
+ def clean(self):
+ # make sure that the details are a valid json object
+ try:
+ json.loads(self.details)
+ except:
+ raise ValidationError({
+ 'details': ValidationError('Details needs to be a valid JSON object', code='invalid')
+ })
+
admin.site.register(Admin)
admin.site.register(SuperAdmin)
admin.site.register(UserProfile)
| Make sure that user details are valid JSON | ## Code Before:
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from settings.models import VotingSystem
# Create your models here.
class Admin(models.Model):
user = models.ForeignKey(User)
system = models.ForeignKey(VotingSystem)
def __unicode__(self):
return u'[%s] %s' % (self.system.machine_name, self.user)
class SuperAdmin(models.Model):
user = models.ForeignKey(User)
def __unicode__(self):
return u'%s' % (self.user)
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name="profile")
details = models.TextField()
def __unicode__(self):
return u'[Profile] %s' % (self.user.username)
admin.site.register(Admin)
admin.site.register(SuperAdmin)
admin.site.register(UserProfile)
## Instruction:
Make sure that user details are valid JSON
## Code After:
from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.contrib import admin
from settings.models import VotingSystem
import json
# Create your models here.
class Admin(models.Model):
user = models.ForeignKey(User)
system = models.ForeignKey(VotingSystem)
def __unicode__(self):
return u'[%s] %s' % (self.system.machine_name, self.user)
class SuperAdmin(models.Model):
user = models.ForeignKey(User)
def __unicode__(self):
return u'%s' % (self.user)
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name="profile")
details = models.TextField()
def __unicode__(self):
return u'[Profile] %s' % (self.user.username)
def clean(self):
# make sure that the details are a valid json object
try:
json.loads(self.details)
except:
raise ValidationError({
'details': ValidationError('Details needs to be a valid JSON object', code='invalid')
})
admin.site.register(Admin)
admin.site.register(SuperAdmin)
admin.site.register(UserProfile)
| # ... existing code ...
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
# ... modified code ...
from settings.models import VotingSystem
import json
...
def clean(self):
# make sure that the details are a valid json object
try:
json.loads(self.details)
except:
raise ValidationError({
'details': ValidationError('Details needs to be a valid JSON object', code='invalid')
})
admin.site.register(Admin)
# ... rest of the code ... |
66fe6f98c079490d2d5de4c161da1d8b3801cda4 | monasca_persister/conf/influxdb.py | monasca_persister/conf/influxdb.py |
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
cfg.IPOpt('ip_address',
help='ip address to influxdb'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
def register_opts(conf):
conf.register_group(influxdb_group)
conf.register_opts(influxdb_opts, influxdb_group)
def list_opts():
return influxdb_group, influxdb_opts
|
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
cfg.HostAddressOpt('ip_address',
help='Valid IP address or hostname '
'to InfluxDB instance'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
def register_opts(conf):
conf.register_group(influxdb_group)
conf.register_opts(influxdb_opts, influxdb_group)
def list_opts():
return influxdb_group, influxdb_opts
| Allow hostnames to be used as ip_address | Allow hostnames to be used as ip_address
Previously introduced change for monasca-persister
had enforced the IPAddress as the only type one can
configure influxdb.ip_address property with.
Following change makes it possible to use also hostname.
Using IPAdress is still possible.
Change-Id: Ib0d7f19b3ac2dcb7c84923872d94f180cda58b2b
| Python | apache-2.0 | stackforge/monasca-persister,openstack/monasca-persister,stackforge/monasca-persister,stackforge/monasca-persister,openstack/monasca-persister,openstack/monasca-persister |
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
- cfg.IPOpt('ip_address',
+ cfg.HostAddressOpt('ip_address',
- help='ip address to influxdb'),
+ help='Valid IP address or hostname '
+ 'to InfluxDB instance'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
def register_opts(conf):
conf.register_group(influxdb_group)
conf.register_opts(influxdb_opts, influxdb_group)
def list_opts():
return influxdb_group, influxdb_opts
| Allow hostnames to be used as ip_address | ## Code Before:
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
cfg.IPOpt('ip_address',
help='ip address to influxdb'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
def register_opts(conf):
conf.register_group(influxdb_group)
conf.register_opts(influxdb_opts, influxdb_group)
def list_opts():
return influxdb_group, influxdb_opts
## Instruction:
Allow hostnames to be used as ip_address
## Code After:
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
cfg.HostAddressOpt('ip_address',
help='Valid IP address or hostname '
'to InfluxDB instance'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
def register_opts(conf):
conf.register_group(influxdb_group)
conf.register_opts(influxdb_opts, influxdb_group)
def list_opts():
return influxdb_group, influxdb_opts
| ...
default='mon'),
cfg.HostAddressOpt('ip_address',
help='Valid IP address or hostname '
'to InfluxDB instance'),
cfg.PortOpt('port',
... |
41c6b1820e8b23079d9098526854c9a60859d128 | gcloud_expenses/test_views.py | gcloud_expenses/test_views.py | import unittest
class ViewTests(unittest.TestCase):
def setUp(self):
from pyramid import testing
self.config = testing.setUp()
def tearDown(self):
from pyramid import testing
testing.tearDown()
def test_my_view(self):
from pyramid import testing
from .views import my_view
request = testing.DummyRequest()
info = my_view(request)
self.assertEqual(info['project'], 'foo')
| import unittest
class ViewTests(unittest.TestCase):
def setUp(self):
from pyramid import testing
self.config = testing.setUp()
def tearDown(self):
from pyramid import testing
testing.tearDown()
def test_home_page(self):
from pyramid import testing
from .views import home_page
request = testing.DummyRequest()
info = home_page(request)
self.assertEqual(info, {})
| Fix test broken in rename. | Fix test broken in rename.
| Python | apache-2.0 | GoogleCloudPlatform/google-cloud-python-expenses-demo,GoogleCloudPlatform/google-cloud-python-expenses-demo | import unittest
class ViewTests(unittest.TestCase):
def setUp(self):
from pyramid import testing
self.config = testing.setUp()
def tearDown(self):
from pyramid import testing
testing.tearDown()
- def test_my_view(self):
+ def test_home_page(self):
from pyramid import testing
- from .views import my_view
+ from .views import home_page
request = testing.DummyRequest()
- info = my_view(request)
+ info = home_page(request)
- self.assertEqual(info['project'], 'foo')
+ self.assertEqual(info, {})
| Fix test broken in rename. | ## Code Before:
import unittest
class ViewTests(unittest.TestCase):
def setUp(self):
from pyramid import testing
self.config = testing.setUp()
def tearDown(self):
from pyramid import testing
testing.tearDown()
def test_my_view(self):
from pyramid import testing
from .views import my_view
request = testing.DummyRequest()
info = my_view(request)
self.assertEqual(info['project'], 'foo')
## Instruction:
Fix test broken in rename.
## Code After:
import unittest
class ViewTests(unittest.TestCase):
def setUp(self):
from pyramid import testing
self.config = testing.setUp()
def tearDown(self):
from pyramid import testing
testing.tearDown()
def test_home_page(self):
from pyramid import testing
from .views import home_page
request = testing.DummyRequest()
info = home_page(request)
self.assertEqual(info, {})
| ...
def test_home_page(self):
from pyramid import testing
from .views import home_page
request = testing.DummyRequest()
info = home_page(request)
self.assertEqual(info, {})
... |
c7941340336b3fe584dd192583c088eb1f1f972e | genomic_neuralnet/common/celeryconfig.py | genomic_neuralnet/common/celeryconfig.py | BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} # Seconds = 1 hour.
# Do not pre-fetch work.
CELERYD_PREFETCH_MULTIPLIER = 1
# Do not ack messages until work is completed.
CELERY_ACKS_LATE = True
# Stop warning me about PICKLE.
CELERY_ACCEPT_CONTENT = ['pickle']
| BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60*60} # 60*60 Seconds = 1 hour.
# Do not pre-fetch work.
CELERYD_PREFETCH_MULTIPLIER = 1
# Do not ack messages until work is completed.
CELERY_ACKS_LATE = True
# Stop warning me about PICKLE.
CELERY_ACCEPT_CONTENT = ['pickle']
# Clear out finished results after 30 minutes.
CELERY_TASK_RESULT_EXPIRES = 60*30
| Reduce result broker message timeout | Reduce result broker message timeout
| Python | mit | rileymcdowell/genomic-neuralnet,rileymcdowell/genomic-neuralnet,rileymcdowell/genomic-neuralnet | - BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} # Seconds = 1 hour.
+ BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60*60} # 60*60 Seconds = 1 hour.
# Do not pre-fetch work.
CELERYD_PREFETCH_MULTIPLIER = 1
# Do not ack messages until work is completed.
CELERY_ACKS_LATE = True
# Stop warning me about PICKLE.
CELERY_ACCEPT_CONTENT = ['pickle']
+ # Clear out finished results after 30 minutes.
+ CELERY_TASK_RESULT_EXPIRES = 60*30
- | Reduce result broker message timeout | ## Code Before:
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} # Seconds = 1 hour.
# Do not pre-fetch work.
CELERYD_PREFETCH_MULTIPLIER = 1
# Do not ack messages until work is completed.
CELERY_ACKS_LATE = True
# Stop warning me about PICKLE.
CELERY_ACCEPT_CONTENT = ['pickle']
## Instruction:
Reduce result broker message timeout
## Code After:
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60*60} # 60*60 Seconds = 1 hour.
# Do not pre-fetch work.
CELERYD_PREFETCH_MULTIPLIER = 1
# Do not ack messages until work is completed.
CELERY_ACKS_LATE = True
# Stop warning me about PICKLE.
CELERY_ACCEPT_CONTENT = ['pickle']
# Clear out finished results after 30 minutes.
CELERY_TASK_RESULT_EXPIRES = 60*30
| # ... existing code ...
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60*60} # 60*60 Seconds = 1 hour.
# Do not pre-fetch work.
# ... modified code ...
CELERY_ACCEPT_CONTENT = ['pickle']
# Clear out finished results after 30 minutes.
CELERY_TASK_RESULT_EXPIRES = 60*30
# ... rest of the code ... |
2917c8d380bfee3c7589f806ea12f2e3f83e8b93 | npc/character/__init__.py | npc/character/__init__.py | from .character import *
|
from .character import Character
from .changeling import Changeling
from .werewolf import Werewolf
def build(attributes: dict = None, other_char: Character = None):
"""
Build a new character object with the appropriate class
This derives the correct character class based on the type tag of either the
other_char character object or the attributes dict, then creates a new
character object using that class. If neither is supplied, a blank Character
is returned.
The character type is fetched first from other_char and only if that is not
present is it fetched from attributes.
Both other_char and attribuets are passed to the character constructor. See
that for how their precedence is applied.
If you need more control over the instantiation process, use
character_klass_from_type and call the object manually.
Args:
attributes (dict): Dictionary of attributes to insert into the
Character.
other_char (Character): Existing character object to copy.
Returns:
Instantiated Character class or subclass matching the given type.
"""
if other_char:
klass = character_klass_from_type(other_char.type_key)
elif attributes:
klass = character_klass_from_type(attributes['type'][0])
else:
klass = Character
return klass(other_char = other_char, attributes = attributes)
def character_klass_from_type(ctype: str):
"""
Choose the correct character class based on type tag
Args:
ctype (str): Character type tag to use
Returns:
Character class or subclass depending on the type
"""
if ctype:
ctype = ctype.lower()
if ctype == 'changeling':
return Changeling
if ctype == 'werewolf':
return Werewolf
return Character
| Add helpers to find the right character class | Add helpers to find the right character class
| Python | mit | aurule/npc,aurule/npc | - from .character import *
+ from .character import Character
+ from .changeling import Changeling
+ from .werewolf import Werewolf
+
+ def build(attributes: dict = None, other_char: Character = None):
+ """
+ Build a new character object with the appropriate class
+
+ This derives the correct character class based on the type tag of either the
+ other_char character object or the attributes dict, then creates a new
+ character object using that class. If neither is supplied, a blank Character
+ is returned.
+
+ The character type is fetched first from other_char and only if that is not
+ present is it fetched from attributes.
+
+ Both other_char and attribuets are passed to the character constructor. See
+ that for how their precedence is applied.
+
+ If you need more control over the instantiation process, use
+ character_klass_from_type and call the object manually.
+
+ Args:
+ attributes (dict): Dictionary of attributes to insert into the
+ Character.
+ other_char (Character): Existing character object to copy.
+
+ Returns:
+ Instantiated Character class or subclass matching the given type.
+ """
+ if other_char:
+ klass = character_klass_from_type(other_char.type_key)
+ elif attributes:
+ klass = character_klass_from_type(attributes['type'][0])
+ else:
+ klass = Character
+
+ return klass(other_char = other_char, attributes = attributes)
+
+ def character_klass_from_type(ctype: str):
+ """
+ Choose the correct character class based on type tag
+
+ Args:
+ ctype (str): Character type tag to use
+
+ Returns:
+ Character class or subclass depending on the type
+ """
+ if ctype:
+ ctype = ctype.lower()
+ if ctype == 'changeling':
+ return Changeling
+ if ctype == 'werewolf':
+ return Werewolf
+
+ return Character
+ | Add helpers to find the right character class | ## Code Before:
from .character import *
## Instruction:
Add helpers to find the right character class
## Code After:
from .character import Character
from .changeling import Changeling
from .werewolf import Werewolf
def build(attributes: dict = None, other_char: Character = None):
"""
Build a new character object with the appropriate class
This derives the correct character class based on the type tag of either the
other_char character object or the attributes dict, then creates a new
character object using that class. If neither is supplied, a blank Character
is returned.
The character type is fetched first from other_char and only if that is not
present is it fetched from attributes.
Both other_char and attribuets are passed to the character constructor. See
that for how their precedence is applied.
If you need more control over the instantiation process, use
character_klass_from_type and call the object manually.
Args:
attributes (dict): Dictionary of attributes to insert into the
Character.
other_char (Character): Existing character object to copy.
Returns:
Instantiated Character class or subclass matching the given type.
"""
if other_char:
klass = character_klass_from_type(other_char.type_key)
elif attributes:
klass = character_klass_from_type(attributes['type'][0])
else:
klass = Character
return klass(other_char = other_char, attributes = attributes)
def character_klass_from_type(ctype: str):
"""
Choose the correct character class based on type tag
Args:
ctype (str): Character type tag to use
Returns:
Character class or subclass depending on the type
"""
if ctype:
ctype = ctype.lower()
if ctype == 'changeling':
return Changeling
if ctype == 'werewolf':
return Werewolf
return Character
| # ... existing code ...
from .character import Character
from .changeling import Changeling
from .werewolf import Werewolf
def build(attributes: dict = None, other_char: Character = None):
"""
Build a new character object with the appropriate class
This derives the correct character class based on the type tag of either the
other_char character object or the attributes dict, then creates a new
character object using that class. If neither is supplied, a blank Character
is returned.
The character type is fetched first from other_char and only if that is not
present is it fetched from attributes.
Both other_char and attribuets are passed to the character constructor. See
that for how their precedence is applied.
If you need more control over the instantiation process, use
character_klass_from_type and call the object manually.
Args:
attributes (dict): Dictionary of attributes to insert into the
Character.
other_char (Character): Existing character object to copy.
Returns:
Instantiated Character class or subclass matching the given type.
"""
if other_char:
klass = character_klass_from_type(other_char.type_key)
elif attributes:
klass = character_klass_from_type(attributes['type'][0])
else:
klass = Character
return klass(other_char = other_char, attributes = attributes)
def character_klass_from_type(ctype: str):
"""
Choose the correct character class based on type tag
Args:
ctype (str): Character type tag to use
Returns:
Character class or subclass depending on the type
"""
if ctype:
ctype = ctype.lower()
if ctype == 'changeling':
return Changeling
if ctype == 'werewolf':
return Werewolf
return Character
# ... rest of the code ... |
df58b36b6f62c39030d6ff28c6fb67c11f112df0 | pyxrf/gui_module/main_window.py | pyxrf/gui_module/main_window.py | from PyQt5.QtWidgets import QMainWindow
_main_window_geometry = {
"initial_height": 800,
"initial_width": 1000,
"min_height": 400,
"min_width": 500,
}
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initialize()
def initialize(self):
self.resize(_main_window_geometry["initial_width"],
_main_window_geometry["initial_height"])
self.setMinimumWidth(_main_window_geometry["min_width"])
self.setMinimumHeight(_main_window_geometry["min_height"])
| from PyQt5.QtWidgets import QMainWindow
_main_window_geometry = {
"initial_height": 800,
"initial_width": 1000,
"min_height": 400,
"min_width": 500,
}
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initialize()
def initialize(self):
self.resize(_main_window_geometry["initial_width"],
_main_window_geometry["initial_height"])
self.setMinimumWidth(_main_window_geometry["min_width"])
self.setMinimumHeight(_main_window_geometry["min_height"])
self.setWindowTitle("PyXRF window title") | Test window title on Mac | Test window title on Mac
| Python | bsd-3-clause | NSLS-II-HXN/PyXRF,NSLS-II/PyXRF,NSLS-II-HXN/PyXRF | from PyQt5.QtWidgets import QMainWindow
_main_window_geometry = {
"initial_height": 800,
"initial_width": 1000,
"min_height": 400,
"min_width": 500,
}
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initialize()
def initialize(self):
self.resize(_main_window_geometry["initial_width"],
_main_window_geometry["initial_height"])
self.setMinimumWidth(_main_window_geometry["min_width"])
self.setMinimumHeight(_main_window_geometry["min_height"])
+ self.setWindowTitle("PyXRF window title") | Test window title on Mac | ## Code Before:
from PyQt5.QtWidgets import QMainWindow
_main_window_geometry = {
"initial_height": 800,
"initial_width": 1000,
"min_height": 400,
"min_width": 500,
}
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initialize()
def initialize(self):
self.resize(_main_window_geometry["initial_width"],
_main_window_geometry["initial_height"])
self.setMinimumWidth(_main_window_geometry["min_width"])
self.setMinimumHeight(_main_window_geometry["min_height"])
## Instruction:
Test window title on Mac
## Code After:
from PyQt5.QtWidgets import QMainWindow
_main_window_geometry = {
"initial_height": 800,
"initial_width": 1000,
"min_height": 400,
"min_width": 500,
}
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initialize()
def initialize(self):
self.resize(_main_window_geometry["initial_width"],
_main_window_geometry["initial_height"])
self.setMinimumWidth(_main_window_geometry["min_width"])
self.setMinimumHeight(_main_window_geometry["min_height"])
self.setWindowTitle("PyXRF window title") | ...
self.setMinimumHeight(_main_window_geometry["min_height"])
self.setWindowTitle("PyXRF window title")
... |
202fba50c287d3df99b22a4f30a96a3d8d9c8141 | tests/test_pypi.py | tests/test_pypi.py | from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
mock_run.call_args_list,
[
mock.call('python setup.py sdist bdist_wheel'),
mock.call('twine upload -u username -p password dist/*'),
mock.call('rm -rf build dist')
]
)
| from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
mock_run.call_args_list,
[
mock.call('rm -rf build dist'),
mock.call('python setup.py sdist bdist_wheel'),
mock.call('twine upload -u username -p password dist/*'),
mock.call('rm -rf build dist')
]
)
| Update test after adding cleaning of dist | test: Update test after adding cleaning of dist
| Python | mit | relekang/python-semantic-release,relekang/python-semantic-release | from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
mock_run.call_args_list,
[
+ mock.call('rm -rf build dist'),
mock.call('python setup.py sdist bdist_wheel'),
mock.call('twine upload -u username -p password dist/*'),
mock.call('rm -rf build dist')
]
)
| Update test after adding cleaning of dist | ## Code Before:
from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
mock_run.call_args_list,
[
mock.call('python setup.py sdist bdist_wheel'),
mock.call('twine upload -u username -p password dist/*'),
mock.call('rm -rf build dist')
]
)
## Instruction:
Update test after adding cleaning of dist
## Code After:
from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
mock_run.call_args_list,
[
mock.call('rm -rf build dist'),
mock.call('python setup.py sdist bdist_wheel'),
mock.call('twine upload -u username -p password dist/*'),
mock.call('rm -rf build dist')
]
)
| ...
[
mock.call('rm -rf build dist'),
mock.call('python setup.py sdist bdist_wheel'),
... |
30be8d71fee8f7429d6b4d48a8168133062e3315 | text_test/regex_utils_test.py | text_test/regex_utils_test.py |
import unittest
from text import regex_utils
class RegexUtilsTest(unittest.TestCase):
def test_check_line(self):
pass
def test_parse_line(self):
pass
if __name__ == '__main__':
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
import unittest
from text import regex_utils
class RegexUtilsTest(unittest.TestCase):
def test_check_line(self):
self.assertTrue(regex_utils.check_line('.*(\d+.\d+.\d+.\d+)', 'MyIP is 192.168.199.4'))
self.assertTrue(regex_utils.check_line('Test (Data|Case) For (py-text|py-task)', 'Test Data For py-text'))
self.assertFalse(regex_utils.check_line('.*(\d+.\d+.\d+.{100,255})', 'MyIP is 192.168.199.4'))
self.assertFalse(regex_utils.check_line(None, 'Test Word'))
self.assertFalse(regex_utils.check_line('.*', None))
def test_parse_line(self):
result = regex_utils.parse_line('name=(\S+), type=(\S+), ip=(\S+)', 'name=ASA5505, type=Firewall, ip=192.168.199.4')
self.assertEqual(len(result), 3)
self.assertEqual(result[0], 'ASA5505')
self.assertEqual(result[1], 'Firewall')
self.assertEqual(result[2], '192.168.199.4')
result = regex_utils.parse_line('Test Data', None)
self.assertEqual(result, None)
result = regex_utils.parse_line(None, 'Test Data')
self.assertEqual(result, 'Test Data')
if __name__ == '__main__':
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Update regex_utils unit test case | Update regex_utils unit test case | Python | apache-2.0 | PinaeOS/py-text,interhui/py-text |
import unittest
from text import regex_utils
class RegexUtilsTest(unittest.TestCase):
def test_check_line(self):
- pass
+ self.assertTrue(regex_utils.check_line('.*(\d+.\d+.\d+.\d+)', 'MyIP is 192.168.199.4'))
+ self.assertTrue(regex_utils.check_line('Test (Data|Case) For (py-text|py-task)', 'Test Data For py-text'))
+ self.assertFalse(regex_utils.check_line('.*(\d+.\d+.\d+.{100,255})', 'MyIP is 192.168.199.4'))
+ self.assertFalse(regex_utils.check_line(None, 'Test Word'))
+ self.assertFalse(regex_utils.check_line('.*', None))
def test_parse_line(self):
+ result = regex_utils.parse_line('name=(\S+), type=(\S+), ip=(\S+)', 'name=ASA5505, type=Firewall, ip=192.168.199.4')
+ self.assertEqual(len(result), 3)
+ self.assertEqual(result[0], 'ASA5505')
+ self.assertEqual(result[1], 'Firewall')
+ self.assertEqual(result[2], '192.168.199.4')
- pass
+
+ result = regex_utils.parse_line('Test Data', None)
+ self.assertEqual(result, None)
+
+ result = regex_utils.parse_line(None, 'Test Data')
+ self.assertEqual(result, 'Test Data')
+
if __name__ == '__main__':
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Update regex_utils unit test case | ## Code Before:
import unittest
from text import regex_utils
class RegexUtilsTest(unittest.TestCase):
def test_check_line(self):
pass
def test_parse_line(self):
pass
if __name__ == '__main__':
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
## Instruction:
Update regex_utils unit test case
## Code After:
import unittest
from text import regex_utils
class RegexUtilsTest(unittest.TestCase):
def test_check_line(self):
self.assertTrue(regex_utils.check_line('.*(\d+.\d+.\d+.\d+)', 'MyIP is 192.168.199.4'))
self.assertTrue(regex_utils.check_line('Test (Data|Case) For (py-text|py-task)', 'Test Data For py-text'))
self.assertFalse(regex_utils.check_line('.*(\d+.\d+.\d+.{100,255})', 'MyIP is 192.168.199.4'))
self.assertFalse(regex_utils.check_line(None, 'Test Word'))
self.assertFalse(regex_utils.check_line('.*', None))
def test_parse_line(self):
result = regex_utils.parse_line('name=(\S+), type=(\S+), ip=(\S+)', 'name=ASA5505, type=Firewall, ip=192.168.199.4')
self.assertEqual(len(result), 3)
self.assertEqual(result[0], 'ASA5505')
self.assertEqual(result[1], 'Firewall')
self.assertEqual(result[2], '192.168.199.4')
result = regex_utils.parse_line('Test Data', None)
self.assertEqual(result, None)
result = regex_utils.parse_line(None, 'Test Data')
self.assertEqual(result, 'Test Data')
if __name__ == '__main__':
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| ...
def test_check_line(self):
self.assertTrue(regex_utils.check_line('.*(\d+.\d+.\d+.\d+)', 'MyIP is 192.168.199.4'))
self.assertTrue(regex_utils.check_line('Test (Data|Case) For (py-text|py-task)', 'Test Data For py-text'))
self.assertFalse(regex_utils.check_line('.*(\d+.\d+.\d+.{100,255})', 'MyIP is 192.168.199.4'))
self.assertFalse(regex_utils.check_line(None, 'Test Word'))
self.assertFalse(regex_utils.check_line('.*', None))
...
def test_parse_line(self):
result = regex_utils.parse_line('name=(\S+), type=(\S+), ip=(\S+)', 'name=ASA5505, type=Firewall, ip=192.168.199.4')
self.assertEqual(len(result), 3)
self.assertEqual(result[0], 'ASA5505')
self.assertEqual(result[1], 'Firewall')
self.assertEqual(result[2], '192.168.199.4')
result = regex_utils.parse_line('Test Data', None)
self.assertEqual(result, None)
result = regex_utils.parse_line(None, 'Test Data')
self.assertEqual(result, 'Test Data')
... |
d1bd82008c21942dee0ed29ba6d4f9eb54f2af33 | issues/signals.py | issues/signals.py | from django.dispatch import Signal
#: Signal fired when a new issue is posted via the API.
issue_posted = Signal(providing_args=('request', 'issue'))
| from django.dispatch import Signal
#: Signal fired when a new issue is posted via the API.
issue_posted = Signal() # Provides arguments: ('request', 'issue')
| Remove documenting argument from Signal | Remove documenting argument from Signal
| Python | mit | 6aika/issue-reporting,6aika/issue-reporting,6aika/issue-reporting | from django.dispatch import Signal
#: Signal fired when a new issue is posted via the API.
- issue_posted = Signal(providing_args=('request', 'issue'))
+ issue_posted = Signal() # Provides arguments: ('request', 'issue')
| Remove documenting argument from Signal | ## Code Before:
from django.dispatch import Signal
#: Signal fired when a new issue is posted via the API.
issue_posted = Signal(providing_args=('request', 'issue'))
## Instruction:
Remove documenting argument from Signal
## Code After:
from django.dispatch import Signal
#: Signal fired when a new issue is posted via the API.
issue_posted = Signal() # Provides arguments: ('request', 'issue')
| // ... existing code ...
#: Signal fired when a new issue is posted via the API.
issue_posted = Signal() # Provides arguments: ('request', 'issue')
// ... rest of the code ... |
3b97e2eafaf8e2cdc2b39024f125c284a5f9de23 | tests/python-test-library/testcases/conf.py | tests/python-test-library/testcases/conf.py | contextSrcPath="."
sessionConfigPath="tests/python-test-library/stubs"
ctxBusName = "org.freedesktop.ContextKit"
ctxMgrPath = "/org/freedesktop/ContextKit/Manager"
ctxMgrIfce = "org.freedesktop.ContextKit.Manager"
ctxScriberIfce = "org.freedesktop.ContextKit.Subscriber"
mceBusName = "com.nokia.mce"
mceRqstPath = "/com/nokia/mce/request"
mceRqstIfce = "com.nokia.mce.request"
testBusName = "org.freedesktop.context.testing"
testRqstPath = "/org/freedesktop/context/testing/request"
testRqstIfce = "org.freedesktop.context.testing.request"
scriberOnePath = "/org/freedesktop/ContextKit/Subscribers/0"
scriberTwoPath = "/org/freedesktop/ContextKit/Subscribers/1"
scriberThirdPath = "/org/freedesktop/ContextKit/Subscribers/2"
properties = ['Context.Device.Orientation.facingUp','Context.Device.Orientation.edgeUp'] | contextSrcPath="."
sessionConfigPath="tests/python-test-library/stubs"
ctxBusName = "org.freedesktop.ContextKit"
ctxMgrPath = "/org/freedesktop/ContextKit/Manager"
ctxMgrIfce = "org.freedesktop.ContextKit.Manager"
ctxScriberIfce = "org.freedesktop.ContextKit.Subscriber"
mceBusName = "com.nokia.mce"
mceRqstPath = "/com/nokia/mce/request"
mceRqstIfce = "com.nokia.mce.request"
scriberBusName = "org.freedesktop.context.testing.subHandler"
scriberHandlerPath = "/org/freedesktop/context/testing/subHandler/request"
scriberHandlerIfce = "org.freedesktop.context.testing.subHandler.request"
scriberOnePath = "/org/freedesktop/ContextKit/Subscribers/0"
scriberTwoPath = "/org/freedesktop/ContextKit/Subscribers/1"
scriberThirdPath = "/org/freedesktop/ContextKit/Subscribers/2"
properties = ['Context.Device.Orientation.facingUp','Context.Device.Orientation.edgeUp'] | Modify subscription handler interface name | Modify subscription handler interface name
| Python | lgpl-2.1 | rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck | contextSrcPath="."
sessionConfigPath="tests/python-test-library/stubs"
ctxBusName = "org.freedesktop.ContextKit"
ctxMgrPath = "/org/freedesktop/ContextKit/Manager"
ctxMgrIfce = "org.freedesktop.ContextKit.Manager"
ctxScriberIfce = "org.freedesktop.ContextKit.Subscriber"
mceBusName = "com.nokia.mce"
mceRqstPath = "/com/nokia/mce/request"
mceRqstIfce = "com.nokia.mce.request"
- testBusName = "org.freedesktop.context.testing"
+ scriberBusName = "org.freedesktop.context.testing.subHandler"
- testRqstPath = "/org/freedesktop/context/testing/request"
+ scriberHandlerPath = "/org/freedesktop/context/testing/subHandler/request"
- testRqstIfce = "org.freedesktop.context.testing.request"
+ scriberHandlerIfce = "org.freedesktop.context.testing.subHandler.request"
scriberOnePath = "/org/freedesktop/ContextKit/Subscribers/0"
scriberTwoPath = "/org/freedesktop/ContextKit/Subscribers/1"
scriberThirdPath = "/org/freedesktop/ContextKit/Subscribers/2"
properties = ['Context.Device.Orientation.facingUp','Context.Device.Orientation.edgeUp'] | Modify subscription handler interface name | ## Code Before:
contextSrcPath="."
sessionConfigPath="tests/python-test-library/stubs"
ctxBusName = "org.freedesktop.ContextKit"
ctxMgrPath = "/org/freedesktop/ContextKit/Manager"
ctxMgrIfce = "org.freedesktop.ContextKit.Manager"
ctxScriberIfce = "org.freedesktop.ContextKit.Subscriber"
mceBusName = "com.nokia.mce"
mceRqstPath = "/com/nokia/mce/request"
mceRqstIfce = "com.nokia.mce.request"
testBusName = "org.freedesktop.context.testing"
testRqstPath = "/org/freedesktop/context/testing/request"
testRqstIfce = "org.freedesktop.context.testing.request"
scriberOnePath = "/org/freedesktop/ContextKit/Subscribers/0"
scriberTwoPath = "/org/freedesktop/ContextKit/Subscribers/1"
scriberThirdPath = "/org/freedesktop/ContextKit/Subscribers/2"
properties = ['Context.Device.Orientation.facingUp','Context.Device.Orientation.edgeUp']
## Instruction:
Modify subscription handler interface name
## Code After:
contextSrcPath="."
sessionConfigPath="tests/python-test-library/stubs"
ctxBusName = "org.freedesktop.ContextKit"
ctxMgrPath = "/org/freedesktop/ContextKit/Manager"
ctxMgrIfce = "org.freedesktop.ContextKit.Manager"
ctxScriberIfce = "org.freedesktop.ContextKit.Subscriber"
mceBusName = "com.nokia.mce"
mceRqstPath = "/com/nokia/mce/request"
mceRqstIfce = "com.nokia.mce.request"
scriberBusName = "org.freedesktop.context.testing.subHandler"
scriberHandlerPath = "/org/freedesktop/context/testing/subHandler/request"
scriberHandlerIfce = "org.freedesktop.context.testing.subHandler.request"
scriberOnePath = "/org/freedesktop/ContextKit/Subscribers/0"
scriberTwoPath = "/org/freedesktop/ContextKit/Subscribers/1"
scriberThirdPath = "/org/freedesktop/ContextKit/Subscribers/2"
properties = ['Context.Device.Orientation.facingUp','Context.Device.Orientation.edgeUp'] | ...
scriberBusName = "org.freedesktop.context.testing.subHandler"
scriberHandlerPath = "/org/freedesktop/context/testing/subHandler/request"
scriberHandlerIfce = "org.freedesktop.context.testing.subHandler.request"
... |
e9cb0bff470dc6bfc926f0b4ac6214ae8a028e61 | vcr/files.py | vcr/files.py | import os
import yaml
from .cassette import Cassette
def load_cassette(cassette_path):
try:
pc = yaml.load(open(cassette_path))
cassette = Cassette(pc)
return cassette
except IOError:
return None
def save_cassette(cassette_path, cassette):
dirname, filename = os.path.split(cassette_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(cassette_path, 'a') as cassette_file:
cassette_file.write(yaml.dump(cassette.serialize()))
| import os
import yaml
from .cassette import Cassette
# Use the libYAML versions if possible
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
def load_cassette(cassette_path):
try:
pc = yaml.load(open(cassette_path), Loader=Loader)
cassette = Cassette(pc)
return cassette
except IOError:
return None
def save_cassette(cassette_path, cassette):
dirname, filename = os.path.split(cassette_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(cassette_path, 'a') as cassette_file:
cassette_file.write(yaml.dump(cassette.serialize(), Dumper=Dumper))
| Use the libYAML version of yaml if it's available | Use the libYAML version of yaml if it's available
| Python | mit | ByteInternet/vcrpy,aclevy/vcrpy,ByteInternet/vcrpy,kevin1024/vcrpy,poussik/vcrpy,bcen/vcrpy,yarikoptic/vcrpy,agriffis/vcrpy,graingert/vcrpy,poussik/vcrpy,gwillem/vcrpy,mgeisler/vcrpy,kevin1024/vcrpy,IvanMalison/vcrpy,graingert/vcrpy | import os
import yaml
from .cassette import Cassette
+ # Use the libYAML versions if possible
+ try:
+ from yaml import CLoader as Loader, CDumper as Dumper
+ except ImportError:
+ from yaml import Loader, Dumper
+
def load_cassette(cassette_path):
try:
- pc = yaml.load(open(cassette_path))
+ pc = yaml.load(open(cassette_path), Loader=Loader)
cassette = Cassette(pc)
return cassette
except IOError:
return None
def save_cassette(cassette_path, cassette):
dirname, filename = os.path.split(cassette_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(cassette_path, 'a') as cassette_file:
- cassette_file.write(yaml.dump(cassette.serialize()))
+ cassette_file.write(yaml.dump(cassette.serialize(), Dumper=Dumper))
| Use the libYAML version of yaml if it's available | ## Code Before:
import os
import yaml
from .cassette import Cassette
def load_cassette(cassette_path):
try:
pc = yaml.load(open(cassette_path))
cassette = Cassette(pc)
return cassette
except IOError:
return None
def save_cassette(cassette_path, cassette):
dirname, filename = os.path.split(cassette_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(cassette_path, 'a') as cassette_file:
cassette_file.write(yaml.dump(cassette.serialize()))
## Instruction:
Use the libYAML version of yaml if it's available
## Code After:
import os
import yaml
from .cassette import Cassette
# Use the libYAML versions if possible
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
def load_cassette(cassette_path):
try:
pc = yaml.load(open(cassette_path), Loader=Loader)
cassette = Cassette(pc)
return cassette
except IOError:
return None
def save_cassette(cassette_path, cassette):
dirname, filename = os.path.split(cassette_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(cassette_path, 'a') as cassette_file:
cassette_file.write(yaml.dump(cassette.serialize(), Dumper=Dumper))
| // ... existing code ...
# Use the libYAML versions if possible
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
// ... modified code ...
try:
pc = yaml.load(open(cassette_path), Loader=Loader)
cassette = Cassette(pc)
...
with open(cassette_path, 'a') as cassette_file:
cassette_file.write(yaml.dump(cassette.serialize(), Dumper=Dumper))
// ... rest of the code ... |
dbe5e67d2685083769e7d154926e6a1a234fa3c4 | src/livestreamer/stream.py | src/livestreamer/stream.py | from livestreamer.utils import urlopen
import pbs
class StreamError(Exception):
pass
class Stream(object):
def open(self):
raise NotImplementedError
class RTMPStream(Stream):
def __init__(self, params):
self.params = params or {}
def open(self):
try:
rtmpdump = pbs.rtmpdump
except pbs.CommandNotFound:
raise StreamError("Unable to find 'rtmpdump' command")
self.params["flv"] = "-"
self.params["_bg"] = True
stream = rtmpdump(**self.params)
return stream.process.stdout
class HTTPStream(Stream):
def __init__(self, url):
self.url = url
def open(self):
return urlopen(self.url)
| from livestreamer.utils import urlopen
import os
import pbs
class StreamError(Exception):
pass
class Stream(object):
def open(self):
raise NotImplementedError
class RTMPStream(Stream):
def __init__(self, params):
self.params = params or {}
def open(self):
try:
rtmpdump = pbs.rtmpdump
except pbs.CommandNotFound:
raise StreamError("Unable to find 'rtmpdump' command")
self.params["flv"] = "-"
self.params["_bg"] = True
self.params["_err"] = open(os.devnull, "w")
stream = rtmpdump(**self.params)
return stream.process.stdout
class HTTPStream(Stream):
def __init__(self, url):
self.url = url
def open(self):
return urlopen(self.url)
| Fix rtmpdump locking up when stderr buffer is filled. | Fix rtmpdump locking up when stderr buffer is filled.
| Python | bsd-2-clause | charmander/livestreamer,sbstp/streamlink,wolftankk/livestreamer,bastimeyer/streamlink,caorong/livestreamer,breunigs/livestreamer,lyhiving/livestreamer,breunigs/livestreamer,okaywit/livestreamer,derrod/livestreamer,fishscene/streamlink,back-to/streamlink,streamlink/streamlink,wlerin/streamlink,melmorabity/streamlink,sbstp/streamlink,Dobatymo/livestreamer,streamlink/streamlink,back-to/streamlink,intact/livestreamer,Masaz-/livestreamer,ethanhlc/streamlink,charmander/livestreamer,blxd/livestreamer,programming086/livestreamer,blxd/livestreamer,derrod/livestreamer,caorong/livestreamer,flijloku/livestreamer,mmetak/streamlink,javiercantero/streamlink,lyhiving/livestreamer,melmorabity/streamlink,chhe/streamlink,Klaudit/livestreamer,Feverqwe/livestreamer,chhe/livestreamer,beardypig/streamlink,beardypig/streamlink,gravyboat/streamlink,Feverqwe/livestreamer,chhe/livestreamer,chrisnicholls/livestreamer,wlerin/streamlink,intact/livestreamer,bastimeyer/streamlink,wolftankk/livestreamer,chrippa/livestreamer,Saturn/livestreamer,chhe/streamlink,Dobatymo/livestreamer,programming086/livestreamer,gtmanfred/livestreamer,chrippa/livestreamer,asermax/livestreamer,mmetak/streamlink,hmit/livestreamer,gravyboat/streamlink,javiercantero/streamlink,Saturn/livestreamer,Klaudit/livestreamer,hmit/livestreamer,fishscene/streamlink,gtmanfred/livestreamer,jtsymon/livestreamer,ethanhlc/streamlink,Masaz-/livestreamer,okaywit/livestreamer,jtsymon/livestreamer,flijloku/livestreamer | from livestreamer.utils import urlopen
+ import os
import pbs
class StreamError(Exception):
pass
class Stream(object):
def open(self):
raise NotImplementedError
class RTMPStream(Stream):
def __init__(self, params):
self.params = params or {}
def open(self):
try:
rtmpdump = pbs.rtmpdump
except pbs.CommandNotFound:
raise StreamError("Unable to find 'rtmpdump' command")
self.params["flv"] = "-"
self.params["_bg"] = True
+ self.params["_err"] = open(os.devnull, "w")
stream = rtmpdump(**self.params)
return stream.process.stdout
class HTTPStream(Stream):
def __init__(self, url):
self.url = url
def open(self):
return urlopen(self.url)
| Fix rtmpdump locking up when stderr buffer is filled. | ## Code Before:
from livestreamer.utils import urlopen
import pbs
class StreamError(Exception):
pass
class Stream(object):
def open(self):
raise NotImplementedError
class RTMPStream(Stream):
def __init__(self, params):
self.params = params or {}
def open(self):
try:
rtmpdump = pbs.rtmpdump
except pbs.CommandNotFound:
raise StreamError("Unable to find 'rtmpdump' command")
self.params["flv"] = "-"
self.params["_bg"] = True
stream = rtmpdump(**self.params)
return stream.process.stdout
class HTTPStream(Stream):
def __init__(self, url):
self.url = url
def open(self):
return urlopen(self.url)
## Instruction:
Fix rtmpdump locking up when stderr buffer is filled.
## Code After:
from livestreamer.utils import urlopen
import os
import pbs
class StreamError(Exception):
pass
class Stream(object):
def open(self):
raise NotImplementedError
class RTMPStream(Stream):
def __init__(self, params):
self.params = params or {}
def open(self):
try:
rtmpdump = pbs.rtmpdump
except pbs.CommandNotFound:
raise StreamError("Unable to find 'rtmpdump' command")
self.params["flv"] = "-"
self.params["_bg"] = True
self.params["_err"] = open(os.devnull, "w")
stream = rtmpdump(**self.params)
return stream.process.stdout
class HTTPStream(Stream):
def __init__(self, url):
self.url = url
def open(self):
return urlopen(self.url)
| // ... existing code ...
import os
import pbs
// ... modified code ...
self.params["_bg"] = True
self.params["_err"] = open(os.devnull, "w")
// ... rest of the code ... |
cbae1dafb07fda5afcd0f2573c81b6eeb08e6e20 | dependencies.py | dependencies.py | import os, pkgutil, site
if pkgutil.find_loader("gi"):
try:
import gi
print('Found gi:', os.path.abspath(gi.__file__))
gi.require_version('Gst', '1.0')
# from gi.repository import GLib, Gst
except ValueError:
print('Couldn\'t find Gst')
print('Please run \'sudo apt-get install gir1.2-gstreamer-1.0\'')
print('Environment seems to be ok.')
else:
print('No gi installed', '\n',
'Please run \'sudo apt-get install python3-gi\'',
'\n',
'A virtual environment might need extra actions like symlinking, ',
'\n',
'you might need to do a symlink looking similar to this:',
'\n',
'ln -s /usr/lib/python3/dist-packages/gi ',
'/srv/homeassistant/lib/python3.4/site-packages',
'\n',
'run this script inside and outside of the virtual environment to find the paths needed')
print(site.getsitepackages()) | import os
import pkgutil
import site
if pkgutil.find_loader("gi"):
try:
import gi
print('Found gi:', os.path.abspath(gi.__file__))
gi.require_version('Gst', '1.0')
# from gi.repository import GLib, Gst
except ValueError:
print('Couldn\'t find Gst')
print('Please run \'sudo apt-get install gir1.2-gstreamer-1.0\'')
return False
print('Environment seems to be ok.')
else:
print('No gi installed', '\n',
'Please run \'sudo apt-get install python3-gi\'',
'\n',
'A virtual environment might need extra actions like symlinking, ',
'\n',
'you might need to do a symlink looking similar to this:',
'\n',
'ln -s /usr/lib/python3/dist-packages/gi ',
'/srv/homeassistant/lib/python3.4/site-packages',
'\n',
'run this script inside and outside of the virtual environment to find the paths needed')
print(site.getsitepackages()) | Exit program if exception is raised | Exit program if exception is raised
| Python | mit | Kane610/axis | - import os, pkgutil, site
+ import os
+ import pkgutil
+ import site
if pkgutil.find_loader("gi"):
try:
import gi
print('Found gi:', os.path.abspath(gi.__file__))
gi.require_version('Gst', '1.0')
# from gi.repository import GLib, Gst
except ValueError:
print('Couldn\'t find Gst')
print('Please run \'sudo apt-get install gir1.2-gstreamer-1.0\'')
+ return False
print('Environment seems to be ok.')
else:
print('No gi installed', '\n',
'Please run \'sudo apt-get install python3-gi\'',
'\n',
'A virtual environment might need extra actions like symlinking, ',
'\n',
'you might need to do a symlink looking similar to this:',
'\n',
'ln -s /usr/lib/python3/dist-packages/gi ',
'/srv/homeassistant/lib/python3.4/site-packages',
'\n',
'run this script inside and outside of the virtual environment to find the paths needed')
print(site.getsitepackages()) | Exit program if exception is raised | ## Code Before:
import os, pkgutil, site
if pkgutil.find_loader("gi"):
try:
import gi
print('Found gi:', os.path.abspath(gi.__file__))
gi.require_version('Gst', '1.0')
# from gi.repository import GLib, Gst
except ValueError:
print('Couldn\'t find Gst')
print('Please run \'sudo apt-get install gir1.2-gstreamer-1.0\'')
print('Environment seems to be ok.')
else:
print('No gi installed', '\n',
'Please run \'sudo apt-get install python3-gi\'',
'\n',
'A virtual environment might need extra actions like symlinking, ',
'\n',
'you might need to do a symlink looking similar to this:',
'\n',
'ln -s /usr/lib/python3/dist-packages/gi ',
'/srv/homeassistant/lib/python3.4/site-packages',
'\n',
'run this script inside and outside of the virtual environment to find the paths needed')
print(site.getsitepackages())
## Instruction:
Exit program if exception is raised
## Code After:
import os
import pkgutil
import site
if pkgutil.find_loader("gi"):
try:
import gi
print('Found gi:', os.path.abspath(gi.__file__))
gi.require_version('Gst', '1.0')
# from gi.repository import GLib, Gst
except ValueError:
print('Couldn\'t find Gst')
print('Please run \'sudo apt-get install gir1.2-gstreamer-1.0\'')
return False
print('Environment seems to be ok.')
else:
print('No gi installed', '\n',
'Please run \'sudo apt-get install python3-gi\'',
'\n',
'A virtual environment might need extra actions like symlinking, ',
'\n',
'you might need to do a symlink looking similar to this:',
'\n',
'ln -s /usr/lib/python3/dist-packages/gi ',
'/srv/homeassistant/lib/python3.4/site-packages',
'\n',
'run this script inside and outside of the virtual environment to find the paths needed')
print(site.getsitepackages()) | # ... existing code ...
import os
import pkgutil
import site
# ... modified code ...
print('Please run \'sudo apt-get install gir1.2-gstreamer-1.0\'')
return False
print('Environment seems to be ok.')
# ... rest of the code ... |
a5f60d664e7758b113abc31b405657952dd5eccd | tests/conftest.py | tests/conftest.py | import os
import pytest
from pywatson.watson import Watson
@pytest.fixture
def config():
"""Get Watson configuration from the environment
:return: dict with keys 'url', 'username', and 'password'
"""
try:
return {
'url': os.environ['WATSON_URL'],
'username': os.environ['WATSON_USERNAME'],
'password': os.environ['WATSON_PASSWORD']
}
except KeyError as err:
raise Exception('You must set the environment variable {}'.format(err.args[0]))
@pytest.fixture
def watson(config):
return Watson(url=config['url'], username=config['username'], password=config['password'])
| import json
import os
import pytest
from pywatson.watson import Watson
@pytest.fixture
def config():
"""Get Watson configuration from the environment
:return: dict with keys 'url', 'username', and 'password'
"""
try:
return {
'url': os.environ['WATSON_URL'],
'username': os.environ['WATSON_USERNAME'],
'password': os.environ['WATSON_PASSWORD']
}
except KeyError as err:
raise Exception('You must set the environment variable {}'.format(err.args[0]))
@pytest.fixture
def watson(config):
return Watson(url=config['url'], username=config['username'], password=config['password'])
@pytest.fixture
def questions():
qs = []
for root, dirs, files in os.walk('tests/json/questions'):
for filename in files:
filepath = os.path.join(root, filename)
try:
qs.append(json.load(open(filepath)))
except ValueError:
raise ValueError('Expected {} to contain valid JSON'.format(filepath))
return qs
| Implement test data JSON loader | Implement test data JSON loader
| Python | mit | sherlocke/pywatson | + import json
import os
import pytest
from pywatson.watson import Watson
@pytest.fixture
def config():
"""Get Watson configuration from the environment
:return: dict with keys 'url', 'username', and 'password'
"""
try:
return {
'url': os.environ['WATSON_URL'],
'username': os.environ['WATSON_USERNAME'],
'password': os.environ['WATSON_PASSWORD']
}
except KeyError as err:
raise Exception('You must set the environment variable {}'.format(err.args[0]))
@pytest.fixture
def watson(config):
return Watson(url=config['url'], username=config['username'], password=config['password'])
+
+ @pytest.fixture
+ def questions():
+ qs = []
+
+ for root, dirs, files in os.walk('tests/json/questions'):
+ for filename in files:
+ filepath = os.path.join(root, filename)
+ try:
+ qs.append(json.load(open(filepath)))
+ except ValueError:
+ raise ValueError('Expected {} to contain valid JSON'.format(filepath))
+
+ return qs
+ | Implement test data JSON loader | ## Code Before:
import os
import pytest
from pywatson.watson import Watson
@pytest.fixture
def config():
"""Get Watson configuration from the environment
:return: dict with keys 'url', 'username', and 'password'
"""
try:
return {
'url': os.environ['WATSON_URL'],
'username': os.environ['WATSON_USERNAME'],
'password': os.environ['WATSON_PASSWORD']
}
except KeyError as err:
raise Exception('You must set the environment variable {}'.format(err.args[0]))
@pytest.fixture
def watson(config):
return Watson(url=config['url'], username=config['username'], password=config['password'])
## Instruction:
Implement test data JSON loader
## Code After:
import json
import os
import pytest
from pywatson.watson import Watson
@pytest.fixture
def config():
"""Get Watson configuration from the environment
:return: dict with keys 'url', 'username', and 'password'
"""
try:
return {
'url': os.environ['WATSON_URL'],
'username': os.environ['WATSON_USERNAME'],
'password': os.environ['WATSON_PASSWORD']
}
except KeyError as err:
raise Exception('You must set the environment variable {}'.format(err.args[0]))
@pytest.fixture
def watson(config):
return Watson(url=config['url'], username=config['username'], password=config['password'])
@pytest.fixture
def questions():
qs = []
for root, dirs, files in os.walk('tests/json/questions'):
for filename in files:
filepath = os.path.join(root, filename)
try:
qs.append(json.load(open(filepath)))
except ValueError:
raise ValueError('Expected {} to contain valid JSON'.format(filepath))
return qs
| // ... existing code ...
import json
import os
// ... modified code ...
return Watson(url=config['url'], username=config['username'], password=config['password'])
@pytest.fixture
def questions():
qs = []
for root, dirs, files in os.walk('tests/json/questions'):
for filename in files:
filepath = os.path.join(root, filename)
try:
qs.append(json.load(open(filepath)))
except ValueError:
raise ValueError('Expected {} to contain valid JSON'.format(filepath))
return qs
// ... rest of the code ... |
0fbd183a95c65eb80bb813368eeb045e9c43b630 | ray/util.py | ray/util.py | import json
import itertools as it
all_sizes = [0.7, 1.0, 1.6, 3.5, 5.0]
all_types = ['Color', 'Texture', 'Edge', 'Orientation']
full_feature_set = list(it.product(all_types, all_sizes))
default_feature_set = list(it.product(all_types[:-1], all_sizes[1:-1]))
def write_segmentation_pipeline_json(jsonfn, ilfn, ilbfn, outdir='.'):
d = {}
d['images'] = [{'name': ilbfn}]
d['session'] = ilfn
d['output_dir'] = outdir
d['features'] = default_feature_set
with open(jsonfn, 'w') as f:
json.dump(d, f)
| import json
import itertools as it
all_sizes = [0.7, 1.0, 1.6, 3.5, 5.0]
all_types = ['Color', 'Texture', 'Edge', 'Orientation']
full_feature_set = list(it.product(all_types, all_sizes))
default_feature_set = list(it.product(all_types[:-1], all_sizes[1:-1]))
def write_segmentation_pipeline_json(jsonfn, ilfn, ilbfns, outdir='.'):
if isinstance(ilbfns, str) or isinstance(ilbfns, unicode):
ilbfns = [ilbfns]
d = {}
d['images'] = [{'name': ilbfn} for ilbfn in ilbfns]
d['session'] = ilfn
d['output_dir'] = outdir
d['features'] = default_feature_set
with open(jsonfn, 'w') as f:
json.dump(d, f)
| Allow multiple batch files for seg pipeline json | Allow multiple batch files for seg pipeline json
| Python | bsd-3-clause | janelia-flyem/gala,jni/gala,jni/ray | import json
import itertools as it
all_sizes = [0.7, 1.0, 1.6, 3.5, 5.0]
all_types = ['Color', 'Texture', 'Edge', 'Orientation']
full_feature_set = list(it.product(all_types, all_sizes))
default_feature_set = list(it.product(all_types[:-1], all_sizes[1:-1]))
- def write_segmentation_pipeline_json(jsonfn, ilfn, ilbfn, outdir='.'):
+ def write_segmentation_pipeline_json(jsonfn, ilfn, ilbfns, outdir='.'):
+ if isinstance(ilbfns, str) or isinstance(ilbfns, unicode):
+ ilbfns = [ilbfns]
d = {}
- d['images'] = [{'name': ilbfn}]
+ d['images'] = [{'name': ilbfn} for ilbfn in ilbfns]
d['session'] = ilfn
d['output_dir'] = outdir
d['features'] = default_feature_set
with open(jsonfn, 'w') as f:
json.dump(d, f)
| Allow multiple batch files for seg pipeline json | ## Code Before:
import json
import itertools as it
all_sizes = [0.7, 1.0, 1.6, 3.5, 5.0]
all_types = ['Color', 'Texture', 'Edge', 'Orientation']
full_feature_set = list(it.product(all_types, all_sizes))
default_feature_set = list(it.product(all_types[:-1], all_sizes[1:-1]))
def write_segmentation_pipeline_json(jsonfn, ilfn, ilbfn, outdir='.'):
d = {}
d['images'] = [{'name': ilbfn}]
d['session'] = ilfn
d['output_dir'] = outdir
d['features'] = default_feature_set
with open(jsonfn, 'w') as f:
json.dump(d, f)
## Instruction:
Allow multiple batch files for seg pipeline json
## Code After:
import json
import itertools as it
all_sizes = [0.7, 1.0, 1.6, 3.5, 5.0]
all_types = ['Color', 'Texture', 'Edge', 'Orientation']
full_feature_set = list(it.product(all_types, all_sizes))
default_feature_set = list(it.product(all_types[:-1], all_sizes[1:-1]))
def write_segmentation_pipeline_json(jsonfn, ilfn, ilbfns, outdir='.'):
if isinstance(ilbfns, str) or isinstance(ilbfns, unicode):
ilbfns = [ilbfns]
d = {}
d['images'] = [{'name': ilbfn} for ilbfn in ilbfns]
d['session'] = ilfn
d['output_dir'] = outdir
d['features'] = default_feature_set
with open(jsonfn, 'w') as f:
json.dump(d, f)
| # ... existing code ...
def write_segmentation_pipeline_json(jsonfn, ilfn, ilbfns, outdir='.'):
if isinstance(ilbfns, str) or isinstance(ilbfns, unicode):
ilbfns = [ilbfns]
d = {}
d['images'] = [{'name': ilbfn} for ilbfn in ilbfns]
d['session'] = ilfn
# ... rest of the code ... |
7d1463fc732cdc6aef3299c6d2bbe916418e6d6e | hkisaml/api.py | hkisaml/api.py | from django.contrib.auth.models import User
from rest_framework import permissions, routers, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
class UserSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
ret = super(UserSerializer, self).to_representation(obj)
if hasattr(obj, 'profile'):
ret['department_name'] = obj.profile.department_name
return ret
class Meta:
fields = [
'last_login', 'username', 'email', 'date_joined',
'first_name', 'last_name'
]
model = User
# ViewSets define the view behavior.
class UserView(generics.RetrieveAPIView,
mixins.RetrieveModelMixin):
def get_queryset(self):
user = self.request.user
if user.is_superuser:
return self.queryset
else:
return self.queryset.filter(id=user.id)
def get_object(self):
username = self.kwargs.get('username', None)
if username:
qs = self.get_queryset()
obj = generics.get_object_or_404(qs, username=username)
else:
obj = self.request.user
return obj
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = User.objects.all()
serializer_class = UserSerializer
#router = routers.DefaultRouter()
#router.register(r'users', UserViewSet)
| from django.contrib.auth.models import User
from rest_framework import permissions, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
class UserSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
ret = super(UserSerializer, self).to_representation(obj)
if hasattr(obj, 'profile'):
ret['department_name'] = obj.profile.department_name
if obj.first_name and obj.last_name:
ret['full_name'] = '%s %s' % (obj.first_name, obj.last_name)
return ret
class Meta:
fields = [
'last_login', 'username', 'email', 'date_joined',
'first_name', 'last_name'
]
model = User
# ViewSets define the view behavior.
class UserView(generics.RetrieveAPIView,
mixins.RetrieveModelMixin):
def get_queryset(self):
user = self.request.user
if user.is_superuser:
return self.queryset
else:
return self.queryset.filter(id=user.id)
def get_object(self):
username = self.kwargs.get('username', None)
if username:
qs = self.get_queryset()
obj = generics.get_object_or_404(qs, username=username)
else:
obj = self.request.user
return obj
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = User.objects.all()
serializer_class = UserSerializer
#router = routers.DefaultRouter()
#router.register(r'users', UserViewSet)
| Add full_name field to API | Add full_name field to API
| Python | mit | mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo | from django.contrib.auth.models import User
- from rest_framework import permissions, routers, serializers, generics, mixins
+ from rest_framework import permissions, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
class UserSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
ret = super(UserSerializer, self).to_representation(obj)
if hasattr(obj, 'profile'):
ret['department_name'] = obj.profile.department_name
+ if obj.first_name and obj.last_name:
+ ret['full_name'] = '%s %s' % (obj.first_name, obj.last_name)
return ret
class Meta:
fields = [
'last_login', 'username', 'email', 'date_joined',
'first_name', 'last_name'
]
model = User
# ViewSets define the view behavior.
class UserView(generics.RetrieveAPIView,
mixins.RetrieveModelMixin):
def get_queryset(self):
user = self.request.user
if user.is_superuser:
return self.queryset
else:
return self.queryset.filter(id=user.id)
def get_object(self):
username = self.kwargs.get('username', None)
if username:
qs = self.get_queryset()
obj = generics.get_object_or_404(qs, username=username)
else:
obj = self.request.user
return obj
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = User.objects.all()
serializer_class = UserSerializer
#router = routers.DefaultRouter()
#router.register(r'users', UserViewSet)
| Add full_name field to API | ## Code Before:
from django.contrib.auth.models import User
from rest_framework import permissions, routers, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
class UserSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
ret = super(UserSerializer, self).to_representation(obj)
if hasattr(obj, 'profile'):
ret['department_name'] = obj.profile.department_name
return ret
class Meta:
fields = [
'last_login', 'username', 'email', 'date_joined',
'first_name', 'last_name'
]
model = User
# ViewSets define the view behavior.
class UserView(generics.RetrieveAPIView,
mixins.RetrieveModelMixin):
def get_queryset(self):
user = self.request.user
if user.is_superuser:
return self.queryset
else:
return self.queryset.filter(id=user.id)
def get_object(self):
username = self.kwargs.get('username', None)
if username:
qs = self.get_queryset()
obj = generics.get_object_or_404(qs, username=username)
else:
obj = self.request.user
return obj
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = User.objects.all()
serializer_class = UserSerializer
#router = routers.DefaultRouter()
#router.register(r'users', UserViewSet)
## Instruction:
Add full_name field to API
## Code After:
from django.contrib.auth.models import User
from rest_framework import permissions, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
class UserSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
ret = super(UserSerializer, self).to_representation(obj)
if hasattr(obj, 'profile'):
ret['department_name'] = obj.profile.department_name
if obj.first_name and obj.last_name:
ret['full_name'] = '%s %s' % (obj.first_name, obj.last_name)
return ret
class Meta:
fields = [
'last_login', 'username', 'email', 'date_joined',
'first_name', 'last_name'
]
model = User
# ViewSets define the view behavior.
class UserView(generics.RetrieveAPIView,
mixins.RetrieveModelMixin):
def get_queryset(self):
user = self.request.user
if user.is_superuser:
return self.queryset
else:
return self.queryset.filter(id=user.id)
def get_object(self):
username = self.kwargs.get('username', None)
if username:
qs = self.get_queryset()
obj = generics.get_object_or_404(qs, username=username)
else:
obj = self.request.user
return obj
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = User.objects.all()
serializer_class = UserSerializer
#router = routers.DefaultRouter()
#router.register(r'users', UserViewSet)
| // ... existing code ...
from django.contrib.auth.models import User
from rest_framework import permissions, serializers, generics, mixins
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
// ... modified code ...
ret['department_name'] = obj.profile.department_name
if obj.first_name and obj.last_name:
ret['full_name'] = '%s %s' % (obj.first_name, obj.last_name)
return ret
// ... rest of the code ... |
9e27c8f803c42e65ec333ed1679ea70a5618f3c6 | dunya/test_settings.py | dunya/test_settings.py | from settings import *
if "motif" in DATABASES:
del DATABASES["motif"]
TEST_RUNNER = "xmlrunner.extra.djangotestrunner.XMLTestRunner"
TEST_OUTPUT_VERBOSE = True
TEST_OUTPUT_DESCRIPTIONS = True
TEST_OUTPUT_DIR = "xmlrunner"
| from settings import *
if "motif" in DATABASES:
del DATABASES["motif"]
from xmlrunner.extra.djangotestrunner import XMLTestRunner
from django.test.runner import DiscoverRunner
from django.db import connections, DEFAULT_DB_ALIAS
# We use the XMLTestRunner on CI
class DunyaTestRunner(XMLTestRunner):
#class DunyaTestRunner(DiscoverRunner):
def setup_databases(self):
result = super(DunyaTestRunner, self).setup_databases()
connection = connections[DEFAULT_DB_ALIAS]
cursor = connection.cursor()
cursor.execute('CREATE EXTENSION IF NOT EXISTS UNACCENT')
return result
TEST_RUNNER = "dunya.test_settings.DunyaTestRunner"
TEST_OUTPUT_VERBOSE = True
TEST_OUTPUT_DESCRIPTIONS = True
TEST_OUTPUT_DIR = "xmlrunner"
| Update test settings to create the unaccent ext if needed | Update test settings to create the unaccent ext if needed
| Python | agpl-3.0 | MTG/dunya,MTG/dunya,MTG/dunya,MTG/dunya | from settings import *
if "motif" in DATABASES:
del DATABASES["motif"]
- TEST_RUNNER = "xmlrunner.extra.djangotestrunner.XMLTestRunner"
+ from xmlrunner.extra.djangotestrunner import XMLTestRunner
+ from django.test.runner import DiscoverRunner
+ from django.db import connections, DEFAULT_DB_ALIAS
+
+ # We use the XMLTestRunner on CI
+ class DunyaTestRunner(XMLTestRunner):
+ #class DunyaTestRunner(DiscoverRunner):
+ def setup_databases(self):
+ result = super(DunyaTestRunner, self).setup_databases()
+ connection = connections[DEFAULT_DB_ALIAS]
+ cursor = connection.cursor()
+ cursor.execute('CREATE EXTENSION IF NOT EXISTS UNACCENT')
+ return result
+
+ TEST_RUNNER = "dunya.test_settings.DunyaTestRunner"
TEST_OUTPUT_VERBOSE = True
TEST_OUTPUT_DESCRIPTIONS = True
TEST_OUTPUT_DIR = "xmlrunner"
| Update test settings to create the unaccent ext if needed | ## Code Before:
from settings import *
if "motif" in DATABASES:
del DATABASES["motif"]
TEST_RUNNER = "xmlrunner.extra.djangotestrunner.XMLTestRunner"
TEST_OUTPUT_VERBOSE = True
TEST_OUTPUT_DESCRIPTIONS = True
TEST_OUTPUT_DIR = "xmlrunner"
## Instruction:
Update test settings to create the unaccent ext if needed
## Code After:
from settings import *
if "motif" in DATABASES:
del DATABASES["motif"]
from xmlrunner.extra.djangotestrunner import XMLTestRunner
from django.test.runner import DiscoverRunner
from django.db import connections, DEFAULT_DB_ALIAS
# We use the XMLTestRunner on CI
class DunyaTestRunner(XMLTestRunner):
#class DunyaTestRunner(DiscoverRunner):
def setup_databases(self):
result = super(DunyaTestRunner, self).setup_databases()
connection = connections[DEFAULT_DB_ALIAS]
cursor = connection.cursor()
cursor.execute('CREATE EXTENSION IF NOT EXISTS UNACCENT')
return result
TEST_RUNNER = "dunya.test_settings.DunyaTestRunner"
TEST_OUTPUT_VERBOSE = True
TEST_OUTPUT_DESCRIPTIONS = True
TEST_OUTPUT_DIR = "xmlrunner"
| # ... existing code ...
from xmlrunner.extra.djangotestrunner import XMLTestRunner
from django.test.runner import DiscoverRunner
from django.db import connections, DEFAULT_DB_ALIAS
# We use the XMLTestRunner on CI
class DunyaTestRunner(XMLTestRunner):
#class DunyaTestRunner(DiscoverRunner):
def setup_databases(self):
result = super(DunyaTestRunner, self).setup_databases()
connection = connections[DEFAULT_DB_ALIAS]
cursor = connection.cursor()
cursor.execute('CREATE EXTENSION IF NOT EXISTS UNACCENT')
return result
TEST_RUNNER = "dunya.test_settings.DunyaTestRunner"
TEST_OUTPUT_VERBOSE = True
# ... rest of the code ... |
c9229922772a4d7f92a26786d6ea441609043a09 | tests/CrawlerRunner/ip_address.py | tests/CrawlerRunner/ip_address.py | from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
| from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
if __name__ == "__main__":
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
| Move code inside __main__ block | Tests: Move code inside __main__ block
| Python | bsd-3-clause | starrify/scrapy,scrapy/scrapy,starrify/scrapy,starrify/scrapy,elacuesta/scrapy,elacuesta/scrapy,pablohoffman/scrapy,pablohoffman/scrapy,pawelmhm/scrapy,pawelmhm/scrapy,dangra/scrapy,dangra/scrapy,scrapy/scrapy,pawelmhm/scrapy,pablohoffman/scrapy,dangra/scrapy,elacuesta/scrapy,scrapy/scrapy | from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
+ if __name__ == "__main__":
- with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
+ with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
- port = urlparse(mock_http_server.http_address).port
+ port = urlparse(mock_http_server.http_address).port
- url = "http://not.a.real.domain:{port}/echo".format(port=port)
+ url = "http://not.a.real.domain:{port}/echo".format(port=port)
- servers = [(mock_dns_server.host, mock_dns_server.port)]
+ servers = [(mock_dns_server.host, mock_dns_server.port)]
- reactor.installResolver(createResolver(servers=servers))
+ reactor.installResolver(createResolver(servers=servers))
- configure_logging()
+ configure_logging()
- runner = CrawlerRunner()
+ runner = CrawlerRunner()
- d = runner.crawl(LocalhostSpider, url=url)
+ d = runner.crawl(LocalhostSpider, url=url)
- d.addBoth(lambda _: reactor.stop())
+ d.addBoth(lambda _: reactor.stop())
- reactor.run()
+ reactor.run()
| Move code inside __main__ block | ## Code Before:
from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
## Instruction:
Move code inside __main__ block
## Code After:
from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
if __name__ == "__main__":
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
| // ... existing code ...
if __name__ == "__main__":
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
// ... rest of the code ... |
797e9f3e4fad744e9211c07067992c245a344fb5 | tests/test_whatcd.py | tests/test_whatcd.py | from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase, use_vcr
class TestInputWhatCD(FlexGetBase):
__yaml__ = """
tasks:
no_fields:
whatcd:
no_user:
whatcd:
password: test
no_pass:
whatcd:
username: test
"""
def test_missing_fields(self):
self.execute_task('no_fields', abort_ok=True)
assert self.task.aborted, 'Task not aborted with no fields present'
self.execute_task('no_user', abort_ok=True)
assert self.task.aborted, 'Task not aborted with no username'
self.execute_task('no_pass', abort_ok=True)
assert self.task.aborted, 'Task not aborted with no password'
class TestWhatCDOnline(FlexGetBase):
__yaml__ = """
tasks:
badlogin:
whatcd:
username: invalid
password: invalid
"""
@use_vcr
def test_invalid_login(self):
self.execute_task("badlogin", abort_ok=True)
assert self.task.aborted, 'Task not aborted with invalid login credentials'
| from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase, use_vcr
class TestWhatCDOnline(FlexGetBase):
__yaml__ = """
tasks:
badlogin:
whatcd:
username: invalid
password: invalid
"""
@use_vcr
def test_invalid_login(self):
self.execute_task("badlogin", abort_ok=True)
assert self.task.aborted, 'Task not aborted with invalid login credentials'
| Remove schema validation unit tests frow whatcd | Remove schema validation unit tests frow whatcd
| Python | mit | JorisDeRieck/Flexget,Danfocus/Flexget,qk4l/Flexget,Flexget/Flexget,JorisDeRieck/Flexget,qk4l/Flexget,ianstalk/Flexget,dsemi/Flexget,oxc/Flexget,crawln45/Flexget,qvazzler/Flexget,Flexget/Flexget,sean797/Flexget,oxc/Flexget,Flexget/Flexget,dsemi/Flexget,drwyrm/Flexget,OmgOhnoes/Flexget,drwyrm/Flexget,jacobmetrick/Flexget,jawilson/Flexget,malkavi/Flexget,crawln45/Flexget,qvazzler/Flexget,malkavi/Flexget,tarzasai/Flexget,cvium/Flexget,drwyrm/Flexget,jawilson/Flexget,LynxyssCZ/Flexget,lildadou/Flexget,cvium/Flexget,lildadou/Flexget,Pretagonist/Flexget,LynxyssCZ/Flexget,tobinjt/Flexget,poulpito/Flexget,JorisDeRieck/Flexget,LynxyssCZ/Flexget,jacobmetrick/Flexget,poulpito/Flexget,jacobmetrick/Flexget,Pretagonist/Flexget,antivirtel/Flexget,tsnoam/Flexget,Danfocus/Flexget,tobinjt/Flexget,Pretagonist/Flexget,tsnoam/Flexget,gazpachoking/Flexget,qk4l/Flexget,antivirtel/Flexget,tarzasai/Flexget,lildadou/Flexget,ianstalk/Flexget,poulpito/Flexget,tobinjt/Flexget,jawilson/Flexget,Danfocus/Flexget,Flexget/Flexget,JorisDeRieck/Flexget,oxc/Flexget,OmgOhnoes/Flexget,antivirtel/Flexget,OmgOhnoes/Flexget,jawilson/Flexget,gazpachoking/Flexget,crawln45/Flexget,cvium/Flexget,qvazzler/Flexget,tarzasai/Flexget,LynxyssCZ/Flexget,malkavi/Flexget,crawln45/Flexget,malkavi/Flexget,sean797/Flexget,tsnoam/Flexget,dsemi/Flexget,Danfocus/Flexget,sean797/Flexget,tobinjt/Flexget,ianstalk/Flexget | from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase, use_vcr
-
-
- class TestInputWhatCD(FlexGetBase):
-
- __yaml__ = """
- tasks:
- no_fields:
- whatcd:
- no_user:
- whatcd:
- password: test
- no_pass:
- whatcd:
- username: test
- """
-
- def test_missing_fields(self):
- self.execute_task('no_fields', abort_ok=True)
- assert self.task.aborted, 'Task not aborted with no fields present'
- self.execute_task('no_user', abort_ok=True)
- assert self.task.aborted, 'Task not aborted with no username'
- self.execute_task('no_pass', abort_ok=True)
- assert self.task.aborted, 'Task not aborted with no password'
class TestWhatCDOnline(FlexGetBase):
__yaml__ = """
tasks:
badlogin:
whatcd:
username: invalid
password: invalid
"""
@use_vcr
def test_invalid_login(self):
self.execute_task("badlogin", abort_ok=True)
assert self.task.aborted, 'Task not aborted with invalid login credentials'
| Remove schema validation unit tests frow whatcd | ## Code Before:
from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase, use_vcr
class TestInputWhatCD(FlexGetBase):
__yaml__ = """
tasks:
no_fields:
whatcd:
no_user:
whatcd:
password: test
no_pass:
whatcd:
username: test
"""
def test_missing_fields(self):
self.execute_task('no_fields', abort_ok=True)
assert self.task.aborted, 'Task not aborted with no fields present'
self.execute_task('no_user', abort_ok=True)
assert self.task.aborted, 'Task not aborted with no username'
self.execute_task('no_pass', abort_ok=True)
assert self.task.aborted, 'Task not aborted with no password'
class TestWhatCDOnline(FlexGetBase):
__yaml__ = """
tasks:
badlogin:
whatcd:
username: invalid
password: invalid
"""
@use_vcr
def test_invalid_login(self):
self.execute_task("badlogin", abort_ok=True)
assert self.task.aborted, 'Task not aborted with invalid login credentials'
## Instruction:
Remove schema validation unit tests frow whatcd
## Code After:
from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase, use_vcr
class TestWhatCDOnline(FlexGetBase):
__yaml__ = """
tasks:
badlogin:
whatcd:
username: invalid
password: invalid
"""
@use_vcr
def test_invalid_login(self):
self.execute_task("badlogin", abort_ok=True)
assert self.task.aborted, 'Task not aborted with invalid login credentials'
| ...
from tests import FlexGetBase, use_vcr
... |
f5bb9e5f388c4ac222da2318638266fdfbe925f0 | beam/vendor.py | beam/vendor.py | from __future__ import unicode_literals
import six
@six.python_2_unicode_compatible
class Vendor(object):
"""
Represents a VPS provider.
"""
def __init__(self, name, endpoint):
"""
Initialise a new vendor object.
:param name: The name of the vendor, e.g. "RamNode".
:param endpoint: The hostname of the SolusVM control panel, with
protocol.
"""
self.name = name
self.endpoint = endpoint
def __hash__(self):
"""
Retrieve a hash value for this object.
:return: This object's hash. Identical objects will have an identical
hash.
"""
return hash(self.name)
def __eq__(self, other):
"""
Test whether this vendor is identical to another.
:param other: The object to compare to this one.
:return: True if the objects are identical, false otherwise.
"""
return isinstance(other, self.__class__) and other.name == self.name
def __str__(self):
"""
Generate a human-readable string representation of this vendor.
:return: This host as a friendly string.
"""
return '{0}({1}, {2})'.format(self.__class__.__name__,
self.name,
self.endpoint)
| from __future__ import unicode_literals
import six
@six.python_2_unicode_compatible
class Vendor(object):
"""
Represents a VPS provider.
"""
def __init__(self, name, endpoint):
"""
Initialise a new vendor object.
:param name: The name of the vendor, e.g. "RamNode".
:param endpoint: The hostname of the SolusVM control panel, with
protocol.
"""
self.name = name
""" The vendor's name, e.g. "RamNode". """
self.endpoint = endpoint
""" The hostname of the SolusVM control panel, with protocol. """
def __hash__(self):
"""
Retrieve a hash value for this object.
:return: This object's hash. Identical objects will have an identical
hash.
"""
return hash(self.name)
def __eq__(self, other):
"""
Test whether this vendor is identical to another.
:param other: The object to compare to this one.
:return: True if the objects are identical, false otherwise.
"""
return isinstance(other, self.__class__) and other.name == self.name
def __str__(self):
"""
Generate a human-readable string representation of this vendor.
:return: This host as a friendly string.
"""
return '{0}({1}, {2})'.format(self.__class__.__name__,
self.name,
self.endpoint)
| Add documentation to Vendor properties | Add documentation to Vendor properties
| Python | mit | gebn/beam,gebn/beam | from __future__ import unicode_literals
import six
@six.python_2_unicode_compatible
class Vendor(object):
"""
Represents a VPS provider.
"""
def __init__(self, name, endpoint):
"""
Initialise a new vendor object.
:param name: The name of the vendor, e.g. "RamNode".
:param endpoint: The hostname of the SolusVM control panel, with
protocol.
"""
self.name = name
+ """ The vendor's name, e.g. "RamNode". """
self.endpoint = endpoint
+ """ The hostname of the SolusVM control panel, with protocol. """
def __hash__(self):
"""
Retrieve a hash value for this object.
:return: This object's hash. Identical objects will have an identical
hash.
"""
return hash(self.name)
def __eq__(self, other):
"""
Test whether this vendor is identical to another.
:param other: The object to compare to this one.
:return: True if the objects are identical, false otherwise.
"""
return isinstance(other, self.__class__) and other.name == self.name
def __str__(self):
"""
Generate a human-readable string representation of this vendor.
:return: This host as a friendly string.
"""
return '{0}({1}, {2})'.format(self.__class__.__name__,
self.name,
self.endpoint)
| Add documentation to Vendor properties | ## Code Before:
from __future__ import unicode_literals
import six
@six.python_2_unicode_compatible
class Vendor(object):
"""
Represents a VPS provider.
"""
def __init__(self, name, endpoint):
"""
Initialise a new vendor object.
:param name: The name of the vendor, e.g. "RamNode".
:param endpoint: The hostname of the SolusVM control panel, with
protocol.
"""
self.name = name
self.endpoint = endpoint
def __hash__(self):
"""
Retrieve a hash value for this object.
:return: This object's hash. Identical objects will have an identical
hash.
"""
return hash(self.name)
def __eq__(self, other):
"""
Test whether this vendor is identical to another.
:param other: The object to compare to this one.
:return: True if the objects are identical, false otherwise.
"""
return isinstance(other, self.__class__) and other.name == self.name
def __str__(self):
"""
Generate a human-readable string representation of this vendor.
:return: This host as a friendly string.
"""
return '{0}({1}, {2})'.format(self.__class__.__name__,
self.name,
self.endpoint)
## Instruction:
Add documentation to Vendor properties
## Code After:
from __future__ import unicode_literals
import six
@six.python_2_unicode_compatible
class Vendor(object):
"""
Represents a VPS provider.
"""
def __init__(self, name, endpoint):
"""
Initialise a new vendor object.
:param name: The name of the vendor, e.g. "RamNode".
:param endpoint: The hostname of the SolusVM control panel, with
protocol.
"""
self.name = name
""" The vendor's name, e.g. "RamNode". """
self.endpoint = endpoint
""" The hostname of the SolusVM control panel, with protocol. """
def __hash__(self):
"""
Retrieve a hash value for this object.
:return: This object's hash. Identical objects will have an identical
hash.
"""
return hash(self.name)
def __eq__(self, other):
"""
Test whether this vendor is identical to another.
:param other: The object to compare to this one.
:return: True if the objects are identical, false otherwise.
"""
return isinstance(other, self.__class__) and other.name == self.name
def __str__(self):
"""
Generate a human-readable string representation of this vendor.
:return: This host as a friendly string.
"""
return '{0}({1}, {2})'.format(self.__class__.__name__,
self.name,
self.endpoint)
| # ... existing code ...
self.name = name
""" The vendor's name, e.g. "RamNode". """
self.endpoint = endpoint
""" The hostname of the SolusVM control panel, with protocol. """
# ... rest of the code ... |
e54fa97cb44557454655efd24380da5223a1c5ae | tests/random_object_id/random_object_id_test.py | tests/random_object_id/random_object_id_test.py | import contextlib
import re
import sys
import mock
from six.moves import cStringIO
from random_object_id.random_object_id import \
gen_random_object_id, parse_args, main
@contextlib.contextmanager
def captured_output():
new_out = StringIO()
old_out = sys.stdout
try:
sys.stdout = new_out
yield sys.stdout
finally:
sys.stdout = old_out
def test_gen_random_object_id():
assert re.match('[0-9a-f]{24}', gen_random_object_id())
def test_gen_random_object_id_time():
with mock.patch('time.time') as mock_time:
mock_time.return_value = 1429506585.786924
object_id = gen_random_object_id()
assert re.match('55348a19', object_id)
def test_parse_args():
assert parse_args(['-l']).long_form
def test_main():
with mock.patch('sys.argv', ['random_object_id']):
with captured_output() as output:
main()
assert re.match('[0-9a-f]{24}\n', output.getvalue())
def test_main_l():
with mock.patch('sys.argv', ['random_object_id', '-l']):
with captured_output() as output:
main()
assert re.match('ObjectId\("[0-9a-f]{24}"\)\n', output.getvalue())
| import contextlib
import re
import sys
import mock
import six
from random_object_id.random_object_id import \
gen_random_object_id, parse_args, main
@contextlib.contextmanager
def captured_output():
old_out = sys.stdout
try:
sys.stdout = six.StringIO()
yield sys.stdout
finally:
sys.stdout = old_out
def test_gen_random_object_id():
assert re.match('[0-9a-f]{24}', gen_random_object_id())
def test_gen_random_object_id_time():
with mock.patch('time.time') as mock_time:
mock_time.return_value = 1429506585.786924
object_id = gen_random_object_id()
assert re.match('55348a19', object_id)
def test_parse_args():
assert parse_args(['-l']).long_form
def test_main():
with mock.patch('sys.argv', ['random_object_id']):
with captured_output() as output:
main()
assert re.match('[0-9a-f]{24}\n', output.getvalue())
def test_main_l():
with mock.patch('sys.argv', ['random_object_id', '-l']):
with captured_output() as output:
main()
assert re.match('ObjectId\("[0-9a-f]{24}"\)\n', output.getvalue())
| Change how StringIO is imported | Change how StringIO is imported
| Python | mit | mxr/random-object-id | import contextlib
import re
import sys
import mock
- from six.moves import cStringIO
+ import six
from random_object_id.random_object_id import \
gen_random_object_id, parse_args, main
@contextlib.contextmanager
def captured_output():
- new_out = StringIO()
old_out = sys.stdout
try:
- sys.stdout = new_out
+ sys.stdout = six.StringIO()
yield sys.stdout
finally:
sys.stdout = old_out
def test_gen_random_object_id():
assert re.match('[0-9a-f]{24}', gen_random_object_id())
def test_gen_random_object_id_time():
with mock.patch('time.time') as mock_time:
mock_time.return_value = 1429506585.786924
object_id = gen_random_object_id()
assert re.match('55348a19', object_id)
def test_parse_args():
assert parse_args(['-l']).long_form
def test_main():
with mock.patch('sys.argv', ['random_object_id']):
with captured_output() as output:
main()
assert re.match('[0-9a-f]{24}\n', output.getvalue())
def test_main_l():
with mock.patch('sys.argv', ['random_object_id', '-l']):
with captured_output() as output:
main()
assert re.match('ObjectId\("[0-9a-f]{24}"\)\n', output.getvalue())
| Change how StringIO is imported | ## Code Before:
import contextlib
import re
import sys
import mock
from six.moves import cStringIO
from random_object_id.random_object_id import \
gen_random_object_id, parse_args, main
@contextlib.contextmanager
def captured_output():
new_out = StringIO()
old_out = sys.stdout
try:
sys.stdout = new_out
yield sys.stdout
finally:
sys.stdout = old_out
def test_gen_random_object_id():
assert re.match('[0-9a-f]{24}', gen_random_object_id())
def test_gen_random_object_id_time():
with mock.patch('time.time') as mock_time:
mock_time.return_value = 1429506585.786924
object_id = gen_random_object_id()
assert re.match('55348a19', object_id)
def test_parse_args():
assert parse_args(['-l']).long_form
def test_main():
with mock.patch('sys.argv', ['random_object_id']):
with captured_output() as output:
main()
assert re.match('[0-9a-f]{24}\n', output.getvalue())
def test_main_l():
with mock.patch('sys.argv', ['random_object_id', '-l']):
with captured_output() as output:
main()
assert re.match('ObjectId\("[0-9a-f]{24}"\)\n', output.getvalue())
## Instruction:
Change how StringIO is imported
## Code After:
import contextlib
import re
import sys
import mock
import six
from random_object_id.random_object_id import \
gen_random_object_id, parse_args, main
@contextlib.contextmanager
def captured_output():
old_out = sys.stdout
try:
sys.stdout = six.StringIO()
yield sys.stdout
finally:
sys.stdout = old_out
def test_gen_random_object_id():
assert re.match('[0-9a-f]{24}', gen_random_object_id())
def test_gen_random_object_id_time():
with mock.patch('time.time') as mock_time:
mock_time.return_value = 1429506585.786924
object_id = gen_random_object_id()
assert re.match('55348a19', object_id)
def test_parse_args():
assert parse_args(['-l']).long_form
def test_main():
with mock.patch('sys.argv', ['random_object_id']):
with captured_output() as output:
main()
assert re.match('[0-9a-f]{24}\n', output.getvalue())
def test_main_l():
with mock.patch('sys.argv', ['random_object_id', '-l']):
with captured_output() as output:
main()
assert re.match('ObjectId\("[0-9a-f]{24}"\)\n', output.getvalue())
| // ... existing code ...
import mock
import six
// ... modified code ...
def captured_output():
old_out = sys.stdout
...
try:
sys.stdout = six.StringIO()
yield sys.stdout
// ... rest of the code ... |
09a54e7a09b362b48bde21dad25b14e73cf72c98 | main.py | main.py | import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
self.sequence += random.choice(["G", "A", "T", "C"])
return self.sequence
def querySubSequence(self, subseq):
"""Return True if the string argument `subseq` is contained inside the `sequence` property"""
# Search for sub-sequence
p = re.compile(subseq)
m = p.search(self.sequence)
if m == None:
found = False
else:
found = True
return found
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
# Create a set of every possible unique subsequence
subseq = set()
i = 0
while i <= len(self.sequence) - m:
subseq.add(self.sequence[i:i+m])
i += 1
subseq = list(subseq)
# Get the occurrence number of each subsequence
OccurrenceNb = []
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
# First most frequent sub-sequence
result = subseq[OccurrenceNb.index(max(OccurrenceNb))]
return result
| import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
self.sequence += random.choice(["G", "A", "T", "C"])
return self.sequence
def querySubSequence(self, subseq):
"""Return True if the string argument `subseq` is contained inside the `sequence` property"""
# Search for sub-sequence
p = re.compile(subseq)
m = p.search(self.sequence)
if m == None:
found = False
else:
found = True
return found
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
import numpy as np
# Create a set of every possible unique subsequence
subseq = set()
i = 0
while i <= len(self.sequence) - m:
subseq.add(self.sequence[i:i+m])
i += 1
subseq = list(subseq)
# Get the occurrence number of each subsequence
OccurrenceNb = []
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
# Most frequent sub-sequence
OccurrenceNb = np.array(OccurrenceNb)
subseq = np.array(subseq)
result = list(subseq[OccurrenceNb == OccurrenceNb.max()])
return result
| Return all most frequent subsequences | Return all most frequent subsequences
| Python | mit | kir0ul/dna | import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
self.sequence += random.choice(["G", "A", "T", "C"])
return self.sequence
def querySubSequence(self, subseq):
"""Return True if the string argument `subseq` is contained inside the `sequence` property"""
# Search for sub-sequence
p = re.compile(subseq)
m = p.search(self.sequence)
if m == None:
found = False
else:
found = True
return found
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
+ import numpy as np
+
# Create a set of every possible unique subsequence
subseq = set()
i = 0
while i <= len(self.sequence) - m:
subseq.add(self.sequence[i:i+m])
i += 1
subseq = list(subseq)
# Get the occurrence number of each subsequence
OccurrenceNb = []
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
-
+
- # First most frequent sub-sequence
+ # Most frequent sub-sequence
+ OccurrenceNb = np.array(OccurrenceNb)
+ subseq = np.array(subseq)
- result = subseq[OccurrenceNb.index(max(OccurrenceNb))]
+ result = list(subseq[OccurrenceNb == OccurrenceNb.max()])
return result
| Return all most frequent subsequences | ## Code Before:
import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
self.sequence += random.choice(["G", "A", "T", "C"])
return self.sequence
def querySubSequence(self, subseq):
"""Return True if the string argument `subseq` is contained inside the `sequence` property"""
# Search for sub-sequence
p = re.compile(subseq)
m = p.search(self.sequence)
if m == None:
found = False
else:
found = True
return found
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
# Create a set of every possible unique subsequence
subseq = set()
i = 0
while i <= len(self.sequence) - m:
subseq.add(self.sequence[i:i+m])
i += 1
subseq = list(subseq)
# Get the occurrence number of each subsequence
OccurrenceNb = []
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
# First most frequent sub-sequence
result = subseq[OccurrenceNb.index(max(OccurrenceNb))]
return result
## Instruction:
Return all most frequent subsequences
## Code After:
import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
self.sequence += random.choice(["G", "A", "T", "C"])
return self.sequence
def querySubSequence(self, subseq):
"""Return True if the string argument `subseq` is contained inside the `sequence` property"""
# Search for sub-sequence
p = re.compile(subseq)
m = p.search(self.sequence)
if m == None:
found = False
else:
found = True
return found
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
import numpy as np
# Create a set of every possible unique subsequence
subseq = set()
i = 0
while i <= len(self.sequence) - m:
subseq.add(self.sequence[i:i+m])
i += 1
subseq = list(subseq)
# Get the occurrence number of each subsequence
OccurrenceNb = []
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
# Most frequent sub-sequence
OccurrenceNb = np.array(OccurrenceNb)
subseq = np.array(subseq)
result = list(subseq[OccurrenceNb == OccurrenceNb.max()])
return result
| ...
import numpy as np
# Create a set of every possible unique subsequence
...
OccurrenceNb.append(len(p.findall(self.sequence)))
# Most frequent sub-sequence
OccurrenceNb = np.array(OccurrenceNb)
subseq = np.array(subseq)
result = list(subseq[OccurrenceNb == OccurrenceNb.max()])
... |
6e32cfd9b2640b4f119a3a8e4138c883fd4bcef0 | _tests/test_scikit_ci_addons.py | _tests/test_scikit_ci_addons.py |
import ci_addons
import os
import pytest
import subprocess
from . import captured_lines
def test_home():
expected_home = os.path.abspath(os.path.dirname(__file__) + '/..')
assert ci_addons.home() == expected_home
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_path(addon):
expected_path = ci_addons.home() + '/' + addon
if not addon.endswith('.py'):
expected_path += '.py'
assert ci_addons.path(addon) == expected_path
def test_list(capsys):
ci_addons.list_addons()
output_lines, _ = captured_lines(capsys)
assert 'anyci/noop.py' in output_lines
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_execute(addon, capfd):
ci_addons.execute(addon, ['foo', 'bar'])
output_lines, _ = captured_lines(capfd)
assert ci_addons.home() + '/anyci/noop.py foo bar' in output_lines
def test_cli():
root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
environment = dict(os.environ)
environment['PYTHONPATH'] = root
subprocess.check_call(
"python -m ci_addons",
shell=True,
env=environment,
stderr=subprocess.STDOUT,
cwd=str(root)
)
|
import ci_addons
import os
import pytest
import subprocess
from . import captured_lines
def test_home():
expected_home = os.path.abspath(os.path.dirname(__file__) + '/..')
assert ci_addons.home() == expected_home
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_path(addon):
expected_path = os.path.join(ci_addons.home(), addon)
if not addon.endswith('.py'):
expected_path += '.py'
assert ci_addons.path(addon) == expected_path
def test_list(capsys):
ci_addons.list_addons()
output_lines, _ = captured_lines(capsys)
assert 'anyci' + os.path.sep + 'noop.py' in output_lines
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_execute(addon, capfd):
ci_addons.execute(addon, ['foo', 'bar'])
output_lines, _ = captured_lines(capfd)
assert os.path.join(ci_addons.home(), 'anyci/noop.py foo bar') in output_lines
def test_cli():
root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
environment = dict(os.environ)
environment['PYTHONPATH'] = root
subprocess.check_call(
"python -m ci_addons",
shell=True,
env=environment,
stderr=subprocess.STDOUT,
cwd=str(root)
)
| Fix failing tests on appveyor | ci: Fix failing tests on appveyor
| Python | apache-2.0 | scikit-build/scikit-ci-addons,scikit-build/scikit-ci-addons |
import ci_addons
import os
import pytest
import subprocess
from . import captured_lines
def test_home():
expected_home = os.path.abspath(os.path.dirname(__file__) + '/..')
assert ci_addons.home() == expected_home
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_path(addon):
- expected_path = ci_addons.home() + '/' + addon
+ expected_path = os.path.join(ci_addons.home(), addon)
if not addon.endswith('.py'):
expected_path += '.py'
assert ci_addons.path(addon) == expected_path
def test_list(capsys):
ci_addons.list_addons()
output_lines, _ = captured_lines(capsys)
- assert 'anyci/noop.py' in output_lines
+ assert 'anyci' + os.path.sep + 'noop.py' in output_lines
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_execute(addon, capfd):
ci_addons.execute(addon, ['foo', 'bar'])
output_lines, _ = captured_lines(capfd)
- assert ci_addons.home() + '/anyci/noop.py foo bar' in output_lines
+ assert os.path.join(ci_addons.home(), 'anyci/noop.py foo bar') in output_lines
def test_cli():
root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
environment = dict(os.environ)
environment['PYTHONPATH'] = root
subprocess.check_call(
"python -m ci_addons",
shell=True,
env=environment,
stderr=subprocess.STDOUT,
cwd=str(root)
)
| Fix failing tests on appveyor | ## Code Before:
import ci_addons
import os
import pytest
import subprocess
from . import captured_lines
def test_home():
expected_home = os.path.abspath(os.path.dirname(__file__) + '/..')
assert ci_addons.home() == expected_home
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_path(addon):
expected_path = ci_addons.home() + '/' + addon
if not addon.endswith('.py'):
expected_path += '.py'
assert ci_addons.path(addon) == expected_path
def test_list(capsys):
ci_addons.list_addons()
output_lines, _ = captured_lines(capsys)
assert 'anyci/noop.py' in output_lines
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_execute(addon, capfd):
ci_addons.execute(addon, ['foo', 'bar'])
output_lines, _ = captured_lines(capfd)
assert ci_addons.home() + '/anyci/noop.py foo bar' in output_lines
def test_cli():
root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
environment = dict(os.environ)
environment['PYTHONPATH'] = root
subprocess.check_call(
"python -m ci_addons",
shell=True,
env=environment,
stderr=subprocess.STDOUT,
cwd=str(root)
)
## Instruction:
Fix failing tests on appveyor
## Code After:
import ci_addons
import os
import pytest
import subprocess
from . import captured_lines
def test_home():
expected_home = os.path.abspath(os.path.dirname(__file__) + '/..')
assert ci_addons.home() == expected_home
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_path(addon):
expected_path = os.path.join(ci_addons.home(), addon)
if not addon.endswith('.py'):
expected_path += '.py'
assert ci_addons.path(addon) == expected_path
def test_list(capsys):
ci_addons.list_addons()
output_lines, _ = captured_lines(capsys)
assert 'anyci' + os.path.sep + 'noop.py' in output_lines
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_execute(addon, capfd):
ci_addons.execute(addon, ['foo', 'bar'])
output_lines, _ = captured_lines(capfd)
assert os.path.join(ci_addons.home(), 'anyci/noop.py foo bar') in output_lines
def test_cli():
root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
environment = dict(os.environ)
environment['PYTHONPATH'] = root
subprocess.check_call(
"python -m ci_addons",
shell=True,
env=environment,
stderr=subprocess.STDOUT,
cwd=str(root)
)
| ...
def test_path(addon):
expected_path = os.path.join(ci_addons.home(), addon)
if not addon.endswith('.py'):
...
output_lines, _ = captured_lines(capsys)
assert 'anyci' + os.path.sep + 'noop.py' in output_lines
...
output_lines, _ = captured_lines(capfd)
assert os.path.join(ci_addons.home(), 'anyci/noop.py foo bar') in output_lines
... |
98ebd229819cb108af7746dfdd950019111063ce | http_server.py | http_server.py | import socket
class HttpServer(object):
"""docstring for HttpServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self._ip = ip
self._port = port
self._backlog = backlog
self._socket = None
def open_socket(self):
self._socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self._socket.bind((self._ip, self._port))
self._socket.listen(self._backlog) | import socket
class HttpServer(object):
"""docstring for HttpServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self._ip = ip
self._port = port
self._backlog = backlog
self._socket = None
def open_socket(self):
self._socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self._socket.bind((self._ip, self._port))
self._socket.listen(self._backlog)
def close_socket(self):
self._socket.shutdown(socket.SHUT_WR)
self._socket.close()
self._socket = None | Add HttpServer.close_socket() to the server's socket | Add HttpServer.close_socket() to the server's socket
| Python | mit | jefrailey/network_tools | import socket
class HttpServer(object):
"""docstring for HttpServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self._ip = ip
self._port = port
self._backlog = backlog
self._socket = None
def open_socket(self):
self._socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self._socket.bind((self._ip, self._port))
self._socket.listen(self._backlog)
+
+ def close_socket(self):
+ self._socket.shutdown(socket.SHUT_WR)
+ self._socket.close()
+ self._socket = None | Add HttpServer.close_socket() to the server's socket | ## Code Before:
import socket
class HttpServer(object):
"""docstring for HttpServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self._ip = ip
self._port = port
self._backlog = backlog
self._socket = None
def open_socket(self):
self._socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self._socket.bind((self._ip, self._port))
self._socket.listen(self._backlog)
## Instruction:
Add HttpServer.close_socket() to the server's socket
## Code After:
import socket
class HttpServer(object):
"""docstring for HttpServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self._ip = ip
self._port = port
self._backlog = backlog
self._socket = None
def open_socket(self):
self._socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self._socket.bind((self._ip, self._port))
self._socket.listen(self._backlog)
def close_socket(self):
self._socket.shutdown(socket.SHUT_WR)
self._socket.close()
self._socket = None | ...
self._socket.listen(self._backlog)
def close_socket(self):
self._socket.shutdown(socket.SHUT_WR)
self._socket.close()
self._socket = None
... |
49bed20629d4b2ef50026700b98694da4c2ce224 | tasks.py | tasks.py |
"""Useful task commands for development and maintenance."""
from invoke import run, task
@task
def clean():
"""Clean the project directory of unwanted files and directories."""
run('rm -rf gmusicapi_scripts.egg-info')
run('rm -rf .coverage')
run('rm -rf .tox')
run('rm -rf .cache')
run('rm -rf build/')
run('rm -rf dist/')
run('rm -rf site/')
run('find . -name *.pyc -delete')
run('find . -name *.pyo -delete')
run('find . -name __pycache__ -delete -depth')
run('find . -name *~ -delete')
@task(clean)
def build():
"""Build sdist and bdist_wheel distributions."""
run('python setup.py sdist bdist_wheel')
@task(build)
def deploy():
"""Build and upload gmusicapi_scripts distributions."""
upload()
@task
def upload():
"""Upload gmusicapi_scripts distributions using twine."""
run('twine upload dist/*')
|
"""Useful task commands for development and maintenance."""
from invoke import run, task
@task
def clean():
"""Clean the project directory of unwanted files and directories."""
run('rm -rf gmusicapi_scripts.egg-info')
run('rm -rf .coverage')
run('rm -rf .tox')
run('rm -rf .cache')
run('rm -rf build/')
run('rm -rf dist/')
run('rm -rf site/')
run('find . -name *.pyc -delete')
run('find . -name *.pyo -delete')
run('find . -name __pycache__ -delete -depth')
run('find . -name *~ -delete')
@task(clean)
def build():
"""Build sdist and bdist_wheel distributions."""
run('python setup.py sdist bdist_wheel')
@task(build)
def deploy():
"""Build and upload gmusicapi_scripts distributions."""
upload()
@task
def docs(test=False):
""""Build the gmusicapi_scripts docs."""
if test:
run('mkdocs serve')
else:
run('mkdocs gh-deploy --clean')
@task
def upload():
"""Upload gmusicapi_scripts distributions using twine."""
run('twine upload dist/*')
| Add task for building docs | Add task for building docs
| Python | mit | thebigmunch/gmusicapi-scripts |
"""Useful task commands for development and maintenance."""
from invoke import run, task
@task
def clean():
"""Clean the project directory of unwanted files and directories."""
run('rm -rf gmusicapi_scripts.egg-info')
run('rm -rf .coverage')
run('rm -rf .tox')
run('rm -rf .cache')
run('rm -rf build/')
run('rm -rf dist/')
run('rm -rf site/')
run('find . -name *.pyc -delete')
run('find . -name *.pyo -delete')
run('find . -name __pycache__ -delete -depth')
run('find . -name *~ -delete')
@task(clean)
def build():
"""Build sdist and bdist_wheel distributions."""
run('python setup.py sdist bdist_wheel')
@task(build)
def deploy():
"""Build and upload gmusicapi_scripts distributions."""
upload()
@task
+ def docs(test=False):
+ """"Build the gmusicapi_scripts docs."""
+
+ if test:
+ run('mkdocs serve')
+ else:
+ run('mkdocs gh-deploy --clean')
+
+
+ @task
def upload():
"""Upload gmusicapi_scripts distributions using twine."""
run('twine upload dist/*')
| Add task for building docs | ## Code Before:
"""Useful task commands for development and maintenance."""
from invoke import run, task
@task
def clean():
"""Clean the project directory of unwanted files and directories."""
run('rm -rf gmusicapi_scripts.egg-info')
run('rm -rf .coverage')
run('rm -rf .tox')
run('rm -rf .cache')
run('rm -rf build/')
run('rm -rf dist/')
run('rm -rf site/')
run('find . -name *.pyc -delete')
run('find . -name *.pyo -delete')
run('find . -name __pycache__ -delete -depth')
run('find . -name *~ -delete')
@task(clean)
def build():
"""Build sdist and bdist_wheel distributions."""
run('python setup.py sdist bdist_wheel')
@task(build)
def deploy():
"""Build and upload gmusicapi_scripts distributions."""
upload()
@task
def upload():
"""Upload gmusicapi_scripts distributions using twine."""
run('twine upload dist/*')
## Instruction:
Add task for building docs
## Code After:
"""Useful task commands for development and maintenance."""
from invoke import run, task
@task
def clean():
"""Clean the project directory of unwanted files and directories."""
run('rm -rf gmusicapi_scripts.egg-info')
run('rm -rf .coverage')
run('rm -rf .tox')
run('rm -rf .cache')
run('rm -rf build/')
run('rm -rf dist/')
run('rm -rf site/')
run('find . -name *.pyc -delete')
run('find . -name *.pyo -delete')
run('find . -name __pycache__ -delete -depth')
run('find . -name *~ -delete')
@task(clean)
def build():
"""Build sdist and bdist_wheel distributions."""
run('python setup.py sdist bdist_wheel')
@task(build)
def deploy():
"""Build and upload gmusicapi_scripts distributions."""
upload()
@task
def docs(test=False):
""""Build the gmusicapi_scripts docs."""
if test:
run('mkdocs serve')
else:
run('mkdocs gh-deploy --clean')
@task
def upload():
"""Upload gmusicapi_scripts distributions using twine."""
run('twine upload dist/*')
| ...
@task
def docs(test=False):
""""Build the gmusicapi_scripts docs."""
if test:
run('mkdocs serve')
else:
run('mkdocs gh-deploy --clean')
@task
def upload():
... |
f65fd97940cb1f9c146de1b95c6e1e8652ae0c52 | bonspy/__init__.py | bonspy/__init__.py |
from __future__ import (
print_function, division, generators,
absolute_import, unicode_literals
)
from .bonsai import BonsaiTree
from .logistic import LogisticConverter
|
from __future__ import (
print_function, division, generators,
absolute_import, unicode_literals
)
from bonspy.bonsai import BonsaiTree
from bonspy.logistic import LogisticConverter
| Use more robust absolute imports | Use more robust absolute imports
| Python | bsd-3-clause | markovianhq/bonspy |
from __future__ import (
print_function, division, generators,
absolute_import, unicode_literals
)
- from .bonsai import BonsaiTree
+ from bonspy.bonsai import BonsaiTree
- from .logistic import LogisticConverter
+ from bonspy.logistic import LogisticConverter
| Use more robust absolute imports | ## Code Before:
from __future__ import (
print_function, division, generators,
absolute_import, unicode_literals
)
from .bonsai import BonsaiTree
from .logistic import LogisticConverter
## Instruction:
Use more robust absolute imports
## Code After:
from __future__ import (
print_function, division, generators,
absolute_import, unicode_literals
)
from bonspy.bonsai import BonsaiTree
from bonspy.logistic import LogisticConverter
| ...
from bonspy.bonsai import BonsaiTree
from bonspy.logistic import LogisticConverter
... |
05fc957280fecbc99c8f58897a06e23dcc4b9453 | elections/uk/forms.py | elections/uk/forms.py |
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
def clean_postcode(self):
postcode = self.cleaned_data['postcode']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
|
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
def clean_q(self):
postcode = self.cleaned_data['q']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
| Fix the postcode form so that it's actually validating the input | Fix the postcode form so that it's actually validating the input
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
- def clean_postcode(self):
+ def clean_q(self):
- postcode = self.cleaned_data['postcode']
+ postcode = self.cleaned_data['q']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
| Fix the postcode form so that it's actually validating the input | ## Code Before:
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
def clean_postcode(self):
postcode = self.cleaned_data['postcode']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
## Instruction:
Fix the postcode form so that it's actually validating the input
## Code After:
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
def clean_q(self):
postcode = self.cleaned_data['q']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
| # ... existing code ...
def clean_q(self):
postcode = self.cleaned_data['q']
try:
# ... rest of the code ... |
f12120dd9a7660277b52cd25f8cfa48b3783eece | rest_framework_friendly_errors/handlers.py | rest_framework_friendly_errors/handlers.py | from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework_friendly_errors import settings
from rest_framework_friendly_errors.utils import is_pretty
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if not response and settings.CATCH_ALL_EXCEPTIONS:
response = exception_handler(APIException(exc), context)
if response is not None:
if is_pretty(response):
return response
error_message = response.data['detail']
error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
exc.__class__.__name__)
response.data.pop('detail', {})
response.data['code'] = error_code
response.data['message'] = error_message
response.data['status_code'] = response.status_code
# response.data['exception'] = exc.__class__.__name__
return response
| from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework_friendly_errors import settings
from rest_framework_friendly_errors.utils import is_pretty
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if not response and settings.CATCH_ALL_EXCEPTIONS:
exc = APIException(exc)
response = exception_handler(exc, context)
if response is not None:
if is_pretty(response):
return response
error_message = response.data['detail']
error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
exc.__class__.__name__)
response.data.pop('detail', {})
response.data['code'] = error_code
response.data['message'] = error_message
response.data['status_code'] = response.status_code
# response.data['exception'] = exc.__class__.__name__
return response
| Create new exception to catch APIException | Create new exception to catch APIException
| Python | mit | oasiswork/drf-friendly-errors,FutureMind/drf-friendly-errors | from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework_friendly_errors import settings
from rest_framework_friendly_errors.utils import is_pretty
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if not response and settings.CATCH_ALL_EXCEPTIONS:
+ exc = APIException(exc)
- response = exception_handler(APIException(exc), context)
+ response = exception_handler(exc, context)
if response is not None:
if is_pretty(response):
return response
error_message = response.data['detail']
error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
exc.__class__.__name__)
response.data.pop('detail', {})
response.data['code'] = error_code
response.data['message'] = error_message
response.data['status_code'] = response.status_code
# response.data['exception'] = exc.__class__.__name__
return response
| Create new exception to catch APIException | ## Code Before:
from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework_friendly_errors import settings
from rest_framework_friendly_errors.utils import is_pretty
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if not response and settings.CATCH_ALL_EXCEPTIONS:
response = exception_handler(APIException(exc), context)
if response is not None:
if is_pretty(response):
return response
error_message = response.data['detail']
error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
exc.__class__.__name__)
response.data.pop('detail', {})
response.data['code'] = error_code
response.data['message'] = error_message
response.data['status_code'] = response.status_code
# response.data['exception'] = exc.__class__.__name__
return response
## Instruction:
Create new exception to catch APIException
## Code After:
from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework_friendly_errors import settings
from rest_framework_friendly_errors.utils import is_pretty
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if not response and settings.CATCH_ALL_EXCEPTIONS:
exc = APIException(exc)
response = exception_handler(exc, context)
if response is not None:
if is_pretty(response):
return response
error_message = response.data['detail']
error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
exc.__class__.__name__)
response.data.pop('detail', {})
response.data['code'] = error_code
response.data['message'] = error_message
response.data['status_code'] = response.status_code
# response.data['exception'] = exc.__class__.__name__
return response
| # ... existing code ...
if not response and settings.CATCH_ALL_EXCEPTIONS:
exc = APIException(exc)
response = exception_handler(exc, context)
# ... rest of the code ... |
27d281ab2c733d80fdf7f3521e250e72341c85b7 | setup.py | setup.py | from distutils.core import setup
import os
f = open("README.rst")
try:
try:
readme_text = f.read()
except:
readme_text = ""
finally:
f.close()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="[email protected]",
long_description=readme_text,
py_modules=["ftptool"])
| from distutils.core import setup
import os
readme_fname = os.path.join(os.path.dirname(__file__), "README.rst")
readme_text = open(readme_fname).read()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="[email protected]",
long_description=readme_text,
py_modules=["ftptool"])
| Make long description import path agnostic. | Make long description import path agnostic.
| Python | bsd-3-clause | bloggse/ftptool | from distutils.core import setup
import os
+ readme_fname = os.path.join(os.path.dirname(__file__), "README.rst")
+ readme_text = open(readme_fname).read()
- f = open("README.rst")
- try:
- try:
- readme_text = f.read()
- except:
- readme_text = ""
- finally:
- f.close()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="[email protected]",
long_description=readme_text,
py_modules=["ftptool"])
| Make long description import path agnostic. | ## Code Before:
from distutils.core import setup
import os
f = open("README.rst")
try:
try:
readme_text = f.read()
except:
readme_text = ""
finally:
f.close()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="[email protected]",
long_description=readme_text,
py_modules=["ftptool"])
## Instruction:
Make long description import path agnostic.
## Code After:
from distutils.core import setup
import os
readme_fname = os.path.join(os.path.dirname(__file__), "README.rst")
readme_text = open(readme_fname).read()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="[email protected]",
long_description=readme_text,
py_modules=["ftptool"])
| # ... existing code ...
readme_fname = os.path.join(os.path.dirname(__file__), "README.rst")
readme_text = open(readme_fname).read()
# ... rest of the code ... |
5bb6cc3ffb92736515df94b62d7d1981eadd7c44 | tilequeue/postgresql.py | tilequeue/postgresql.py | from itertools import cycle
from psycopg2.extras import register_hstore, register_json
import psycopg2
import threading
import ujson
class DBAffinityConnectionsNoLimit(object):
# Similar to the db affinity pool, but without keeping track of
# the connections. It's the caller's responsibility to call us
# back with the connection objects so that we can close them.
def __init__(self, dbnames, conn_info):
self.dbnames = dbnames
self.conn_info = conn_info
self.conn_mapping = {}
self.lock = threading.Lock()
self.dbname_index = 0
def _make_conn(self, conn_info):
conn = psycopg2.connect(**conn_info)
conn.set_session(readonly=True, autocommit=True)
register_hstore(conn)
register_json(conn, loads=ujson.loads)
return conn
def get_conns(self, n_conn):
with self.lock:
dbname = self.dbnames[self.dbname_index]
self.dbname_index += 1
if self.dbname_index >= len(self.dbnames):
self.dbname_index = 0
conn_info_with_db = dict(self.conn_info, dbname=dbname)
conns = [self._make_conn(conn_info_with_db)
for i in range(n_conn)]
return conns
def put_conns(self, conns):
for conn in conns:
try:
conn.close()
except:
pass
def closeall(self):
raise Exception('DBAffinityConnectionsNoLimit pool does not track '
'connections')
| from itertools import cycle
from psycopg2.extras import register_hstore, register_json
import psycopg2
import threading
import ujson
class DBAffinityConnectionsNoLimit(object):
# Similar to the db affinity pool, but without keeping track of
# the connections. It's the caller's responsibility to call us
# back with the connection objects so that we can close them.
def __init__(self, dbnames, conn_info):
self.dbnames = cycle(dbnames)
self.conn_info = conn_info
self.conn_mapping = {}
self.lock = threading.Lock()
def _make_conn(self, conn_info):
conn = psycopg2.connect(**conn_info)
conn.set_session(readonly=True, autocommit=True)
register_hstore(conn)
register_json(conn, loads=ujson.loads)
return conn
def get_conns(self, n_conn):
with self.lock:
dbname = self.dbnames.next()
conn_info_with_db = dict(self.conn_info, dbname=dbname)
conns = [self._make_conn(conn_info_with_db)
for i in range(n_conn)]
return conns
def put_conns(self, conns):
for conn in conns:
try:
conn.close()
except:
pass
def closeall(self):
raise Exception('DBAffinityConnectionsNoLimit pool does not track '
'connections')
| Use cycle instead of counting an index ourselves | Use cycle instead of counting an index ourselves
| Python | mit | tilezen/tilequeue,mapzen/tilequeue | from itertools import cycle
from psycopg2.extras import register_hstore, register_json
import psycopg2
import threading
import ujson
class DBAffinityConnectionsNoLimit(object):
# Similar to the db affinity pool, but without keeping track of
# the connections. It's the caller's responsibility to call us
# back with the connection objects so that we can close them.
def __init__(self, dbnames, conn_info):
- self.dbnames = dbnames
+ self.dbnames = cycle(dbnames)
self.conn_info = conn_info
self.conn_mapping = {}
self.lock = threading.Lock()
- self.dbname_index = 0
def _make_conn(self, conn_info):
conn = psycopg2.connect(**conn_info)
conn.set_session(readonly=True, autocommit=True)
register_hstore(conn)
register_json(conn, loads=ujson.loads)
return conn
def get_conns(self, n_conn):
with self.lock:
- dbname = self.dbnames[self.dbname_index]
+ dbname = self.dbnames.next()
- self.dbname_index += 1
- if self.dbname_index >= len(self.dbnames):
- self.dbname_index = 0
conn_info_with_db = dict(self.conn_info, dbname=dbname)
conns = [self._make_conn(conn_info_with_db)
for i in range(n_conn)]
return conns
def put_conns(self, conns):
for conn in conns:
try:
conn.close()
except:
pass
def closeall(self):
raise Exception('DBAffinityConnectionsNoLimit pool does not track '
'connections')
| Use cycle instead of counting an index ourselves | ## Code Before:
from itertools import cycle
from psycopg2.extras import register_hstore, register_json
import psycopg2
import threading
import ujson
class DBAffinityConnectionsNoLimit(object):
# Similar to the db affinity pool, but without keeping track of
# the connections. It's the caller's responsibility to call us
# back with the connection objects so that we can close them.
def __init__(self, dbnames, conn_info):
self.dbnames = dbnames
self.conn_info = conn_info
self.conn_mapping = {}
self.lock = threading.Lock()
self.dbname_index = 0
def _make_conn(self, conn_info):
conn = psycopg2.connect(**conn_info)
conn.set_session(readonly=True, autocommit=True)
register_hstore(conn)
register_json(conn, loads=ujson.loads)
return conn
def get_conns(self, n_conn):
with self.lock:
dbname = self.dbnames[self.dbname_index]
self.dbname_index += 1
if self.dbname_index >= len(self.dbnames):
self.dbname_index = 0
conn_info_with_db = dict(self.conn_info, dbname=dbname)
conns = [self._make_conn(conn_info_with_db)
for i in range(n_conn)]
return conns
def put_conns(self, conns):
for conn in conns:
try:
conn.close()
except:
pass
def closeall(self):
raise Exception('DBAffinityConnectionsNoLimit pool does not track '
'connections')
## Instruction:
Use cycle instead of counting an index ourselves
## Code After:
from itertools import cycle
from psycopg2.extras import register_hstore, register_json
import psycopg2
import threading
import ujson
class DBAffinityConnectionsNoLimit(object):
# Similar to the db affinity pool, but without keeping track of
# the connections. It's the caller's responsibility to call us
# back with the connection objects so that we can close them.
def __init__(self, dbnames, conn_info):
self.dbnames = cycle(dbnames)
self.conn_info = conn_info
self.conn_mapping = {}
self.lock = threading.Lock()
def _make_conn(self, conn_info):
conn = psycopg2.connect(**conn_info)
conn.set_session(readonly=True, autocommit=True)
register_hstore(conn)
register_json(conn, loads=ujson.loads)
return conn
def get_conns(self, n_conn):
with self.lock:
dbname = self.dbnames.next()
conn_info_with_db = dict(self.conn_info, dbname=dbname)
conns = [self._make_conn(conn_info_with_db)
for i in range(n_conn)]
return conns
def put_conns(self, conns):
for conn in conns:
try:
conn.close()
except:
pass
def closeall(self):
raise Exception('DBAffinityConnectionsNoLimit pool does not track '
'connections')
| ...
def __init__(self, dbnames, conn_info):
self.dbnames = cycle(dbnames)
self.conn_info = conn_info
...
self.lock = threading.Lock()
...
with self.lock:
dbname = self.dbnames.next()
conn_info_with_db = dict(self.conn_info, dbname=dbname)
... |
55cd1bc079017945c2b8f48542c491d6a7d5153f | tests/test_cl_json.py | tests/test_cl_json.py | from kqml import cl_json, KQMLList
def test_parse():
json_dict = {'a': 1, 'b': 2,
'c': ['foo', {'bar': None, 'done': False}],
'this_is_json': True}
res = cl_json._cl_from_json(json_dict)
assert isinstance(res, KQMLList)
assert len(res) == 2*len(json_dict.keys())
back_dict = cl_json.cl_to_json(res)
assert len(back_dict) == len(json_dict)
# TODO: Should test for equality.
| from kqml import cl_json, KQMLList
def _equal(json_val, back_json_val):
if json_val is False and back_json_val is None:
return True
if type(json_val) != type(back_json_val):
return False
if isinstance(json_val, dict):
ret = True
for key, value in json_val.items():
if not _equal(value, back_json_val[key]):
ret = False
break
elif isinstance(json_val, list):
ret = True
for i, value in enumerate(json_val):
if not _equal(value, back_json_val[i]):
ret = False
break
else:
ret = (json_val == back_json_val)
return ret
def test_parse():
json_dict = {'a': 1, 'b': 2,
'c': ['foo', {'bar': None, 'done': False}],
'this_is_json': True}
res = cl_json._cl_from_json(json_dict)
assert isinstance(res, KQMLList)
assert len(res) == 2*len(json_dict.keys())
back_dict = cl_json.cl_to_json(res)
assert len(back_dict) == len(json_dict)
assert _equal(json_dict, back_dict)
| Write deeper test of equality for recovered dict. | Write deeper test of equality for recovered dict.
| Python | bsd-2-clause | bgyori/pykqml | from kqml import cl_json, KQMLList
+
+
+ def _equal(json_val, back_json_val):
+ if json_val is False and back_json_val is None:
+ return True
+ if type(json_val) != type(back_json_val):
+ return False
+
+ if isinstance(json_val, dict):
+ ret = True
+ for key, value in json_val.items():
+ if not _equal(value, back_json_val[key]):
+ ret = False
+ break
+ elif isinstance(json_val, list):
+ ret = True
+ for i, value in enumerate(json_val):
+ if not _equal(value, back_json_val[i]):
+ ret = False
+ break
+ else:
+ ret = (json_val == back_json_val)
+ return ret
def test_parse():
json_dict = {'a': 1, 'b': 2,
'c': ['foo', {'bar': None, 'done': False}],
'this_is_json': True}
res = cl_json._cl_from_json(json_dict)
assert isinstance(res, KQMLList)
assert len(res) == 2*len(json_dict.keys())
back_dict = cl_json.cl_to_json(res)
assert len(back_dict) == len(json_dict)
- # TODO: Should test for equality.
+ assert _equal(json_dict, back_dict)
| Write deeper test of equality for recovered dict. | ## Code Before:
from kqml import cl_json, KQMLList
def test_parse():
json_dict = {'a': 1, 'b': 2,
'c': ['foo', {'bar': None, 'done': False}],
'this_is_json': True}
res = cl_json._cl_from_json(json_dict)
assert isinstance(res, KQMLList)
assert len(res) == 2*len(json_dict.keys())
back_dict = cl_json.cl_to_json(res)
assert len(back_dict) == len(json_dict)
# TODO: Should test for equality.
## Instruction:
Write deeper test of equality for recovered dict.
## Code After:
from kqml import cl_json, KQMLList
def _equal(json_val, back_json_val):
if json_val is False and back_json_val is None:
return True
if type(json_val) != type(back_json_val):
return False
if isinstance(json_val, dict):
ret = True
for key, value in json_val.items():
if not _equal(value, back_json_val[key]):
ret = False
break
elif isinstance(json_val, list):
ret = True
for i, value in enumerate(json_val):
if not _equal(value, back_json_val[i]):
ret = False
break
else:
ret = (json_val == back_json_val)
return ret
def test_parse():
json_dict = {'a': 1, 'b': 2,
'c': ['foo', {'bar': None, 'done': False}],
'this_is_json': True}
res = cl_json._cl_from_json(json_dict)
assert isinstance(res, KQMLList)
assert len(res) == 2*len(json_dict.keys())
back_dict = cl_json.cl_to_json(res)
assert len(back_dict) == len(json_dict)
assert _equal(json_dict, back_dict)
| // ... existing code ...
from kqml import cl_json, KQMLList
def _equal(json_val, back_json_val):
if json_val is False and back_json_val is None:
return True
if type(json_val) != type(back_json_val):
return False
if isinstance(json_val, dict):
ret = True
for key, value in json_val.items():
if not _equal(value, back_json_val[key]):
ret = False
break
elif isinstance(json_val, list):
ret = True
for i, value in enumerate(json_val):
if not _equal(value, back_json_val[i]):
ret = False
break
else:
ret = (json_val == back_json_val)
return ret
// ... modified code ...
assert len(back_dict) == len(json_dict)
assert _equal(json_dict, back_dict)
// ... rest of the code ... |
08ecc9aaf3398a0dd69bf27fc65c8ca744f98e4b | Orange/tests/test_naive_bayes.py | Orange/tests/test_naive_bayes.py | import unittest
import numpy as np
from Orange import data
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 5, (nrows, ncols))
x[:, 0] = np.ones(nrows) * 3
y = x[:, ncols / 2].reshape(nrows, 1)
table = data.Table(x, y)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.5)
| import unittest
import numpy as np
import Orange
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = Orange.data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 4, (nrows, ncols))
x[:, 0] = 3
y = x[:, ncols // 2].reshape(nrows, 1)
continuous_table = Orange.data.Table(x, y)
table = Orange.data.discretization.DiscretizeTable(continuous_table)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.6)
| Improve naive bayes unit test. | Improve naive bayes unit test.
| Python | bsd-2-clause | cheral/orange3,qusp/orange3,qPCR4vir/orange3,cheral/orange3,qusp/orange3,qusp/orange3,cheral/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,marinkaz/orange3,kwikadi/orange3,qPCR4vir/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,qPCR4vir/orange3,marinkaz/orange3,kwikadi/orange3,marinkaz/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,qusp/orange3,kwikadi/orange3,kwikadi/orange3,marinkaz/orange3,cheral/orange3 | import unittest
import numpy as np
- from Orange import data
+ import Orange
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
- t = data.Table(x1, y1)
+ t = Orange.data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
- x = np.random.random_integers(0, 5, (nrows, ncols))
+ x = np.random.random_integers(0, 4, (nrows, ncols))
- x[:, 0] = np.ones(nrows) * 3
+ x[:, 0] = 3
- y = x[:, ncols / 2].reshape(nrows, 1)
+ y = x[:, ncols // 2].reshape(nrows, 1)
- table = data.Table(x, y)
+ continuous_table = Orange.data.Table(x, y)
+ table = Orange.data.discretization.DiscretizeTable(continuous_table)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
- self.assertGreater(ca, 0.5)
+ self.assertGreater(ca, 0.6)
| Improve naive bayes unit test. | ## Code Before:
import unittest
import numpy as np
from Orange import data
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 5, (nrows, ncols))
x[:, 0] = np.ones(nrows) * 3
y = x[:, ncols / 2].reshape(nrows, 1)
table = data.Table(x, y)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.5)
## Instruction:
Improve naive bayes unit test.
## Code After:
import unittest
import numpy as np
import Orange
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = Orange.data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 4, (nrows, ncols))
x[:, 0] = 3
y = x[:, ncols // 2].reshape(nrows, 1)
continuous_table = Orange.data.Table(x, y)
table = Orange.data.discretization.DiscretizeTable(continuous_table)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.6)
| ...
import Orange
import Orange.classification.naive_bayes as nb
...
y1, y2 = np.split(y, 2)
t = Orange.data.Table(x1, y1)
learn = nb.BayesLearner()
...
ncols = 10
x = np.random.random_integers(0, 4, (nrows, ncols))
x[:, 0] = 3
y = x[:, ncols // 2].reshape(nrows, 1)
continuous_table = Orange.data.Table(x, y)
table = Orange.data.discretization.DiscretizeTable(continuous_table)
bayes = nb.BayesStorageLearner()
...
ca = scoring.CA(results)
self.assertGreater(ca, 0.6)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.