commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
e779a66c29ecb389b03357ca2e2ccb88752072b7
test/selenium/src/lib/constants/ux.py
test/selenium/src/lib/constants/ux.py
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com MAX_USER_WAIT_SECONDS = 10 MAX_ALERT_WAIT = 1 ELEMENT_MOVING_TIMEOUT = 5
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com MAX_USER_WAIT_SECONDS = 60 MAX_ALERT_WAIT = 1 ELEMENT_MOVING_TIMEOUT = 5
Increase wait time for element loading from 10s to 1min
Increase wait time for element loading from 10s to 1min
Python
apache-2.0
j0gurt/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,NejcZupec/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,josthkko/ggrc-core,kr41/ggrc-core,prasannav7/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,prasannav7/ggrc-core,selahssea/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,andrei-karalionak/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,edofic/ggrc-core,prasannav7/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,prasannav7/ggrc-core
--- +++ @@ -3,6 +3,6 @@ # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com -MAX_USER_WAIT_SECONDS = 10 +MAX_USER_WAIT_SECONDS = 60 MAX_ALERT_WAIT = 1 ELEMENT_MOVING_TIMEOUT = 5
80bbff0511e47fbb3b9ed7774942ef5f9880a9c3
plugins/Views/WireframeView/WireframeView.py
plugins/Views/WireframeView/WireframeView.py
from Cura.View.View import View from Cura.View.Renderer import Renderer from Cura.Scene.Iterator.DepthFirstIterator import DepthFirstIterator class WireframeView(View): def __init__(self): super().__init__() def render(self): scene = self.getController().getScene() renderer = self.getRenderer() for node in DepthFirstIterator(scene.getRoot()): if not node.render(renderer): if node.getMeshData(): renderer.renderMesh(node.getGlobalTransformation(), node.getMeshData(), Renderer.RenderLines)
from Cura.View.View import View from Cura.View.Renderer import Renderer from Cura.Scene.Iterator.DepthFirstIterator import DepthFirstIterator class WireframeView(View): def __init__(self): super().__init__() def render(self): scene = self.getController().getScene() renderer = self.getRenderer() for node in DepthFirstIterator(scene.getRoot()): if not node.render(renderer): if node.getMeshData(): renderer.renderMesh(node.getGlobalTransformation(), node.getMeshData(), Renderer.RenderWireframe)
Use the new wireframe mode to render the Wireframe view correctly
Use the new wireframe mode to render the Wireframe view correctly
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
--- +++ @@ -13,5 +13,5 @@ for node in DepthFirstIterator(scene.getRoot()): if not node.render(renderer): if node.getMeshData(): - renderer.renderMesh(node.getGlobalTransformation(), node.getMeshData(), Renderer.RenderLines) + renderer.renderMesh(node.getGlobalTransformation(), node.getMeshData(), Renderer.RenderWireframe)
82cc087e5dc39201444e19ce305a44aea8c4b3d1
nailgun/nailgun/extrasettings.py
nailgun/nailgun/extrasettings.py
import os import os.path LOGPATH = "/var/log/nailgun" LOGFILE = os.path.join(LOGPATH, "nailgun.log") LOGLEVEL = "DEBUG" CELERYLOGFILE = os.path.join(LOGPATH, "celery.log") CELERYLOGLEVEL = "DEBUG" PATH_TO_SSH_KEY = os.path.join(os.getenv("HOME"), ".ssh", "id_rsa") PATH_TO_BOOTSTRAP_SSH_KEY = os.path.join(os.getenv("HOME"), ".ssh", "bootstrap.rsa") COBBLER_URL = "http://localhost/cobbler_api" COBBLER_USER = "cobbler" COBBLER_PASSWORD = "cobbler" COBBLER_PROFILE = "centos-6.2-x86_64"
import os import os.path LOGPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") LOGFILE = os.path.join(LOGPATH, "nailgun.log") LOGLEVEL = "DEBUG" CELERYLOGFILE = os.path.join(LOGPATH, "celery.log") CELERYLOGLEVEL = "DEBUG" PATH_TO_SSH_KEY = os.path.join(os.getenv("HOME"), ".ssh", "id_rsa") PATH_TO_BOOTSTRAP_SSH_KEY = os.path.join(os.getenv("HOME"), ".ssh", "bootstrap.rsa") COBBLER_URL = "http://localhost/cobbler_api" COBBLER_USER = "cobbler" COBBLER_PASSWORD = "cobbler" COBBLER_PROFILE = "centos-6.2-x86_64"
Set LOGPATH to nailgun folder by default
Set LOGPATH to nailgun folder by default
Python
apache-2.0
dancn/fuel-main-dev,koder-ua/nailgun-fcert,huntxu/fuel-web,SergK/fuel-main,dancn/fuel-main-dev,AnselZhangGit/fuel-main,huntxu/fuel-main,eayunstack/fuel-web,ddepaoli3/fuel-main-dev,nebril/fuel-web,eayunstack/fuel-main,zhaochao/fuel-main,Fiware/ops.Fuel-main-dev,Fiware/ops.Fuel-main-dev,prmtl/fuel-web,prmtl/fuel-web,nebril/fuel-web,AnselZhangGit/fuel-main,nebril/fuel-web,SmartInfrastructures/fuel-main-dev,zhaochao/fuel-main,ddepaoli3/fuel-main-dev,AnselZhangGit/fuel-main,koder-ua/nailgun-fcert,ddepaoli3/fuel-main-dev,eayunstack/fuel-web,SmartInfrastructures/fuel-web-dev,Fiware/ops.Fuel-main-dev,zhaochao/fuel-web,koder-ua/nailgun-fcert,prmtl/fuel-web,huntxu/fuel-web,SmartInfrastructures/fuel-web-dev,SmartInfrastructures/fuel-web-dev,zhaochao/fuel-web,dancn/fuel-main-dev,koder-ua/nailgun-fcert,huntxu/fuel-web,teselkin/fuel-main,eayunstack/fuel-main,nebril/fuel-web,nebril/fuel-web,stackforge/fuel-web,zhaochao/fuel-main,huntxu/fuel-main,zhaochao/fuel-web,stackforge/fuel-main,eayunstack/fuel-main,SmartInfrastructures/fuel-web-dev,AnselZhangGit/fuel-main,huntxu/fuel-main,Fiware/ops.Fuel-main-dev,dancn/fuel-main-dev,prmtl/fuel-web,eayunstack/fuel-web,prmtl/fuel-web,stackforge/fuel-web,huntxu/fuel-web,teselkin/fuel-main,SmartInfrastructures/fuel-main-dev,SergK/fuel-main,SmartInfrastructures/fuel-main-dev,zhaochao/fuel-web,teselkin/fuel-main,zhaochao/fuel-main,stackforge/fuel-main,teselkin/fuel-main,ddepaoli3/fuel-main-dev,zhaochao/fuel-web,SergK/fuel-main,stackforge/fuel-web,SmartInfrastructures/fuel-web-dev,zhaochao/fuel-main,eayunstack/fuel-web,eayunstack/fuel-web,SmartInfrastructures/fuel-main-dev,stackforge/fuel-main,huntxu/fuel-web
--- +++ @@ -1,7 +1,7 @@ import os import os.path -LOGPATH = "/var/log/nailgun" +LOGPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") LOGFILE = os.path.join(LOGPATH, "nailgun.log") LOGLEVEL = "DEBUG" CELERYLOGFILE = os.path.join(LOGPATH, "celery.log")
cc3b82a943baf42f78b131d3218ad5eb748a11ce
test_proj/urls.py
test_proj/urls.py
from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), url(r'^admin_tools/', include('admin_tools.urls')), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
try: from django.conf.urls import patterns, url, include except ImportError: # django < 1.4 from django.conf.urls.defaults import patterns, url, include from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), url(r'^admin_tools/', include('admin_tools.urls')), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
Support for Django > 1.4 for test proj
Support for Django > 1.4 for test proj
Python
mit
husbas/django-admin-tools,husbas/django-admin-tools,husbas/django-admin-tools
--- +++ @@ -1,4 +1,7 @@ -from django.conf.urls.defaults import * +try: + from django.conf.urls import patterns, url, include +except ImportError: # django < 1.4 + from django.conf.urls.defaults import patterns, url, include from django.conf import settings from django.contrib import admin
fc3e823b6bf1b5c7de62a55f4b5459bbc0c9a4c3
tests/conftest.py
tests/conftest.py
# -*- coding: utf-8 -*- ''' General-purpose fixtures for vdirsyncer's testsuite. ''' import logging import os import click_log from hypothesis import HealthCheck, Verbosity, settings import pytest @pytest.fixture(autouse=True) def setup_logging(): click_log.basic_config('vdirsyncer').setLevel(logging.DEBUG) # XXX: Py2 @pytest.fixture(autouse=True) def suppress_py2_warning(monkeypatch): monkeypatch.setattr('vdirsyncer.cli._check_python2', lambda _: None) try: import pytest_benchmark except ImportError: @pytest.fixture def benchmark(): return lambda x: x() else: del pytest_benchmark settings.register_profile("ci", settings( max_examples=1000, verbosity=Verbosity.verbose, suppress_health_check=[HealthCheck.too_slow] )) settings.register_profile("deterministic", settings( derandomize=True, )) if os.getenv('DETERMINISTIC_TESTS').lower() == 'true': settings.load_profile("deterministic") elif os.getenv('CI').lower() == 'true': settings.load_profile("ci")
# -*- coding: utf-8 -*- ''' General-purpose fixtures for vdirsyncer's testsuite. ''' import logging import os import click_log from hypothesis import HealthCheck, Verbosity, settings import pytest @pytest.fixture(autouse=True) def setup_logging(): click_log.basic_config('vdirsyncer').setLevel(logging.DEBUG) # XXX: Py2 @pytest.fixture(autouse=True) def suppress_py2_warning(monkeypatch): monkeypatch.setattr('vdirsyncer.cli._check_python2', lambda _: None) try: import pytest_benchmark except ImportError: @pytest.fixture def benchmark(): return lambda x: x() else: del pytest_benchmark settings.register_profile("ci", settings( max_examples=1000, verbosity=Verbosity.verbose, suppress_health_check=[HealthCheck.too_slow] )) settings.register_profile("deterministic", settings( derandomize=True, )) if os.environ['DETERMINISTIC_TESTS'].lower() == 'true': settings.load_profile("deterministic") elif os.environ['CI'].lower() == 'true': settings.load_profile("ci")
Use os.environ instead of getenv
Use os.environ instead of getenv None.lower() fails too, but KeyError() is a nicer errormessage
Python
mit
hobarrera/vdirsyncer,untitaker/vdirsyncer,untitaker/vdirsyncer,untitaker/vdirsyncer,hobarrera/vdirsyncer
--- +++ @@ -41,7 +41,7 @@ derandomize=True, )) -if os.getenv('DETERMINISTIC_TESTS').lower() == 'true': +if os.environ['DETERMINISTIC_TESTS'].lower() == 'true': settings.load_profile("deterministic") -elif os.getenv('CI').lower() == 'true': +elif os.environ['CI'].lower() == 'true': settings.load_profile("ci")
0ba616bbd037a1c84f20221a95a623d853da9db9
garfield/sims/tests.py
garfield/sims/tests.py
from mock import patch from sms.tests.test_sms import GarfieldTwilioTestCase from sms.tests.test_sms import GarfieldTwilioTestClient class GarfieldTestSimSmsCaseNewJohn(GarfieldTwilioTestCase): @patch('sms.tasks.save_sms_message.apply_async') def test_sim_receive_sms(self, mock_save_sms_message): response = self.client.sms("Test.", path="/sims/sms/receive/") self.assert_twiml(response) self.assertTrue(mock_save_sms_message.called) @patch('sms.tasks.save_sms_message.apply_async') def test_sim_send_sms(self, mock_save_sms_message): response = self.client.sms("Test.", path="/sims/sms/send/") self.assert_twiml(response) self.assertTrue(mock_save_sms_message.called) class GarfieldTestSimVoiceCase(GarfieldTwilioTestCase): def test_sims_receive_call(self): response = self.client.call("Test.", path="/sims/voice/receive/") self.assert_twiml(response) def test_sims_send_call(self): response = self.client.call("Test.", path="/sims/voice/send/") self.assert_twiml(response)
from django.test import override_settings from mock import patch from sms.tests.test_sms import GarfieldTwilioTestCase from sms.tests.test_sms import GarfieldTwilioTestClient @override_settings(TWILIO_PHONE_NUMBER="+15558675309") class GarfieldTestSimSmsCaseNewJohn(GarfieldTwilioTestCase): @patch('sms.tasks.save_sms_message.apply_async') def test_sim_receive_sms(self, mock_save_sms_message): response = self.client.sms("Test.", path="/sims/sms/receive/") self.assert_twiml(response) self.assertTrue(mock_save_sms_message.called) @patch('sms.tasks.save_sms_message.apply_async') def test_sim_send_sms(self, mock_save_sms_message): response = self.client.sms("Test.", path="/sims/sms/send/") self.assert_twiml(response) self.assertTrue(mock_save_sms_message.called) @override_settings(TWILIO_PHONE_NUMBER="+15558675309") class GarfieldTestSimVoiceCase(GarfieldTwilioTestCase): def test_sims_receive_call(self): response = self.client.call("Test.", path="/sims/voice/receive/") self.assert_twiml(response) def test_sims_send_call(self): response = self.client.call("Test.", path="/sims/voice/send/") self.assert_twiml(response)
Add override settings for CI without local settings.
Add override settings for CI without local settings.
Python
mit
RobSpectre/garfield,RobSpectre/garfield
--- +++ @@ -1,9 +1,12 @@ +from django.test import override_settings + from mock import patch from sms.tests.test_sms import GarfieldTwilioTestCase from sms.tests.test_sms import GarfieldTwilioTestClient +@override_settings(TWILIO_PHONE_NUMBER="+15558675309") class GarfieldTestSimSmsCaseNewJohn(GarfieldTwilioTestCase): @patch('sms.tasks.save_sms_message.apply_async') def test_sim_receive_sms(self, mock_save_sms_message): @@ -22,6 +25,7 @@ self.assertTrue(mock_save_sms_message.called) +@override_settings(TWILIO_PHONE_NUMBER="+15558675309") class GarfieldTestSimVoiceCase(GarfieldTwilioTestCase): def test_sims_receive_call(self): response = self.client.call("Test.",
f5faf9c90b2671f7d09e1a4f21c036737bd039ef
echo/tests/test_response.py
echo/tests/test_response.py
import json from echo.response import EchoResponse, EchoSimplePlainTextResponse from echo.tests import BaseEchoTestCase class TestEchoSimplePlainTextResponse(BaseEchoTestCase): def test_populates_text_in_response(self): """The Plain text response should populate the outputSpeech""" expected = "This is the text" response = EchoSimplePlainTextResponse(expected) data = json.loads(response.content) assert data['response']['outputSpeech']['type'] == EchoResponse.PLAIN_TEXT_OUTPUT assert data['response']['outputSpeech']['text'] == expected def test_populates_session(self): """The Plain text response should populate the session attributes""" expected = {'apple': 'red', 'orange': 'orange'} response = EchoSimplePlainTextResponse('text', session=expected) data = json.loads(response.content) assert data['sessionAttributes'] == expected def test_sets_end_session_bool(self): """The Plain text response should be able to set the end_session bool""" response = EchoSimplePlainTextResponse('text', end_session=False) data = json.loads(response.content) assert not data['response']['shouldEndSession']
import json from echo.response import EchoResponse, EchoSimplePlainTextResponse from echo.tests import BaseEchoTestCase class TestEchoSimplePlainTextResponse(BaseEchoTestCase): def test_populates_text_in_response(self): """The Plain text response should populate the outputSpeech""" expected = "This is the text" response = EchoSimplePlainTextResponse(expected) data = json.loads(response.content.decode()) assert data['response']['outputSpeech']['type'] == EchoResponse.PLAIN_TEXT_OUTPUT assert data['response']['outputSpeech']['text'] == expected def test_populates_session(self): """The Plain text response should populate the session attributes""" expected = {'apple': 'red', 'orange': 'orange'} response = EchoSimplePlainTextResponse('text', session=expected) data = json.loads(response.content.decode()) assert data['sessionAttributes'] == expected def test_sets_end_session_bool(self): """The Plain text response should be able to set the end_session bool""" response = EchoSimplePlainTextResponse('text', end_session=False) data = json.loads(response.content.decode()) assert not data['response']['shouldEndSession']
Fix response tests in py3
Fix response tests in py3
Python
mit
bunchesofdonald/django-echo
--- +++ @@ -9,7 +9,7 @@ """The Plain text response should populate the outputSpeech""" expected = "This is the text" response = EchoSimplePlainTextResponse(expected) - data = json.loads(response.content) + data = json.loads(response.content.decode()) assert data['response']['outputSpeech']['type'] == EchoResponse.PLAIN_TEXT_OUTPUT assert data['response']['outputSpeech']['text'] == expected @@ -18,12 +18,12 @@ """The Plain text response should populate the session attributes""" expected = {'apple': 'red', 'orange': 'orange'} response = EchoSimplePlainTextResponse('text', session=expected) - data = json.loads(response.content) + data = json.loads(response.content.decode()) assert data['sessionAttributes'] == expected def test_sets_end_session_bool(self): """The Plain text response should be able to set the end_session bool""" response = EchoSimplePlainTextResponse('text', end_session=False) - data = json.loads(response.content) + data = json.loads(response.content.decode()) assert not data['response']['shouldEndSession']
32388a96b848629bf8f4b7d7ea832fca8c3dccd9
fabfile/templates/collector_haproxy.py
fabfile/templates/collector_haproxy.py
import string template = string.Template("""#contrail-collector-marker-start listen contrail-collector-stats :5938 mode http stats enable stats uri / stats auth $__contrail_hap_user__:$__contrail_hap_passwd__ frontend contrail-analytics-api *:8081 default_backend contrail-analytics-api backend contrail-analytics-api option nolinger balance roundrobin option tcp-check tcp-check connect port 6379 default-server error-limit 1 on-error mark-down $__contrail_analytics_api_backend_servers__ #contrail-collector-marker-end """)
import string template = string.Template("""#contrail-collector-marker-start listen contrail-collector-stats :5938 mode http stats enable stats uri / stats auth $__contrail_hap_user__:$__contrail_hap_passwd__ frontend contrail-analytics-api *:8081 default_backend contrail-analytics-api backend contrail-analytics-api option nolinger timeout server 3m balance roundrobin $__contrail_analytics_api_backend_servers__ #contrail-collector-marker-end """)
Remove tcp-check connect option for redis on haproxy
Remove tcp-check connect option for redis on haproxy tcp-check connect option for redis on haproxy.cfg causes the client connections in the redis-server to grow continuously and reaches the max limit resulting in connection failure/response error for requests from collector and other analytics services to redis. Change-Id: If088ba40e7f0bc420a753ec11bca9dd081ffb160 Partial-Bug: #1648601
Python
apache-2.0
Juniper/contrail-fabric-utils,Juniper/contrail-fabric-utils
--- +++ @@ -12,10 +12,8 @@ backend contrail-analytics-api option nolinger + timeout server 3m balance roundrobin - option tcp-check - tcp-check connect port 6379 - default-server error-limit 1 on-error mark-down $__contrail_analytics_api_backend_servers__ #contrail-collector-marker-end
8c1ab6a774b380fdbb571818e68b375e25909bff
pdf_parser/filters/filters/lzw_and_flate.py
pdf_parser/filters/filters/lzw_and_flate.py
""" Compression filters """ from ..stream_filter import StreamFilter from io import BytesIO import zlib class LZWDecode(StreamFilter): """LZW compression""" filter_name = 'LZWDecode' EOD = None @staticmethod def decode_data(data, **kwargs): """Based on code from http://rosettacode.org/wiki/LZW_compression""" # Build the dictionary. dict_size = 256 dictionary = {bytes((i,)): bytes((i,)) for i in range(dict_size)} # use StringIO, otherwise this becomes O(N^2) # due to string concatenation in a loop result = BytesIO() compressed = bytearray(data) w = compressed.pop(0) result.write(w) for k in compressed: if k in dictionary: entry = dictionary[k] elif k == dict_size: entry = w + w[0] else: raise ValueError('Bad compressed k: %s' % k) result.write(entry) # Add w+entry[0] to the dictionary. dictionary[dict_size] = w + entry[0] dict_size += 1 w = entry return result.getvalue() class FlateDecode(StreamFilter): """Zlib compression""" filter_name = 'FlateDecode' EOD = None @staticmethod def decode_data(data, CloseTarget=False, Predictor=None, Columns=None, BitsPerComponent=None): #TODO: use these parameters return zlib.decompress(data)
""" Compression filters """ from ..stream_filter import StreamFilter from io import BytesIO import zlib class LZWDecode(StreamFilter): """LZW compression""" filter_name = 'LZWDecode' EOD = None @staticmethod def decode_data(data, **kwargs): """Based on code from http://rosettacode.org/wiki/LZW_compression""" # Build the dictionary. dict_size = 256 dictionary = {bytes((i,)): bytes((i,)) for i in range(dict_size)} # use StringIO, otherwise this becomes O(N^2) # due to string concatenation in a loop result = BytesIO() compressed = bytearray(data) w = compressed.pop(0) result.write(w) for k in compressed: if k in dictionary: entry = dictionary[k] elif k == dict_size: entry = w + w[0] else: raise ValueError('Bad compressed k: %s' % k) result.write(entry) # Add w+entry[0] to the dictionary. dictionary[dict_size] = w + entry[0] dict_size += 1 w = entry return result.getvalue() class FlateDecode(StreamFilter): """Zlib compression""" filter_name = 'FlateDecode' EOD = None @staticmethod def decode_data(data, **kwargs): #TODO: use these parameters return zlib.decompress(data) @staticmethod def encode_data(data, **kwargs): #TODO: use these parameters return zlib.compress(data)
Add encode method to flat filter
Add encode method to flat filter
Python
mit
ajmarks/gymnast,ajmarks/gymnast
--- +++ @@ -47,7 +47,11 @@ EOD = None @staticmethod - def decode_data(data, CloseTarget=False, Predictor=None, - Columns=None, BitsPerComponent=None): + def decode_data(data, **kwargs): #TODO: use these parameters return zlib.decompress(data) + + @staticmethod + def encode_data(data, **kwargs): + #TODO: use these parameters + return zlib.compress(data)
d792f82ea6e59b0e998d023fdbc24b0829e2d0e7
pythran/tests/openmp/omp_parallel_copyin.py
pythran/tests/openmp/omp_parallel_copyin.py
#threadprivate supprimé, est ce que c'est grave? def omp_parallel_copyin(): sum = 0 sum1 = 7 num_threads = 0 if 'omp parallel copyin(sum1) private(i)': 'omp for' for i in xrange(1, 1000): sum1 += i if 'omp critical': sum += sum1 num_threads += 1 known_sum = (999 * 1000) / 2 + 7 * num_threads return known_sum == sum
#unittest.skip threadprivate not supported def omp_parallel_copyin(): sum = 0 sum1 = 7 num_threads = 0 if 'omp parallel copyin(sum1) private(i)': 'omp for' for i in xrange(1, 1000): sum1 += i if 'omp critical': sum += sum1 num_threads += 1 known_sum = (999 * 1000) / 2 + 7 * num_threads return known_sum == sum
Disable an OpenMP test that requires threadprivate
Disable an OpenMP test that requires threadprivate
Python
bsd-3-clause
pbrunet/pythran,artas360/pythran,pbrunet/pythran,pombredanne/pythran,hainm/pythran,artas360/pythran,hainm/pythran,serge-sans-paille/pythran,hainm/pythran,pombredanne/pythran,artas360/pythran,serge-sans-paille/pythran,pombredanne/pythran,pbrunet/pythran
--- +++ @@ -1,4 +1,4 @@ -#threadprivate supprimé, est ce que c'est grave? +#unittest.skip threadprivate not supported def omp_parallel_copyin(): sum = 0 sum1 = 7
83908d3d8d3de0db5f8af26155137bf382afa24a
lettuce_webdriver/django.py
lettuce_webdriver/django.py
""" Django-specific extensions """ def site_url(url): """ Determine the server URL. """ base_url = 'http://%s' % socket.gethostname() if server.port is not 80: base_url += ':%d' % server.port return urlparse.urljoin(base_url, url) @step(r'I visit site page "([^"]*)"') def visit_page(step, page): """ Visit the specific page of the site. """ step.given('I visit "%s"' % site_url(page))
""" Django-specific extensions """ import socket import urlparse from lettuce import step from lettuce.django import server # make sure the steps are loaded import lettuce_webdriver.webdriver # pylint:disable=unused-import def site_url(url): """ Determine the server URL. """ base_url = 'http://%s' % socket.gethostname() if server.port is not 80: base_url += ':%d' % server.port return urlparse.urljoin(base_url, url) @step(r'I visit site page "([^"]*)"') def visit_page(self, page): """ Visit the specific page of the site. """ self.given('I visit "%s"' % site_url(page))
Fix bugs with lettuce-webdriver Django steps
Fix bugs with lettuce-webdriver Django steps
Python
mit
infoxchange/lettuce_webdriver,infoxchange/lettuce_webdriver,aloetesting/aloe_webdriver,infoxchange/aloe_webdriver,koterpillar/aloe_webdriver,macndesign/lettuce_webdriver,ponsfrilus/lettuce_webdriver,aloetesting/aloe_webdriver,ponsfrilus/lettuce_webdriver,bbangert/lettuce_webdriver,aloetesting/aloe_webdriver,bbangert/lettuce_webdriver,koterpillar/aloe_webdriver,macndesign/lettuce_webdriver,infoxchange/aloe_webdriver
--- +++ @@ -1,6 +1,15 @@ """ Django-specific extensions """ + +import socket +import urlparse + +from lettuce import step +from lettuce.django import server + +# make sure the steps are loaded +import lettuce_webdriver.webdriver # pylint:disable=unused-import def site_url(url): @@ -16,9 +25,9 @@ @step(r'I visit site page "([^"]*)"') -def visit_page(step, page): +def visit_page(self, page): """ Visit the specific page of the site. """ - step.given('I visit "%s"' % site_url(page)) + self.given('I visit "%s"' % site_url(page))
39ea336297b0479abb29a70f831b2a02a01fcc18
portas/portas/utils.py
portas/portas/utils.py
import contextlib import functools import logging import sys import webob.exc LOG = logging.getLogger(__name__) def http_success_code(code): """Attaches response code to a method. This decorator associates a response code with a method. Note that the function attributes are directly manipulated; the method is not wrapped. """ def decorator(func): func.wsgi_code = code return func return decorator def verify_tenant(func): @functools.wraps(func) def __inner(self, req, tenant_id, *args, **kwargs): if hasattr(req, 'context') and tenant_id != req.context.tenant_id: LOG.info('User is not authorized to access this tenant.') raise webob.exc.HTTPUnauthorized return func(self, req, tenant_id, *args, **kwargs) return __inner def require_admin(func): @functools.wraps(func) def __inner(self, req, *args, **kwargs): if hasattr(req, 'context') and not req.context.is_admin: LOG.info('User has no admin priviledges.') raise webob.exc.HTTPUnauthorized return func(self, req, *args, **kwargs) return __inner @contextlib.contextmanager def save_and_reraise_exception(): """Save current exception, run some code and then re-raise. In some cases the exception context can be cleared, resulting in None being attempted to be reraised after an exception handler is run. This can happen when eventlet switches greenthreads or when running an exception handler, code raises and catches an exception. In both cases the exception context will be cleared. To work around this, we save the exception state, run handler code, and then re-raise the original exception. If another exception occurs, the saved exception is logged and the new exception is reraised. """ type_, value, traceback = sys.exc_info() try: yield except Exception: LOG.error('Original exception being dropped', exc_info=(type_, value, traceback)) raise raise type_, value, traceback
import logging LOG = logging.getLogger(__name__) # def verify_tenant(func): # @functools.wraps(func) # def __inner(self, req, tenant_id, *args, **kwargs): # if hasattr(req, 'context') and tenant_id != req.context.tenant: # LOG.info('User is not authorized to access this tenant.') # raise webob.exc.HTTPUnauthorized # return func(self, req, tenant_id, *args, **kwargs) # return __inner # # # def require_admin(func): # @functools.wraps(func) # def __inner(self, req, *args, **kwargs): # if hasattr(req, 'context') and not req.context.is_admin: # LOG.info('User has no admin priviledges.') # raise webob.exc.HTTPUnauthorized # return func(self, req, *args, **kwargs) # return __inner
Remove unnecessary blocks of code
Remove unnecessary blocks of code
Python
apache-2.0
Bloomie/murano-agent,openstack/python-muranoclient,ativelkov/murano-api,sajuptpm/murano,NeCTAR-RC/murano,satish-avninetworks/murano,satish-avninetworks/murano,openstack/murano,openstack/murano-agent,openstack/murano-agent,telefonicaid/murano,satish-avninetworks/murano,DavidPurcell/murano_temp,openstack/murano-agent,sergmelikyan/murano,chenyujie/hybrid-murano,olivierlemasle/murano,olivierlemasle/murano,ativelkov/murano-api,sajuptpm/murano,Bloomie/murano-agent,satish-avninetworks/murano,openstack/murano,telefonicaid/murano-agent,olivierlemasle/murano,chenyujie/hybrid-murano,telefonicaid/murano-agent,Bloomie/murano-agent,openstack/python-muranoclient,telefonicaid/murano-agent,DavidPurcell/murano_temp,openstack/murano-agent,DavidPurcell/murano_temp,NeCTAR-RC/murano,NeCTAR-RC/murano,telefonicaid/murano,olivierlemasle/murano,Bloomie/murano-agent,DavidPurcell/murano_temp,sergmelikyan/murano,NeCTAR-RC/murano
--- +++ @@ -1,66 +1,24 @@ -import contextlib -import functools import logging -import sys - -import webob.exc LOG = logging.getLogger(__name__) -def http_success_code(code): - """Attaches response code to a method. +# def verify_tenant(func): +# @functools.wraps(func) +# def __inner(self, req, tenant_id, *args, **kwargs): +# if hasattr(req, 'context') and tenant_id != req.context.tenant: +# LOG.info('User is not authorized to access this tenant.') +# raise webob.exc.HTTPUnauthorized +# return func(self, req, tenant_id, *args, **kwargs) +# return __inner +# +# +# def require_admin(func): +# @functools.wraps(func) +# def __inner(self, req, *args, **kwargs): +# if hasattr(req, 'context') and not req.context.is_admin: +# LOG.info('User has no admin priviledges.') +# raise webob.exc.HTTPUnauthorized +# return func(self, req, *args, **kwargs) +# return __inner - This decorator associates a response code with a method. Note - that the function attributes are directly manipulated; the method - is not wrapped. - """ - - def decorator(func): - func.wsgi_code = code - return func - return decorator - - -def verify_tenant(func): - @functools.wraps(func) - def __inner(self, req, tenant_id, *args, **kwargs): - if hasattr(req, 'context') and tenant_id != req.context.tenant_id: - LOG.info('User is not authorized to access this tenant.') - raise webob.exc.HTTPUnauthorized - return func(self, req, tenant_id, *args, **kwargs) - return __inner - - -def require_admin(func): - @functools.wraps(func) - def __inner(self, req, *args, **kwargs): - if hasattr(req, 'context') and not req.context.is_admin: - LOG.info('User has no admin priviledges.') - raise webob.exc.HTTPUnauthorized - return func(self, req, *args, **kwargs) - return __inner - - -@contextlib.contextmanager -def save_and_reraise_exception(): - """Save current exception, run some code and then re-raise. - - In some cases the exception context can be cleared, resulting in None - being attempted to be reraised after an exception handler is run. This - can happen when eventlet switches greenthreads or when running an - exception handler, code raises and catches an exception. In both - cases the exception context will be cleared. - - To work around this, we save the exception state, run handler code, and - then re-raise the original exception. If another exception occurs, the - saved exception is logged and the new exception is reraised. - """ - type_, value, traceback = sys.exc_info() - try: - yield - except Exception: - LOG.error('Original exception being dropped', - exc_info=(type_, value, traceback)) - raise - raise type_, value, traceback
6eff6622457b619f36404957968f30e3b1944362
openfisca_country_template/__init__.py
openfisca_country_template/__init__.py
# -*- coding: utf-8 -*- import os from openfisca_core.taxbenefitsystems import TaxBenefitSystem from . import entities COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) # Our country tax and benefit class inherits from the general TaxBenefitSystem class. # The name CountryTaxBenefitSystem must not be changed, as all tools of the OpenFisca ecosystem expect a CountryTaxBenefitSystem class to be exposed in the __init__ module of a country package. class CountryTaxBenefitSystem(TaxBenefitSystem): def __init__(self): # We initialize our tax and benefit system with the general constructor super(CountryTaxBenefitSystem, self).__init__(entities.entities) # We add to our tax and benefit system all the variables self.add_variables_from_directory(os.path.join(COUNTRY_DIR, 'variables')) # We add to our tax and benefit system all the legislation parameters defined in the parameters files param_path = os.path.join(COUNTRY_DIR, 'parameters') self.load_parameters(param_path)
# -*- coding: utf-8 -*- import os from openfisca_core.taxbenefitsystems import TaxBenefitSystem from openfisca_country_template import entities from openfisca_country_template.situation_examples import couple COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) # Our country tax and benefit class inherits from the general TaxBenefitSystem class. # The name CountryTaxBenefitSystem must not be changed, as all tools of the OpenFisca ecosystem expect a CountryTaxBenefitSystem class to be exposed in the __init__ module of a country package. class CountryTaxBenefitSystem(TaxBenefitSystem): def __init__(self): # We initialize our tax and benefit system with the general constructor super(CountryTaxBenefitSystem, self).__init__(entities.entities) # We add to our tax and benefit system all the variables self.add_variables_from_directory(os.path.join(COUNTRY_DIR, 'variables')) # We add to our tax and benefit system all the legislation parameters defined in the parameters files param_path = os.path.join(COUNTRY_DIR, 'parameters') self.load_parameters(param_path) # We define which variable, parameter and simulation example will be used in the OpenAPI specification self.open_api_config = { "variable_example": "disposable_income", "parameter_example": "taxes.income_tax_rate", "simulation_example": couple, }
Define which examples to use in OpenAPI
Define which examples to use in OpenAPI
Python
agpl-3.0
openfisca/country-template,openfisca/country-template
--- +++ @@ -4,7 +4,8 @@ from openfisca_core.taxbenefitsystems import TaxBenefitSystem -from . import entities +from openfisca_country_template import entities +from openfisca_country_template.situation_examples import couple COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) @@ -23,3 +24,10 @@ # We add to our tax and benefit system all the legislation parameters defined in the parameters files param_path = os.path.join(COUNTRY_DIR, 'parameters') self.load_parameters(param_path) + + # We define which variable, parameter and simulation example will be used in the OpenAPI specification + self.open_api_config = { + "variable_example": "disposable_income", + "parameter_example": "taxes.income_tax_rate", + "simulation_example": couple, + }
edd096abfa3c304b49fe94155a64fc2371a3084a
py/linhomy/matrices.py
py/linhomy/matrices.py
''' >>> IC_FLAG[2] array([[1, 3], [1, 4]]) >>> IC_FLAG[3] array([[1, 4, 6], [1, 5, 8], [1, 6, 9]]) ''' # For Python2 compatibility from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __metaclass__ = type import numpy from .fibonacci import FIBONACCI from .tools import grow_list from .data import IC_flag def fib_zeros_array(*argv): '''Return array with shape (FIB[argv[0] + 1], ...). ''' shape = tuple(FIBONACCI[n+1] for n in argv) value = numpy.zeros(shape, int) return value @grow_list def IC_FLAG(self): deg = len(self) value = fib_zeros_array(deg, deg) for i, line in enumerate(IC_flag[deg]): value[i] = list(map(int, line.split()[1:])) return value
''' >>> FLAG_from_IC[2] array([[1, 1], [3, 4]]) The flag vector of ICC is [1, 6, 9]. >>> numpy.dot(FLAG_from_IC[3], [0, 0, 1]) array([1, 6, 9]) >>> FLAG_from_IC[3] array([[1, 1, 1], [4, 5, 6], [6, 8, 9]]) ''' # For Python2 compatibility from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __metaclass__ = type import numpy from .fibonacci import FIBONACCI from .tools import grow_list from .data import IC_flag def fib_zeros_array(*argv): '''Return array with shape (FIB[argv[0] + 1], ...). ''' shape = tuple(FIBONACCI[n+1] for n in argv) value = numpy.zeros(shape, int) return value @grow_list def FLAG_from_IC(self): deg = len(self) value = fib_zeros_array(deg, deg) for i, line in enumerate(IC_flag[deg]): value[:,i] = list(map(int, line.split()[1:])) return value
Rewrite to replace IC_FLAG by FLAG_from_IC.
Rewrite to replace IC_FLAG by FLAG_from_IC.
Python
mit
jfine2358/py-linhomy
--- +++ @@ -1,15 +1,18 @@ ''' ->>> IC_FLAG[2] -array([[1, 3], - [1, 4]]) +>>> FLAG_from_IC[2] +array([[1, 1], + [3, 4]]) +The flag vector of ICC is [1, 6, 9]. +>>> numpy.dot(FLAG_from_IC[3], [0, 0, 1]) +array([1, 6, 9]) ->>> IC_FLAG[3] -array([[1, 4, 6], - [1, 5, 8], - [1, 6, 9]]) +>>> FLAG_from_IC[3] +array([[1, 1, 1], + [4, 5, 6], + [6, 8, 9]]) ''' @@ -36,12 +39,12 @@ @grow_list -def IC_FLAG(self): +def FLAG_from_IC(self): deg = len(self) value = fib_zeros_array(deg, deg) for i, line in enumerate(IC_flag[deg]): - value[i] = list(map(int, line.split()[1:])) + value[:,i] = list(map(int, line.split()[1:])) return value
3e3e4b88692922fe3182e4db1db60e8a60ced8e4
apps/user/admin.py
apps/user/admin.py
# -*- coding: utf-8 -*- # # defivelo-intranet -- Outil métier pour la gestion du Défi Vélo # Copyright (C) 2015 Didier Raboud <me+defivelo@odyx.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from importlib import import_module from django.apps import apps from django.conf import settings from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import UserManagedState, UserProfile admin.site.register(UserProfile) admin.site.register(UserManagedState) # Monkey-patch the get_username, mostly for the admin def get_user_model_safe(): """ Get the user model before it is loaded, but after the app registry is populated """ app_label, model_name = settings.AUTH_USER_MODEL.split('.') app_config = apps.get_app_config(app_label) models_module = import_module("%s.%s" % (app_config.name, "models")) return getattr(models_module, model_name) def username(self): return _('{fullname} <{email}>').format( fullname=self.get_full_name(), email=self.email) get_user_model_safe().get_username = username
# -*- coding: utf-8 -*- # # defivelo-intranet -- Outil métier pour la gestion du Défi Vélo # Copyright (C) 2015 Didier Raboud <me+defivelo@odyx.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from importlib import import_module from django.apps import apps from django.conf import settings from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import UserManagedState, UserProfile admin.site.register(UserProfile) admin.site.register(UserManagedState)
Drop the hurtinq username patching of username that also affects edition
Drop the hurtinq username patching of username that also affects edition
Python
agpl-3.0
defivelo/db,defivelo/db,defivelo/db
--- +++ @@ -26,25 +26,3 @@ admin.site.register(UserProfile) admin.site.register(UserManagedState) - -# Monkey-patch the get_username, mostly for the admin - - -def get_user_model_safe(): - """ - Get the user model before it is loaded, but after the app registry - is populated - """ - app_label, model_name = settings.AUTH_USER_MODEL.split('.') - app_config = apps.get_app_config(app_label) - models_module = import_module("%s.%s" % (app_config.name, "models")) - return getattr(models_module, model_name) - - -def username(self): - return _('{fullname} <{email}>').format( - fullname=self.get_full_name(), - email=self.email) - - -get_user_model_safe().get_username = username
8c64757759e69f7aff84065db8da604dd43faded
pyrsss/usarray/info.py
pyrsss/usarray/info.py
import pandas as PD INFO_LINK = 'http://ds.iris.edu/files/earthscope/usarray/_US-MT-StationList.txt' """Full URL link to USArray MT site information text file.""" HEADER = 'VNET NET STA SITE DESCRIPTION LAT LON ELEV START END STATUS INSTALL CERT' """Header line of data file.""" def get_info_map(info_link=INFO_LINK): """ Return a :class:`DataFrame` containing the information provided at *info_link*, a link to a tab delineated text file containing information for each USArray MT site. """ df = PD.read_table(info_link, sep='\t', skiprows=1, names=['vnet', 'net', 'sta', 'location', 'lat', 'lon', 'elev', 'start', 'end', 'status', 'install', 'cert'], parse_dates=[7, 8], index_col=2) return df
import pandas as PD INFO_LINK = 'http://ds.iris.edu/files/earthscope/usarray/_US-MT-StationList.txt' """Full URL link to USArray MT site information text file.""" HEADER = 'VNET NET STA SITE DESCRIPTION LAT LON ELEV START END STATUS INSTALL CERT' """Header line of data file.""" def get_info_map(info_link=INFO_LINK): """ Return a :class:`DataFrame` containing the information provided at *info_link*, a link to a tab delineated text file containing information for each USArray MT site. """ df = PD.read_csv(info_link, sep='\t', skiprows=1, names=['vnet', 'net', 'sta', 'location', 'lat', 'lon', 'elev', 'start', 'end', 'status', 'install', 'cert'], parse_dates=[7, 8], index_col=2) return df
Change of function name due to deprecation.
Change of function name due to deprecation.
Python
mit
butala/pyrsss
--- +++ @@ -15,21 +15,21 @@ *info_link*, a link to a tab delineated text file containing information for each USArray MT site. """ - df = PD.read_table(info_link, - sep='\t', - skiprows=1, - names=['vnet', - 'net', - 'sta', - 'location', - 'lat', - 'lon', - 'elev', - 'start', - 'end', - 'status', - 'install', - 'cert'], - parse_dates=[7, 8], - index_col=2) + df = PD.read_csv(info_link, + sep='\t', + skiprows=1, + names=['vnet', + 'net', + 'sta', + 'location', + 'lat', + 'lon', + 'elev', + 'start', + 'end', + 'status', + 'install', + 'cert'], + parse_dates=[7, 8], + index_col=2) return df
fba4801ce64853db37af01b08e1533719425118d
repovisor/repovisor.py
repovisor/repovisor.py
from git import Repo from git.exc import InvalidGitRepositoryError import os def reposearch(*folders): for folder in folders: for dir, subdirs, files in os.walk(folder): try: yield dict(vcs='git', pntr=Repo(dir), folder=dir) subdirs[:] = [] continue except InvalidGitRepositoryError: pass
from git import Repo from git.exc import InvalidGitRepositoryError import os import warnings vcs_statechecker = {'git': None} def reposearch(*folders): for folder in folders: for dir, subdirs, files in os.walk(folder): try: yield dict(vcs='git', pntr=Repo(dir), folder=dir) subdirs[:] = [] continue except InvalidGitRepositoryError: pass def repocheck(*repos): for repo in repos: if 'state' in repo: repo['laststate'] = repo['state'] if repo['vcs'] not in vcs_statechecker: warnings.warn( 'Unknown vcs type: {} not checked'.format(repo['folder'])) repo['state'] = vcs_statechecker[repo['vcs']](repo['pntr']) def git_for_each_ref(repo, ref): """replicate my for-each-ref pattern""" upstream = ref.tracking_branch().name if not upstream: return dict(upstream=None) ahead = sum(1 for c in repo.iter_commits(rev=upstream.name + '..' + ref.name)) behind = sum(1 for c in repo.iter_commits(rev=ref.name + '..' + upstream.name)) return dict(upstream=upstream, ahead=ahead, behind=behind) def checkGit(repo): """Check a git repo state and report it""" dirty = repo.is_dirty() untracked = repo.untracked_files reflist = [git_for_each_ref(repo, ref) for ref in repo.heads] return dict(dirty=dirty, untracked=untracked, refcheck=reflist) def addHandlers(): """add statechker handlers to dict""" vcs_statechecker['git'] = checkGit
Add repocheck looper, git checker
Add repocheck looper, git checker
Python
bsd-3-clause
gjcooper/repovisor,gjcooper/repovisor
--- +++ @@ -1,6 +1,10 @@ from git import Repo from git.exc import InvalidGitRepositoryError import os +import warnings + +vcs_statechecker = {'git': None} + def reposearch(*folders): for folder in folders: @@ -12,3 +16,37 @@ except InvalidGitRepositoryError: pass + +def repocheck(*repos): + for repo in repos: + if 'state' in repo: + repo['laststate'] = repo['state'] + if repo['vcs'] not in vcs_statechecker: + warnings.warn( + 'Unknown vcs type: {} not checked'.format(repo['folder'])) + repo['state'] = vcs_statechecker[repo['vcs']](repo['pntr']) + + +def git_for_each_ref(repo, ref): + """replicate my for-each-ref pattern""" + upstream = ref.tracking_branch().name + if not upstream: + return dict(upstream=None) + ahead = sum(1 for c in + repo.iter_commits(rev=upstream.name + '..' + ref.name)) + behind = sum(1 for c in + repo.iter_commits(rev=ref.name + '..' + upstream.name)) + return dict(upstream=upstream, ahead=ahead, behind=behind) + + +def checkGit(repo): + """Check a git repo state and report it""" + dirty = repo.is_dirty() + untracked = repo.untracked_files + reflist = [git_for_each_ref(repo, ref) for ref in repo.heads] + return dict(dirty=dirty, untracked=untracked, refcheck=reflist) + + +def addHandlers(): + """add statechker handlers to dict""" + vcs_statechecker['git'] = checkGit
256c0f9cfd1ca0c5982ac9ab001c5ced84a02c32
src/bots/inputs/malwaredomains/feed.py
src/bots/inputs/malwaredomains/feed.py
#!/usr/bin/python import sys from lib.bot import * from lib.utils import * from lib.event import * from lib.cache import * import time class MalwareDomainsBot(Bot): def process(self): url = "http://www.malwaredomainlist.com/updatescsv.php" report = fetch_url(url, timeout = 60.0, chunk_size = 16384) rep_ascii = report.decode('ascii', 'ignore') # print report self.pipeline.send(rep_ascii) if __name__ == "__main__": bot = MalwareDomainsBot(sys.argv[1]) bot.start()
#!/usr/bin/python import sys from lib.bot import * from lib.utils import * from lib.event import * from lib.cache import * import time class MalwareDomainsBot(Bot): def process(self): url = "http://www.malwaredomainlist.com/updatescsv.php" report = fetch_url(url, timeout = 60.0, chunk_size = 16384) rep_ascii = report.decode('ascii','ignore') # [FIXME] crete generic decoder - see above self.pipeline.send(rep_ascii) if __name__ == "__main__": bot = MalwareDomainsBot(sys.argv[1]) bot.start()
Comment added to create generic decode method
Comment added to create generic decode method
Python
agpl-3.0
aaronkaplan/intelmq-old,s4n7h0/intelmq,Phantasus/intelmq,aaronkaplan/intelmq-old,aaronkaplan/intelmq-old
--- +++ @@ -12,8 +12,9 @@ def process(self): url = "http://www.malwaredomainlist.com/updatescsv.php" report = fetch_url(url, timeout = 60.0, chunk_size = 16384) - rep_ascii = report.decode('ascii', 'ignore') -# print report + + rep_ascii = report.decode('ascii','ignore') +# [FIXME] crete generic decoder - see above self.pipeline.send(rep_ascii)
31ad44a9ea518a6ced7d1bd938cec1ee215fefac
pyexp/string_permu_check.py
pyexp/string_permu_check.py
'''Module to solve the algoritm question: Given a string S, how to count how many permutations of S is in a longer string L, assuming, of course, that permutations of S must be in contagious blocks in L. I will solve it in O(len(L)) time. For demonstration purpose, let's assume the characters are ASCII lowercase letters only. ''' # Q: given a character, how to convert it into its # ASCII value? A: using ord() and chr() SHIFT = ord('a') def char_to_int(char): '''convert char in a-z to 0-25 ''' # TODO: range check return ord(char) - SHIFT def int_to_char(num): '''convert num in 0-25 to a-z ''' # TODO: range check return chr(num + SHIFT) def string_permu_hash(in_str): base = len(in_str) + 1 hash_result = 0 for c in in_str: hash_result += base ** char_to_int(c) return hash_result
'''Module to solve the algoritm question: Given a string S, how to count how many permutations of S is in a longer string L, assuming, of course, that permutations of S must be in contagious blocks in L. I will solve it in O(len(L)) time. For demonstration purpose, let's assume the characters are ASCII lowercase letters only. ''' # Q: given a character, how to convert it into its # ASCII value? A: using ord() and chr() SHIFT = ord('a') def char_to_int(char): '''convert char in a-z to 0-25 ''' # TODO: range check return ord(char) - SHIFT def int_to_char(num): '''convert num in 0-25 to a-z ''' # TODO: range check return chr(num + SHIFT) def string_permu_hash(in_str): '''hash a string based on the numbers of each char in the string. So 2 permutations of a string give the same hash. You can decompose this hash to get back the number of each char. ''' base = len(in_str) + 1 hash_result = 0 for c in in_str: hash_result += base ** char_to_int(c) return hash_result
Add documentation for the hash function.
Add documentation for the hash function.
Python
mit
nguyentu1602/pyexp
--- +++ @@ -25,6 +25,11 @@ return chr(num + SHIFT) def string_permu_hash(in_str): + '''hash a string based on the numbers of each char + in the string. So 2 permutations of a string give + the same hash. You can decompose this hash to get + back the number of each char. + ''' base = len(in_str) + 1 hash_result = 0 for c in in_str:
57376590aec0db20a8046deaee86d035c8963a40
readthedocs/builds/admin.py
readthedocs/builds/admin.py
"""Django admin interface for `~builds.models.Build` and related models. """ from django.contrib import admin from readthedocs.builds.models import Build, VersionAlias, Version, BuildCommandResult from guardian.admin import GuardedModelAdmin class BuildCommandResultInline(admin.TabularInline): model = BuildCommandResult fields = ('command', 'exit_code') class BuildAdmin(admin.ModelAdmin): fields = ('project', 'version', 'type', 'error', 'state', 'success', 'length') list_display = ('project', 'success', 'type', 'state', 'date') raw_id_fields = ('project', 'version') inlines = (BuildCommandResultInline,) class VersionAdmin(GuardedModelAdmin): search_fields = ('slug', 'project__name') list_filter = ('project', 'privacy_level') admin.site.register(Build, BuildAdmin) admin.site.register(VersionAlias) admin.site.register(Version, VersionAdmin)
"""Django admin interface for `~builds.models.Build` and related models. """ from django.contrib import admin from readthedocs.builds.models import Build, VersionAlias, Version, BuildCommandResult from guardian.admin import GuardedModelAdmin class BuildCommandResultInline(admin.TabularInline): model = BuildCommandResult fields = ('command', 'exit_code', 'output') class BuildAdmin(admin.ModelAdmin): fields = ('project', 'version', 'type', 'state', 'error', 'success', 'length') list_display = ('project', 'success', 'type', 'state', 'date') raw_id_fields = ('project', 'version') inlines = (BuildCommandResultInline,) class VersionAdmin(GuardedModelAdmin): search_fields = ('slug', 'project__name') list_filter = ('project', 'privacy_level') admin.site.register(Build, BuildAdmin) admin.site.register(VersionAlias) admin.site.register(Version, VersionAdmin)
Include output in result inline
Include output in result inline
Python
mit
tddv/readthedocs.org,espdev/readthedocs.org,espdev/readthedocs.org,davidfischer/readthedocs.org,safwanrahman/readthedocs.org,tddv/readthedocs.org,safwanrahman/readthedocs.org,tddv/readthedocs.org,espdev/readthedocs.org,davidfischer/readthedocs.org,espdev/readthedocs.org,rtfd/readthedocs.org,espdev/readthedocs.org,davidfischer/readthedocs.org,safwanrahman/readthedocs.org,pombredanne/readthedocs.org,rtfd/readthedocs.org,pombredanne/readthedocs.org,rtfd/readthedocs.org,pombredanne/readthedocs.org,safwanrahman/readthedocs.org,davidfischer/readthedocs.org,rtfd/readthedocs.org
--- +++ @@ -9,11 +9,11 @@ class BuildCommandResultInline(admin.TabularInline): model = BuildCommandResult - fields = ('command', 'exit_code') + fields = ('command', 'exit_code', 'output') class BuildAdmin(admin.ModelAdmin): - fields = ('project', 'version', 'type', 'error', 'state', 'success', 'length') + fields = ('project', 'version', 'type', 'state', 'error', 'success', 'length') list_display = ('project', 'success', 'type', 'state', 'date') raw_id_fields = ('project', 'version') inlines = (BuildCommandResultInline,)
47269f733427fef34e4f43c2652eda79aa3e5e0d
test/test_util/test_StopWatch.py
test/test_util/test_StopWatch.py
# -*- encoding: utf-8 -*- """Created on Dec 16, 2014. @author: Katharina Eggensperger @projekt: AutoML2015 """ from __future__ import print_function import time import unittest from autosklearn.util import StopWatch class Test(unittest.TestCase): _multiprocess_can_split_ = True def test_stopwatch_overhead(self): # CPU overhead start = time.clock() watch = StopWatch() for i in range(1, 1000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.clock() dur = stop - start cpu_overhead = dur - watch.cpu_sum() self.assertLess(cpu_overhead, 1.5) # Wall Overhead start = time.time() watch = StopWatch() for i in range(1, 1000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.time() dur = stop - start wall_overhead = dur - watch.wall_sum() self.assertLess(wall_overhead, 2) self.assertLess(cpu_overhead, 2*wall_overhead) if __name__ == '__main__': # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
# -*- encoding: utf-8 -*- """Created on Dec 16, 2014. @author: Katharina Eggensperger @projekt: AutoML2015 """ from __future__ import print_function import time import unittest import unittest.mock from autosklearn.util import StopWatch class Test(unittest.TestCase): _multiprocess_can_split_ = True def test_stopwatch_overhead(self): # Wall Overhead start = time.time() cpu_start = time.clock() watch = StopWatch() for i in range(1, 1000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) cpu_stop = time.clock() stop = time.time() dur = stop - start cpu_dur = cpu_stop - cpu_start cpu_overhead = cpu_dur - watch.cpu_sum() wall_overhead = dur - watch.wall_sum() self.assertLess(cpu_overhead, 1) self.assertLess(wall_overhead, 1) self.assertLess(watch.cpu_sum(), 2 * watch.wall_sum()) if __name__ == '__main__': # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
TEST potentially fix brittle stopwatch test
TEST potentially fix brittle stopwatch test
Python
bsd-3-clause
automl/auto-sklearn,automl/auto-sklearn
--- +++ @@ -9,6 +9,7 @@ from __future__ import print_function import time import unittest +import unittest.mock from autosklearn.util import StopWatch @@ -17,29 +18,24 @@ _multiprocess_can_split_ = True def test_stopwatch_overhead(self): - # CPU overhead - start = time.clock() + + # Wall Overhead + start = time.time() + cpu_start = time.clock() watch = StopWatch() for i in range(1, 1000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) - stop = time.clock() - dur = stop - start - cpu_overhead = dur - watch.cpu_sum() - self.assertLess(cpu_overhead, 1.5) - - # Wall Overhead - start = time.time() - watch = StopWatch() - for i in range(1, 1000): - watch.start_task('task_%d' % i) - watch.stop_task('task_%d' % i) + cpu_stop = time.clock() stop = time.time() dur = stop - start + cpu_dur = cpu_stop - cpu_start + cpu_overhead = cpu_dur - watch.cpu_sum() wall_overhead = dur - watch.wall_sum() - self.assertLess(wall_overhead, 2) - self.assertLess(cpu_overhead, 2*wall_overhead) + self.assertLess(cpu_overhead, 1) + self.assertLess(wall_overhead, 1) + self.assertLess(watch.cpu_sum(), 2 * watch.wall_sum()) if __name__ == '__main__':
2a3a5fba536877c0ba735244a986e49605ce3fc0
tests/test_schematics_adapter.py
tests/test_schematics_adapter.py
from schematics.models import Model from schematics.types import IntType from hyp.adapters.schematics import SchematicsSerializerAdapter class Post(object): def __init__(self): self.id = 1 class Simple(Model): id = IntType() def test_object_conversion(): adapter = SchematicsSerializerAdapter(Simple) assert adapter.to_primitive(Post())['id'] == 1 def test_dict_conversion(): adapter = SchematicsSerializerAdapter(Simple) assert adapter.to_primitive({'id': 1})['id'] == 1
import pytest from schematics.models import Model from schematics.types import IntType from hyp.adapters.schematics import SchematicsSerializerAdapter class Post(object): def __init__(self): self.id = 1 class Simple(Model): id = IntType() @pytest.fixture def adapter(): return SchematicsSerializerAdapter(Simple) def test_object_conversion(adapter): assert adapter.to_primitive(Post())['id'] == 1 def test_dict_conversion(adapter): adapter = SchematicsSerializerAdapter(Simple) assert adapter.to_primitive({'id': 1})['id'] == 1
Convert the adapter into a pytest fixture
Convert the adapter into a pytest fixture
Python
mit
kalasjocke/hyp
--- +++ @@ -1,3 +1,4 @@ +import pytest from schematics.models import Model from schematics.types import IntType @@ -13,11 +14,15 @@ id = IntType() -def test_object_conversion(): - adapter = SchematicsSerializerAdapter(Simple) +@pytest.fixture +def adapter(): + return SchematicsSerializerAdapter(Simple) + + +def test_object_conversion(adapter): assert adapter.to_primitive(Post())['id'] == 1 -def test_dict_conversion(): +def test_dict_conversion(adapter): adapter = SchematicsSerializerAdapter(Simple) assert adapter.to_primitive({'id': 1})['id'] == 1
a8c7a6d6cd87f057fbd03c41cec41dba35e6bdf6
unittesting/test_color_scheme.py
unittesting/test_color_scheme.py
import sublime from sublime_plugin import ApplicationCommand from .mixin import UnitTestingMixin from .const import DONE_MESSAGE try: from ColorSchemeUnit.lib.runner import ColorSchemeUnit except Exception: print('ColorSchemeUnit runner could not be imported') class UnitTestingColorSchemeCommand(ApplicationCommand, UnitTestingMixin): def run(self, package=None, **kargs): if not package: return window = sublime.active_window() settings = self.load_unittesting_settings(package, **kargs) stream = self.load_stream(package, settings["output"]) # Make sure at least one file from the # package opened for ColorSchemeUnit. tests = sublime.find_resources("color_scheme_test*") tests = [t for t in tests if t.startswith("Packages/%s/" % package)] if not tests: stream.write("ERROR: No syntax_test files are found in %s!" % package) stream.write("\n") stream.write(DONE_MESSAGE) stream.close() return # trigger "Start reading output" stream.write("Running ColorSchemeUnit\n") stream.flush() view = window.open_file(sublime.packages_path().rstrip('Packages') + tests[0]) view.set_scratch(True) ColorSchemeUnit(window).run(output=stream)
import sublime from sublime_plugin import ApplicationCommand from .mixin import UnitTestingMixin from .const import DONE_MESSAGE try: from ColorSchemeUnit.lib.runner import ColorSchemeUnit except Exception: print('ColorSchemeUnit runner could not be imported') class UnitTestingColorSchemeCommand(ApplicationCommand, UnitTestingMixin): def run(self, package=None, **kargs): if not package: return window = sublime.active_window() settings = self.load_unittesting_settings(package, **kargs) stream = self.load_stream(package, settings["output"]) tests = sublime.find_resources("color_scheme_test*") tests = [t for t in tests if t.startswith("Packages/%s/" % package)] if not tests: stream.write("ERROR: No syntax_test files are found in %s!" % package) stream.write("\n") stream.write(DONE_MESSAGE) stream.close() return # trigger "Start reading output" stream.write("Running ColorSchemeUnit\n") stream.flush() result = ColorSchemeUnit(window).run(output=stream, package=package, async=False) if result: stream.write('\n') stream.write("OK.\n") else: stream.write('\n') stream.write("FAILED.\n") stream.write("\n") stream.write(DONE_MESSAGE) stream.close()
Use ColorSchemeunit new run with package API
Use ColorSchemeunit new run with package API Re: https://github.com/gerardroche/sublime-color-scheme-unit/issues/18 The new API allows to run with package name so Unittesting doesn't need to open any files before running the tests. I also added an async parameter which allows to run the tests in non async mode and get the result of the tests, True for pass and False for fail. This allows UnitTesting to handle printing the OK, FAILED and DONE messsages.
Python
mit
randy3k/UnitTesting,randy3k/UnitTesting,randy3k/UnitTesting,randy3k/UnitTesting
--- +++ @@ -19,8 +19,6 @@ settings = self.load_unittesting_settings(package, **kargs) stream = self.load_stream(package, settings["output"]) - # Make sure at least one file from the - # package opened for ColorSchemeUnit. tests = sublime.find_resources("color_scheme_test*") tests = [t for t in tests if t.startswith("Packages/%s/" % package)] @@ -35,7 +33,15 @@ stream.write("Running ColorSchemeUnit\n") stream.flush() - view = window.open_file(sublime.packages_path().rstrip('Packages') + tests[0]) - view.set_scratch(True) + result = ColorSchemeUnit(window).run(output=stream, package=package, async=False) - ColorSchemeUnit(window).run(output=stream) + if result: + stream.write('\n') + stream.write("OK.\n") + else: + stream.write('\n') + stream.write("FAILED.\n") + + stream.write("\n") + stream.write(DONE_MESSAGE) + stream.close()
1667e4c28d969af615d028a4b828cc2c868957bc
tests/git_code_debt/list_metrics_test.py
tests/git_code_debt/list_metrics_test.py
import __builtin__ import mock import pytest from git_code_debt.list_metrics import color from git_code_debt.list_metrics import CYAN from git_code_debt.list_metrics import main from git_code_debt.list_metrics import NORMAL @pytest.mark.integration def test_list_metricssmoke(): # This test is just to make sure that it doesn't fail catastrophically with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock: main([]) assert print_mock.called def test_color_no_color(): ret = color('foo', 'bar', False) assert ret == 'foo' def test_colored(): ret = color('foo', CYAN, True) assert ret == CYAN + 'foo' + NORMAL
import __builtin__ import mock import pytest from git_code_debt.list_metrics import color from git_code_debt.list_metrics import CYAN from git_code_debt.list_metrics import main from git_code_debt.list_metrics import NORMAL @pytest.yield_fixture def print_mock(): with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock: yield print_mock @pytest.mark.integration def test_list_metrics_smoke(print_mock): # This test is just to make sure that it doesn't fail catastrophically main([]) assert print_mock.called @pytest.mark.integration def test_list_metrics_no_color_smoke(print_mock): main(['--color', 'never']) assert all([ '\033' not in call[0][0] for call in print_mock.call_args_list ]) def test_color_no_color(): ret = color('foo', 'bar', False) assert ret == 'foo' def test_colored(): ret = color('foo', CYAN, True) assert ret == CYAN + 'foo' + NORMAL
Add integration test for --color never.
Add integration test for --color never.
Python
mit
Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt
--- +++ @@ -10,12 +10,25 @@ from git_code_debt.list_metrics import NORMAL +@pytest.yield_fixture +def print_mock(): + with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock: + yield print_mock + + @pytest.mark.integration -def test_list_metricssmoke(): +def test_list_metrics_smoke(print_mock): # This test is just to make sure that it doesn't fail catastrophically - with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock: - main([]) - assert print_mock.called + main([]) + assert print_mock.called + + +@pytest.mark.integration +def test_list_metrics_no_color_smoke(print_mock): + main(['--color', 'never']) + assert all([ + '\033' not in call[0][0] for call in print_mock.call_args_list + ]) def test_color_no_color():
14be519ba4bb09957865f1810c88c02f6b359c48
tests/utilities/test_customtreeview.py
tests/utilities/test_customtreeview.py
from __future__ import absolute_import, print_function import unittest from qtpy.QtWidgets import QApplication from addie.utilities.customtreeview import CustomizedTreeView class CustomTreeViewTests(unittest.TestCase): def setUp(self): self.main_window = QApplication([]) def tearDown(self): self.main_window.quit() def test_get_selected_items(self): """Test get_selected_items in tree of CustomizedTreeView""" treeview = CustomizedTreeView(None) items = treeview.get_selected_items() self.assertEqual(items, []) self.assertEqual(type(items), list)
from __future__ import absolute_import, print_function import pytest from addie.utilities.customtreeview import CustomizedTreeView @pytest.fixture def custom_tree_view(qtbot): return CustomizedTreeView(None) def test_get_selected_items(qtbot, custom_tree_view): """Test get_selected_items in tree of CustomizedTreeView""" items = custom_tree_view.get_selected_items() assert items == [] assert type(items) == list
Refactor CustomTreeView test to use pytest-qt
Refactor CustomTreeView test to use pytest-qt
Python
mit
neutrons/FastGR,neutrons/FastGR,neutrons/FastGR
--- +++ @@ -1,19 +1,15 @@ from __future__ import absolute_import, print_function -import unittest -from qtpy.QtWidgets import QApplication +import pytest from addie.utilities.customtreeview import CustomizedTreeView -class CustomTreeViewTests(unittest.TestCase): - def setUp(self): - self.main_window = QApplication([]) +@pytest.fixture +def custom_tree_view(qtbot): + return CustomizedTreeView(None) - def tearDown(self): - self.main_window.quit() - def test_get_selected_items(self): - """Test get_selected_items in tree of CustomizedTreeView""" - treeview = CustomizedTreeView(None) - items = treeview.get_selected_items() - self.assertEqual(items, []) - self.assertEqual(type(items), list) +def test_get_selected_items(qtbot, custom_tree_view): + """Test get_selected_items in tree of CustomizedTreeView""" + items = custom_tree_view.get_selected_items() + assert items == [] + assert type(items) == list
f3763c417d745463361b054fd4ffa0ddf35833eb
src/server/Universe.py
src/server/Universe.py
class Universe: def __init__(self, height=100000000, width=100000000): self.entities = [] self.height = height self.width = width self.teams = [] self.state = [] def add(self, entity): self.entities.append(entity) def remove(self, entity): self.entities.remove(entity) # Time passes and position updates during tick def tick(self, duration): for i in self.entities: i.tick(duration) # Position changed, so check for collisions def collide(self): for i in self.entities: for j in self.entities: if i != j: if i.checkCollide(j): i.collide(j) # Now that damage is dealt in collisions, destroy objects and update logic def tock(self): for i in self.entities: i.tock() def dumpState(self): return self.state
class Universe: def __init__(self, height=100000000, width=100000000): self.entities = [] self.height = height self.width = width self.teams = [] self.state = [] self.maxID = 0 def add(self, entity): maxID += 1 entity.id = maxID self.entities.append(entity) def remove(self, entity): self.entities.remove(entity) # Time passes and position updates during tick def tick(self, duration): for i in self.entities: i.tick(duration) # Position changed, so check for collisions def collide(self): for i in self.entities: for j in self.entities: if i != j: if i.checkCollide(j): i.collide(j) # Now that damage is dealt in collisions, destroy objects and update logic def tock(self): for i in self.entities: i.tock() def dumpState(self): return self.state
Add ID to Entity upon creation
Add ID to Entity upon creation
Python
mit
cnlohr/bridgesim,cnlohr/bridgesim,cnlohr/bridgesim,cnlohr/bridgesim
--- +++ @@ -5,8 +5,11 @@ self.width = width self.teams = [] self.state = [] + self.maxID = 0 def add(self, entity): + maxID += 1 + entity.id = maxID self.entities.append(entity) def remove(self, entity):
79d868ed68148b1e8f7c046b1ae9bb4b5a413c99
base/components/accounts/admin.py
base/components/accounts/admin.py
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group from .models import Editor class ContributorMixin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if not change: obj.submitted_by = request.user obj.edited_by.add(request.user) obj.save() super(ContributorMixin, self).save_model(request, obj, form, change) class EditorAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('username', 'password')}), ('Personal Information', {'fields': ('name', 'email')}), ('Important Dates', { 'classes': ('grp-collapse grp-closed',), 'fields': ('started', 'last_login', 'active_since') }), ('Permissions', { 'classes': ('grp-collapse grp-closed',), 'fields': ('is_active', 'is_staff', 'is_superuser') }) ) list_display = ['username', 'name', 'email', 'is_active', 'is_staff', 'is_superuser'] list_filter = ['is_active', 'is_staff', 'is_superuser'] admin.site.register(Editor, EditorAdmin) admin.site.unregister(Group)
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group from .models import Editor class ContributorMixin(admin.ModelAdmin): def save_model(self, request, obj, form, change): super(ContributorMixin, self).save_model(request, obj, form, change) if not change: obj.submitted_by = request.user obj.edited_by.add(request.user) obj.save() class EditorAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('username', 'password')}), ('Personal Information', {'fields': ('name', 'email')}), ('Important Dates', { 'classes': ('grp-collapse grp-closed',), 'fields': ('started', 'last_login', 'active_since') }), ('Permissions', { 'classes': ('grp-collapse grp-closed',), 'fields': ('is_active', 'is_staff', 'is_superuser') }) ) list_display = ['username', 'name', 'email', 'is_active', 'is_staff', 'is_superuser'] list_filter = ['is_active', 'is_staff', 'is_superuser'] admin.site.register(Editor, EditorAdmin) admin.site.unregister(Group)
Move the super() up on ContributorMixin.
Move the super() up on ContributorMixin.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
--- +++ @@ -7,11 +7,11 @@ class ContributorMixin(admin.ModelAdmin): def save_model(self, request, obj, form, change): + super(ContributorMixin, self).save_model(request, obj, form, change) if not change: obj.submitted_by = request.user obj.edited_by.add(request.user) obj.save() - super(ContributorMixin, self).save_model(request, obj, form, change) class EditorAdmin(admin.ModelAdmin):
1da9b6538294744aa1d68ec6f48bebbbf5d714bb
bot/action/standard/admin/fail.py
bot/action/standard/admin/fail.py
from bot.action.core.action import Action class FailAction(Action): def process(self, event): raise NotARealError("simulated error") class NotARealError(Exception): pass
from bot.action.core.action import Action class FailAction(Action): def process(self, event): if event.command_args == "fatal": raise NotARealFatalError("simulated fatal error") raise NotARealError("simulated error") class NotARealError(Exception): pass class NotARealFatalError(BaseException): pass
Allow to simulate fatal errors
Allow to simulate fatal errors
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
--- +++ @@ -3,8 +3,14 @@ class FailAction(Action): def process(self, event): + if event.command_args == "fatal": + raise NotARealFatalError("simulated fatal error") raise NotARealError("simulated error") class NotARealError(Exception): pass + + +class NotARealFatalError(BaseException): + pass
f0d629ae8b4568b2aceaf38779c8b07832e860b0
teamspeak_web_utils.py
teamspeak_web_utils.py
import re from bs4 import BeautifulSoup import cfscrape def nplstatus(): scraper = cfscrape.create_scraper() data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content soup = BeautifulSoup(data, 'html.parser') raw_status = soup.find_all(class_='register_linklabel')[2].span return not raw_status def latest_version(): scraper = cfscrape.create_scraper() data = scraper.get('http://teamspeak.com/downloads').content soup = BeautifulSoup(data, 'html.parser') def search(search_string): return soup.find_all(text=re.compile(search_string))[0].parent.\ find(class_='version').text return search(r'Client\ 64\-bit'), search(r'Server\ 64\-bit')
import re from bs4 import BeautifulSoup import cfscrape def nplstatus(): scraper = cfscrape.create_scraper() data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content soup = BeautifulSoup(data, 'html.parser') raw_status = soup.find_all(class_='register_linklabel')[2].span return not raw_status def latest_version(): scraper = cfscrape.create_scraper() data = scraper.get('http://teamspeak.com/downloads').content soup = BeautifulSoup(data, 'html.parser') def search(search_string): return soup.find_all(text=re.compile(search_string))[0].parent.\ find(class_='version').text def clean(s): return s.replace('\n', '').strip() return clean(search(r'Client\ 64\-bit')), \ clean(search(r'Server\ 64\-bit'))
Clean string returned by website
Clean string returned by website => remove newline-characters and strip
Python
mit
Thor77/TeamspeakIRC
--- +++ @@ -21,4 +21,8 @@ def search(search_string): return soup.find_all(text=re.compile(search_string))[0].parent.\ find(class_='version').text - return search(r'Client\ 64\-bit'), search(r'Server\ 64\-bit') + + def clean(s): + return s.replace('\n', '').strip() + return clean(search(r'Client\ 64\-bit')), \ + clean(search(r'Server\ 64\-bit'))
75eb6f93fff381953788a98aac8ee61bbf36c900
apps/storybase/templatetags/verbatim.py
apps/storybase/templatetags/verbatim.py
""" Handlebars templates use constructs like: {{if condition}} print something{{/if}} This, of course, completely screws up Django templates, because Django thinks {{ and }} mean something. Wrap {% verbatim %} and {% endverbatim %} around those blocks of Handlebars templates and this will try its best to output the contents with no changes. """ from django import template # For Django >= 1.5, use the default verbatim tag implementation if not hasattr(template.defaulttags, 'verbatim'): register = template.Library() class VerbatimNode(template.Node): def __init__(self, text): self.text = text def render(self, context): return self.text @register.tag def verbatim(parser, token): text = [] while 1: token = parser.tokens.pop(0) if token.contents == 'endverbatim': break if token.token_type == template.TOKEN_VAR: text.append('{{') elif token.token_type == template.TOKEN_BLOCK: text.append('{%') text.append(token.contents) if token.token_type == template.TOKEN_VAR: text.append('}}') elif token.token_type == template.TOKEN_BLOCK: text.append('%}') return VerbatimNode(''.join(text))
""" Handlebars templates use constructs like: {{if condition}} print something{{/if}} This, of course, completely screws up Django templates, because Django thinks {{ and }} mean something. Wrap {% verbatim %} and {% endverbatim %} around those blocks of Handlebars templates and this will try its best to output the contents with no changes. """ from django import template register = template.Library() # For Django >= 1.5, use the default verbatim tag implementation if not hasattr(template.defaulttags, 'verbatim'): class VerbatimNode(template.Node): def __init__(self, text): self.text = text def render(self, context): return self.text @register.tag def verbatim(parser, token): text = [] while 1: token = parser.tokens.pop(0) if token.contents == 'endverbatim': break if token.token_type == template.TOKEN_VAR: text.append('{{') elif token.token_type == template.TOKEN_BLOCK: text.append('{%') text.append(token.contents) if token.token_type == template.TOKEN_VAR: text.append('}}') elif token.token_type == template.TOKEN_BLOCK: text.append('%}') return VerbatimNode(''.join(text))
Move register outside of guard
Move register outside of guard Even if we don't load the ``verbatim`` tag backbport, the module still needs to have a ``register`` variable. Addresses #660
Python
mit
denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase
--- +++ @@ -13,10 +13,10 @@ from django import template +register = template.Library() + # For Django >= 1.5, use the default verbatim tag implementation if not hasattr(template.defaulttags, 'verbatim'): - register = template.Library() - class VerbatimNode(template.Node): def __init__(self, text):
d7b532e83b30e429a9c87b52799c30dda6c4628c
plasmapy/physics/tests/test_dimensionless.py
plasmapy/physics/tests/test_dimensionless.py
from plasmapy.physics.dimensionless import (beta) import astropy.units as u B = 1.0 * u.T n_i = 5e19 * u.m ** -3 T_e = 1e6 * u.K def test_beta(): # Check that beta is dimensionless float(beta(T_e, n_i, B))
from plasmapy.physics.dimensionless import (beta) import astropy.units as u import numpy as np B = 1.0 * u.T n = 5e19 * u.m ** -3 T = 1e6 * u.K def test_beta_dimensionless(): # Check that beta is dimensionless float(beta(T, n, B)) def quantum_theta_dimensionless(): # Check that quantum theta is dimensionless float(quantum_theta(T, n)) def test_beta_nan(): # Check that nans are passed through properly B = np.array([1, np.nan]) * u.T n = np.array([1, 1]) * u.cm**-3 T = np.array([1, 1]) * u.K out = beta(T, n, B) assert out[1] == np.nan * u.dimensionless_unscaled
Add test for beta passing through nans
Add test for beta passing through nans
Python
bsd-3-clause
StanczakDominik/PlasmaPy
--- +++ @@ -1,12 +1,27 @@ from plasmapy.physics.dimensionless import (beta) import astropy.units as u +import numpy as np B = 1.0 * u.T -n_i = 5e19 * u.m ** -3 -T_e = 1e6 * u.K +n = 5e19 * u.m ** -3 +T = 1e6 * u.K -def test_beta(): +def test_beta_dimensionless(): # Check that beta is dimensionless - float(beta(T_e, n_i, B)) + float(beta(T, n, B)) + + +def quantum_theta_dimensionless(): + # Check that quantum theta is dimensionless + float(quantum_theta(T, n)) + + +def test_beta_nan(): + # Check that nans are passed through properly + B = np.array([1, np.nan]) * u.T + n = np.array([1, 1]) * u.cm**-3 + T = np.array([1, 1]) * u.K + out = beta(T, n, B) + assert out[1] == np.nan * u.dimensionless_unscaled
4bfa6627b14c3e00e32b10a2806f02d4fafd6509
chipy_org/libs/social_auth_pipelines.py
chipy_org/libs/social_auth_pipelines.py
from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name == 'google-oauth2': # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github']: # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
Fix false positive for the social login
Fix false positive for the social login
Python
mit
brianray/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,tanyaschlusser/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,chicagopython/chipy.org,brianray/chipy.org,agfor/chipy.org
--- +++ @@ -1,3 +1,4 @@ +from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email @@ -6,12 +7,17 @@ def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] - if backend.name == 'google-oauth2': + if backend.name in ['google-oauth2', 'github']: # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) - msg = ugettext('This email is already in use. First login with your other account and ' - 'under the top right menu click add account.') - raise AuthAlreadyAssociated(backend, msg % { - 'provider': backend.name - }) + email = kwargs['details'].get('email') + + if email: + User = get_user_model() + if User.objects.filter(email=email).exists(): + msg = ugettext('This email is already in use. First login with your other account and ' + 'under the top right menu click add account.') + raise AuthAlreadyAssociated(backend, msg % { + 'provider': backend.name + })
02095500794565fc84aee8272bfece1b39bc270f
examples/example_architecture_upload.py
examples/example_architecture_upload.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import glob import datetime from teamscale_client import TeamscaleClient from teamscale_client.constants import CoverageFormats TEAMSCALE_URL = "http://localhost:8080" USERNAME = "admin" PASSWORD = "admin" PROJECT_NAME = "test" if __name__ == '__main__': client = TeamscaleClient(TEAMSCALE_URL, USERNAME, PASSWORD, PROJECT_NAME) client.upload_architectures({"architectures/system.architecture": "/home/user/a/path/to/system.architecture"}, datetime.datetime.now(), "Upload architecture", "test-partition")
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import glob import datetime from teamscale_client import TeamscaleClient from teamscale_client.constants import CoverageFormats TEAMSCALE_URL = "http://localhost:8080" USERNAME = "admin" PASSWORD = "F0VzQ_2Q2wqGmBFBrI6EIVWVK4QxR55o" PROJECT_NAME = "test" if __name__ == '__main__': client = TeamscaleClient(TEAMSCALE_URL, USERNAME, PASSWORD, PROJECT_NAME) client.upload_architectures({"archs/abap.architecture": "/home/kinnen/repos/conqat-cqse_bmw/engine/eu.cqse.conqat.engine.abap/abap_exporter.architecture"}, datetime.datetime.now(), "Upload architecture")
Update example for architecture upload
Update example for architecture upload
Python
apache-2.0
cqse/teamscale-client-python
--- +++ @@ -12,11 +12,11 @@ TEAMSCALE_URL = "http://localhost:8080" USERNAME = "admin" -PASSWORD = "admin" +PASSWORD = "F0VzQ_2Q2wqGmBFBrI6EIVWVK4QxR55o" PROJECT_NAME = "test" if __name__ == '__main__': client = TeamscaleClient(TEAMSCALE_URL, USERNAME, PASSWORD, PROJECT_NAME) - client.upload_architectures({"architectures/system.architecture": "/home/user/a/path/to/system.architecture"}, datetime.datetime.now(), "Upload architecture", "test-partition") + client.upload_architectures({"archs/abap.architecture": "/home/kinnen/repos/conqat-cqse_bmw/engine/eu.cqse.conqat.engine.abap/abap_exporter.architecture"}, datetime.datetime.now(), "Upload architecture")
f9c98ff2c5166f113918f9dc575abcad781bce01
tests/test-vext-api.py
tests/test-vext-api.py
import unittest from vext.env import findsyspy, in_venv class TestVextAPI(unittest.TestCase): def test_findsyspy(self): # Stub test, checks no exceptions are thrown. findsyspy() def test_invenv(self): # Stub test, checks no exceptions are thrown. in_venv() if __name__ == "__main__": unittest.main()
import os import unittest from vext.env import findsyspy, in_venv class TestVextAPI(unittest.TestCase): def test_findsyspy(self): # Stub test, checks no exceptions are thrown. findsyspy() def test_invenv(self): # Stub test, checks no exceptions are thrown. # TODO, fake running inside and outside an virtualenv and actually check the return value in_venv() if __name__ == "__main__": unittest.main()
Revert trying to test in virtualenv for now.
Revert trying to test in virtualenv for now.
Python
mit
stuaxo/vext
--- +++ @@ -1,3 +1,4 @@ +import os import unittest from vext.env import findsyspy, in_venv @@ -10,6 +11,8 @@ def test_invenv(self): # Stub test, checks no exceptions are thrown. + + # TODO, fake running inside and outside an virtualenv and actually check the return value in_venv()
dfa144f02ac43012ea51f24b9752eabe8a1ef9b5
opps/images/templatetags/images_tags.py
opps/images/templatetags/images_tags.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop """ if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign """ new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_x2), (image.crop_y1, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop """ if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign """ new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
Fix rules x,y on image_obj Coordinates for manual cropping. The first pair are X and Y coordinates, for the left, top point and the second pair are X and Y coordinates, for the right, bottom point (thus forming the square to crop);
Fix rules x,y on image_obj Coordinates for manual cropping. The first pair are X and Y coordinates, for the left, top point and the second pair are X and Y coordinates, for the right, bottom point (thus forming the square to crop);
Python
mit
williamroot/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,jeanmask/opps,opps/opps,YACOWS/opps,opps/opps,williamroot/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps
--- +++ @@ -28,8 +28,8 @@ if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: - new['crop'] = ((image.crop_x1, image.crop_x2), - (image.crop_y1, image.crop_y2)) + new['crop'] = ((image.crop_x1, image.crop_y1), + (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
e93c29e7d3bbb66da000ec46e1908b36c2c497e1
lab_assistant/storage/__init__.py
lab_assistant/storage/__init__.py
from copy import deepcopy from simpleflake import simpleflake from lab_assistant import conf, utils __all__ = [ 'get_storage', 'store', 'retrieve', 'retrieve_all', 'clear', ] def get_storage(path=None, name='Experiment', **opts): if not path: path = conf.storage['path'] _opts = deepcopy(conf.storage.get('options', {})) _opts.update(opts) opts = _opts if path in get_storage._cache: return get_storage._cache[path] Storage = utils.import_path(path) get_storage._cache[path] = Storage(name, **opts) return get_storage._cache[path] get_storage._cache = {} def store(result, storage=None): storage = storage or get_storage() key = simpleflake() storage.set(key, result) return key def retrieve(key, storage=None): storage = storage or get_storage() return storage.get(key) def retrieve_all(storage=None): return (storage or get_storage()).list() def remove(key, storage=None): (storage or get_storage()).remove(key) def clear(storage=None): return (storage or get_storage()).clear()
from copy import deepcopy from simpleflake import simpleflake from lab_assistant import conf, utils __all__ = [ 'get_storage', 'store', 'retrieve', 'retrieve_all', 'clear', ] def get_storage(path=None, name='Experiment', **opts): if not path: path = conf.storage['path'] _opts = deepcopy(conf.storage.get('options', {})) _opts.update(opts) opts = _opts if path in get_storage._cache: return get_storage._cache[path] Storage = utils.import_path(path) get_storage._cache[path] = Storage(name, **opts) return get_storage._cache[path] get_storage._cache = {} def store(result, storage=None): storage = storage or get_storage(name=result.experiment.name) key = simpleflake() storage.set(key, result) return key def retrieve(key, storage=None): storage = storage or get_storage() return storage.get(key) def retrieve_all(storage=None): return (storage or get_storage()).list() def remove(key, storage=None): (storage or get_storage()).remove(key) def clear(storage=None): return (storage or get_storage()).clear()
Store results under correct experiment key
Store results under correct experiment key
Python
mit
joealcorn/lab_assistant
--- +++ @@ -31,7 +31,7 @@ def store(result, storage=None): - storage = storage or get_storage() + storage = storage or get_storage(name=result.experiment.name) key = simpleflake() storage.set(key, result) return key
77f4fca43b1d4be85894ad565801d8a333008fdc
Lib/test/test_pep263.py
Lib/test/test_pep263.py
#! -*- coding: koi8-r -*- import unittest from test import test_support class PEP263Test(unittest.TestCase): def test_pep263(self): self.assertEqual( u"".encode("utf-8"), '\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd' ) self.assertEqual( u"\".encode("utf-8"), '\\\xd0\x9f' ) def test_main(): test_support.run_unittest(PEP263Test) if __name__=="__main__": test_main()
#! -*- coding: koi8-r -*- # This file is marked as binary in the CVS, to prevent MacCVS from recoding it. import unittest from test import test_support class PEP263Test(unittest.TestCase): def test_pep263(self): self.assertEqual( u"".encode("utf-8"), '\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd' ) self.assertEqual( u"\".encode("utf-8"), '\\\xd0\x9f' ) def test_main(): test_support.run_unittest(PEP263Test) if __name__=="__main__": test_main()
Add a comment explaining -kb.
Add a comment explaining -kb.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -1,4 +1,5 @@ #! -*- coding: koi8-r -*- +# This file is marked as binary in the CVS, to prevent MacCVS from recoding it. import unittest from test import test_support
aaad392fedca6b3f9879240591877f6a64d907c3
wordcloud/wordcloud.py
wordcloud/wordcloud.py
import os from operator import itemgetter from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines() def popular_words(max_entries=20): sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date') cloudlist = [] try: # Generate tag cloud from content of returned entries words = {} for entry in sqs[:max_entries]: text = entry.object.content for x in text.lower().split(): cleanx = x.replace(',', '').replace('.', '').replace('"', '').strip() if cleanx not in STOP_WORDS: # and not cleanx in hansard_words: words[cleanx] = 1 + words.get(cleanx, 0) for word in words: cloudlist.append( { "text": word, "weight": words.get(word), "link": "/search/hansard/?q=%s" % word, } ) sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:25] except: sortedlist = [] return sortedlist
import os from operator import itemgetter from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines() def popular_words(max_entries=20, max_words=25): sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date') cloudlist = [] try: # Generate tag cloud from content of returned entries words = {} for entry in sqs[:max_entries]: text = entry.object.content for x in text.lower().split(): cleanx = x.replace(',', '').replace('.', '').replace('"', '').strip() if cleanx not in STOP_WORDS: # and not cleanx in hansard_words: words[cleanx] = 1 + words.get(cleanx, 0) for word in words: cloudlist.append( { "text": word, "weight": words.get(word), "link": "/search/hansard/?q=%s" % word, } ) sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:max_words] except: sortedlist = [] return sortedlist
Make maximum number of words a parameter
Make maximum number of words a parameter
Python
agpl-3.0
geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola
--- +++ @@ -10,7 +10,7 @@ STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines() -def popular_words(max_entries=20): +def popular_words(max_entries=20, max_words=25): sqs = SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date') cloudlist = [] @@ -35,7 +35,7 @@ } ) - sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:25] + sortedlist = sorted(cloudlist, key=itemgetter('weight'), reverse=True)[:max_words] except: sortedlist = []
baaa7e4818ac71898ff3b601d006f5e23d444bee
pyes/exceptions.py
pyes/exceptions.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Alberto Paro' __all__ = ['NoServerAvailable', "QueryError", "NotFoundException", "AlreadyExistsException", "IndexMissingException", "SearchPhaseExecutionException", "InvalidQuery", "InvalidParameterQuery", "QueryParameterError", "ReplicationShardOperationFailedException", "ClusterBlockException", "MapperParsingException", "ElasticSearchException", ] class NoServerAvailable(Exception): pass class InvalidQuery(Exception): pass class InvalidParameterQuery(InvalidQuery): pass class QueryError(Exception): pass class QueryParameterError(Exception): pass class ElasticSearchException(Exception): """Base class of exceptions raised as a result of parsing an error return from ElasticSearch. An exception of this class will be raised if no more specific subclass is appropriate. """ def __init__(self, error, status=None, result=None): super(ElasticSearchException, self).__init__(error) self.status = status self.result = result class ElasticSearchIllegalArgumentException(ElasticSearchException): pass class IndexMissingException(ElasticSearchException): pass class NotFoundException(ElasticSearchException): pass class AlreadyExistsException(ElasticSearchException): pass class SearchPhaseExecutionException(ElasticSearchException): pass class ReplicationShardOperationFailedException(ElasticSearchException): pass class ClusterBlockException(ElasticSearchException): pass class MapperParsingException(ElasticSearchException): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Alberto Paro' __all__ = ['NoServerAvailable', "QueryError", "NotFoundException", "AlreadyExistsException", "IndexMissingException", "SearchPhaseExecutionException", "InvalidQuery", "InvalidParameterQuery", "QueryParameterError", "ScriptFieldsError", "ReplicationShardOperationFailedException", "ClusterBlockException", "MapperParsingException", "ElasticSearchException", ] class NoServerAvailable(Exception): pass class InvalidQuery(Exception): pass class InvalidParameterQuery(InvalidQuery): pass class QueryError(Exception): pass class QueryParameterError(Exception): pass class ScriptFieldsError(Exception): pass class ElasticSearchException(Exception): """Base class of exceptions raised as a result of parsing an error return from ElasticSearch. An exception of this class will be raised if no more specific subclass is appropriate. """ def __init__(self, error, status=None, result=None): super(ElasticSearchException, self).__init__(error) self.status = status self.result = result class ElasticSearchIllegalArgumentException(ElasticSearchException): pass class IndexMissingException(ElasticSearchException): pass class NotFoundException(ElasticSearchException): pass class AlreadyExistsException(ElasticSearchException): pass class SearchPhaseExecutionException(ElasticSearchException): pass class ReplicationShardOperationFailedException(ElasticSearchException): pass class ClusterBlockException(ElasticSearchException): pass class MapperParsingException(ElasticSearchException): pass
Add exception type for script_fields related errors
Add exception type for script_fields related errors
Python
bsd-3-clause
jayzeng/pyes,rookdev/pyes,haiwen/pyes,mavarick/pyes,haiwen/pyes,mouadino/pyes,haiwen/pyes,HackLinux/pyes,Fiedzia/pyes,jayzeng/pyes,mavarick/pyes,aparo/pyes,aparo/pyes,mouadino/pyes,Fiedzia/pyes,mavarick/pyes,HackLinux/pyes,aparo/pyes,rookdev/pyes,Fiedzia/pyes,jayzeng/pyes,HackLinux/pyes
--- +++ @@ -12,6 +12,7 @@ "InvalidQuery", "InvalidParameterQuery", "QueryParameterError", + "ScriptFieldsError", "ReplicationShardOperationFailedException", "ClusterBlockException", "MapperParsingException", @@ -34,6 +35,8 @@ class QueryParameterError(Exception): pass +class ScriptFieldsError(Exception): + pass class ElasticSearchException(Exception): """Base class of exceptions raised as a result of parsing an error return
032256c7e13cd6630b7c6da16c083ad5b622aa64
pynuts/__init__.py
pynuts/__init__.py
"""__init__ file for Pynuts.""" import flask from flask.ext.sqlalchemy import SQLAlchemy import document import view class Pynuts(flask.Flask): """Create the Pynuts class. :param import_name: Flask application name :param config: Flask application configuration :param reflect: Create models with database data .. seealso:: `Flask Application <http://flask.pocoo.org/docs/api/>`_ """ def __init__(self, import_name, config=None, reflect=False, *args, **kwargs): super(Pynuts, self).__init__(import_name, *args, **kwargs) self.config.update(config or {}) self.db = SQLAlchemy(self) self.documents = {} if reflect: self.db.metadata.reflect(bind=self.db.get_engine(self)) class Document(document.Document): """Document base class of the application.""" _pynuts = self self.Document = Document class ModelView(view.ModelView): """Model view base class of the application.""" _pynuts = self self.ModelView = ModelView def render_rest(self, document_type, part='index.rst.jinja2', **kwargs): return self.documents[document_type].generate_rest(part, **kwargs)
"""__init__ file for Pynuts.""" import flask from flask.ext.sqlalchemy import SQLAlchemy import document import view class Pynuts(flask.Flask): """Create the Pynuts class. :param import_name: Flask application name :param config: Flask application configuration :param reflect: Create models with database data .. seealso:: `Flask Application <http://flask.pocoo.org/docs/api/>`_ """ def __init__(self, import_name, config=None, reflect=False, *args, **kwargs): super(Pynuts, self).__init__(import_name, *args, **kwargs) self.config.update(config or {}) self.db = SQLAlchemy(self) self.documents = {} self.views = {} if reflect: self.db.metadata.reflect(bind=self.db.get_engine(self)) class Document(document.Document): """Document base class of the application.""" _pynuts = self self.Document = Document class ModelView(view.ModelView): """Model view base class of the application.""" _pynuts = self self.ModelView = ModelView def render_rest(self, document_type, part='index.rst.jinja2', **kwargs): return self.documents[document_type].generate_rest(part, **kwargs)
Add views in Pynuts init
Add views in Pynuts init
Python
bsd-3-clause
Kozea/Pynuts,Kozea/Pynuts,Kozea/Pynuts
--- +++ @@ -24,6 +24,7 @@ self.config.update(config or {}) self.db = SQLAlchemy(self) self.documents = {} + self.views = {} if reflect: self.db.metadata.reflect(bind=self.db.get_engine(self))
0de68abab608680d4ef390fea572828fb12b6abd
rounding/common.py
rounding/common.py
''' Created on Oct 6, 2013 @author: dmaust ''' import math class RounderBase(object): ''' Abstract base class for rounding ''' def __init__(self, precision=0): ''' Constructor ''' self.precision = precision self.cumulative_error = 0 def _get_fraction(self, x): scale = 10.0**self.precision scaled_x = x * scale fraction = scaled_x - math.floor(scaled_x) return fraction, scaled_x, scale def _record_roundoff_error(self, x, result): self.cumulative_error += result - x @property def roundoff_error(self): return self.cumulative_error
''' Created on Oct 6, 2013 @author: dmaust ''' import math class RounderBase(object): ''' Abstract base class for rounding ''' def __init__(self, precision=0): ''' Constructor ''' self.precision = precision self.cumulative_error = 0 self.count = 0 def _get_fraction(self, x): scale = 10.0**self.precision scaled_x = x * scale fraction = scaled_x - math.floor(scaled_x) return fraction, scaled_x, scale def _record_roundoff_error(self, x, result): self.cumulative_error += result - x self.count += 1 @property def roundoff_error(self): return self.cumulative_error @property def average_roundoff(self): return self.cumulative_error / self.count
Add average_roundoff to rounding base class.
Add average_roundoff to rounding base class.
Python
apache-2.0
dmaust/rounding
--- +++ @@ -17,6 +17,7 @@ ''' self.precision = precision self.cumulative_error = 0 + self.count = 0 def _get_fraction(self, x): @@ -27,7 +28,12 @@ def _record_roundoff_error(self, x, result): self.cumulative_error += result - x + self.count += 1 @property def roundoff_error(self): return self.cumulative_error + + @property + def average_roundoff(self): + return self.cumulative_error / self.count
b6a3890efc1716877eff7cce7f451df82cc3ca5c
services/heroku.py
services/heroku.py
import foauth.providers class Heroku(foauth.providers.OAuth2): # General info about the provider provider_url = 'https://heroku.com/' docs_url = 'https://devcenter.heroku.com/articles/platform-api-reference' category = 'Code' # URLs to interact with the API authorize_url = 'https://id.heroku.com/oauth/authorize' access_token_url = 'https://id.heroku.com/oauth/token' api_domain = 'api.heroku.com' available_permissions = [ ('identity', 'read your account information'), ('read', 'read all of your apps and resources, excluding configuration values'), ('write', 'write to all of your apps and resources, excluding configuration values'), ('read-protected', 'read all of your apps and resources, including configuration values'), ('write-protected', 'write to all of your apps and resources, including configuration values'), ('global', 'read and write to all of your account, apps and resources'), ] def get_user_id(self, key): r = self.api(key, self.api_domain, u'/account') return unicode(r.json()[u'id'])
import foauth.providers class Heroku(foauth.providers.OAuth2): # General info about the provider provider_url = 'https://heroku.com/' docs_url = 'https://devcenter.heroku.com/articles/platform-api-reference' category = 'Code' # URLs to interact with the API authorize_url = 'https://id.heroku.com/oauth/authorize' access_token_url = 'https://id.heroku.com/oauth/token' api_domain = 'api.heroku.com' available_permissions = [ (None, 'read your account information'), ('read', 'read all of your apps and resources, excluding configuration values'), ('write', 'write to all of your apps and resources, excluding configuration values'), ('read-protected', 'read all of your apps and resources, including configuration values'), ('write-protected', 'write to all of your apps and resources, including configuration values'), ('global', 'read and write to all of your account, apps and resources'), ] permissions_widget = 'radio' def get_authorize_params(self, redirect_uri, scopes): params = super(Heroku, self).get_authorize_params(redirect_uri, scopes) params['scope'] = scopes[0] or 'identity' return params def get_user_id(self, key): r = self.api(key, self.api_domain, u'/account') return unicode(r.json()[u'id'])
Rewrite Heroku's scope handling a bit to better match reality
Rewrite Heroku's scope handling a bit to better match reality
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
--- +++ @@ -13,13 +13,19 @@ api_domain = 'api.heroku.com' available_permissions = [ - ('identity', 'read your account information'), + (None, 'read your account information'), ('read', 'read all of your apps and resources, excluding configuration values'), ('write', 'write to all of your apps and resources, excluding configuration values'), ('read-protected', 'read all of your apps and resources, including configuration values'), ('write-protected', 'write to all of your apps and resources, including configuration values'), ('global', 'read and write to all of your account, apps and resources'), ] + permissions_widget = 'radio' + + def get_authorize_params(self, redirect_uri, scopes): + params = super(Heroku, self).get_authorize_params(redirect_uri, scopes) + params['scope'] = scopes[0] or 'identity' + return params def get_user_id(self, key): r = self.api(key, self.api_domain, u'/account')
c8422778e31888cbc02dc764af875114916e5f88
smsviewer/views.py
smsviewer/views.py
from pyramid.view import view_config from lxml import etree @view_config(route_name='index', renderer='index.mako') def my_view(request): smsfile = "sms.xml" with open(smsfile) as f: tree = etree.parse(f) root = tree.getroot() return {"messages": sorted([e for e in root if e.get("contact_name") == "Lacey Shankle"], key=lambda message: message.get("date"))} return {'project': 'smsviewer'}
from pyramid.view import view_config from lxml import etree @view_config(route_name='index', renderer='index.mako') def my_view(request): smsfile = "sms.xml" with open(smsfile) as f: tree = etree.parse(f) root = tree.getroot() els = root.xpath("*[@contact_name='Lacey Shankle']") return {"messages": sorted(els, key=lambda message: message.get("date"))}
Use xpath to find messages instead of a loop
Use xpath to find messages instead of a loop
Python
mit
spiffytech/smsviewer,spiffytech/smsviewer
--- +++ @@ -10,5 +10,6 @@ root = tree.getroot() - return {"messages": sorted([e for e in root if e.get("contact_name") == "Lacey Shankle"], key=lambda message: message.get("date"))} - return {'project': 'smsviewer'} + els = root.xpath("*[@contact_name='Lacey Shankle']") + + return {"messages": sorted(els, key=lambda message: message.get("date"))}
dea4ed78fef278c2cb87b052c98a67940339835a
tagalog/_compat.py
tagalog/_compat.py
try: from urlparse import urlparse except ImportError: # Python3 from urllib import parse as urlparse try: _xrange = xrange except NameError: _xrange = range
try: from urlparse import urlparse except ImportError: # Python3 from urllib.parse import urlparse try: _xrange = xrange except NameError: _xrange = range
Fix compat module for Python 3
Fix compat module for Python 3
Python
mit
nickstenning/tagalog,alphagov/tagalog,alphagov/tagalog,nickstenning/tagalog
--- +++ @@ -1,7 +1,7 @@ try: from urlparse import urlparse except ImportError: # Python3 - from urllib import parse as urlparse + from urllib.parse import urlparse try: _xrange = xrange
aa78db30ad56262e7961013b523e69dacec26d60
tests/util_test.py
tests/util_test.py
#!/usr/bin/python import unittest from decimal import Decimal from blivet import util class MiscTest(unittest.TestCase): longMessage = True def test_power_of_two(self): self.assertFalse(util.power_of_two(None)) self.assertFalse(util.power_of_two("not a number")) self.assertFalse(util.power_of_two(Decimal(2.2))) self.assertFalse(util.power_of_two(-1)) self.assertFalse(util.power_of_two(0)) self.assertFalse(util.power_of_two(1)) for i in range(1, 60, 5): self.assertTrue(util.power_of_two(2 ** i), msg=i) self.assertFalse(util.power_of_two(2 ** i + 1), msg=i) self.assertFalse(util.power_of_two(2 ** i - 1), msg=i)
#!/usr/bin/python import unittest from decimal import Decimal from blivet import util class MiscTest(unittest.TestCase): # Disable this warning, which will only be triggered on python3. For # python2, the default is False. longMessage = True # pylint: disable=pointless-class-attribute-override def test_power_of_two(self): self.assertFalse(util.power_of_two(None)) self.assertFalse(util.power_of_two("not a number")) self.assertFalse(util.power_of_two(Decimal(2.2))) self.assertFalse(util.power_of_two(-1)) self.assertFalse(util.power_of_two(0)) self.assertFalse(util.power_of_two(1)) for i in range(1, 60, 5): self.assertTrue(util.power_of_two(2 ** i), msg=i) self.assertFalse(util.power_of_two(2 ** i + 1), msg=i) self.assertFalse(util.power_of_two(2 ** i - 1), msg=i)
Disable a pointless override warning.
Disable a pointless override warning. This is a valid warning, but only on python3. On python2, the default is False. I don't want to crud up the code with a bunch of conditionals for stuff like this.
Python
lgpl-2.1
AdamWill/blivet,vpodzime/blivet,rvykydal/blivet,dwlehman/blivet,dwlehman/blivet,jkonecny12/blivet,rhinstaller/blivet,vpodzime/blivet,rhinstaller/blivet,rvykydal/blivet,vojtechtrefny/blivet,jkonecny12/blivet,vojtechtrefny/blivet,AdamWill/blivet
--- +++ @@ -7,7 +7,9 @@ class MiscTest(unittest.TestCase): - longMessage = True + # Disable this warning, which will only be triggered on python3. For + # python2, the default is False. + longMessage = True # pylint: disable=pointless-class-attribute-override def test_power_of_two(self): self.assertFalse(util.power_of_two(None))
8670dc8d6c0c920f21598b132250537a744eeebc
tweepy/__init__.py
tweepy/__init__.py
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. """ Tweepy Twitter API library """ __version__ = '3.1.0' __author__ = 'Joshua Roesslein' __license__ = 'MIT' from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category from tweepy.error import TweepError from tweepy.api import API from tweepy.cache import Cache, MemoryCache, FileCache from tweepy.auth import OAuthHandler, AppAuthHandler from tweepy.streaming import Stream, StreamListener from tweepy.cursor import Cursor # Global, unauthenticated instance of API api = API() def debug(enable=True, level=1): pass # import http.client # http.client.HTTPConnection.debuglevel = level
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. """ Tweepy Twitter API library """ __version__ = '3.1.0' __author__ = 'Joshua Roesslein' __license__ = 'MIT' from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category from tweepy.error import TweepError from tweepy.api import API from tweepy.cache import Cache, MemoryCache, FileCache from tweepy.auth import OAuthHandler, AppAuthHandler from tweepy.streaming import Stream, StreamListener from tweepy.cursor import Cursor # Global, unauthenticated instance of API api = API() def debug(enable=True, level=1): from six.moves.http_client import HTTPConnection HTTPConnection.debuglevel = level
Fix tweepy.debug() by using six's module helpers.
Fix tweepy.debug() by using six's module helpers.
Python
mit
tweepy/tweepy,bconnelly/tweepy,kylemanna/tweepy,yared-bezum/tweepy,conversocial/tweepy,vikasgorur/tweepy,atomicjets/tweepy,iamjakob/tweepy,robbiewoods05/tweepy,arunxarun/tweepy,tsablic/tweepy,kcompher/tweepy,rudraksh125/tweepy,svven/tweepy,srimanthd/tweepy,vishnugonela/tweepy,truekonrads/tweepy,IsaacHaze/tweepy,awangga/tweepy,raymondethan/tweepy,cogniteev/tweepy,LikeABird/tweepy,aganzha/tweepy,aleczadikian/tweepy,takeshineshiro/tweepy,techieshark/tweepy,Choko256/tweepy,thelostscientist/tweepy,damchilly/tweepy,vivek8943/tweepy,kskk02/tweepy,sa8/tweepy,elijah513/tweepy,wjt/tweepy,tuxos/tweepy,obskyr/tweepy,sidewire/tweepy,edsu/tweepy,zhenv5/tweepy,hackebrot/tweepy
--- +++ @@ -21,6 +21,5 @@ api = API() def debug(enable=True, level=1): - pass - # import http.client - # http.client.HTTPConnection.debuglevel = level + from six.moves.http_client import HTTPConnection + HTTPConnection.debuglevel = level
1d9b0ac91bca0dd19f83507f9e27414334fdb756
bin/commands/restash.py
bin/commands/restash.py
"""Restash changes.""" import re import sys from subprocess import check_output, PIPE, Popen from utils.messages import error def restash(stash='stash@{0}'): """Restashes a stash reference.""" if re.match('^stash@{.*}$', stash) is None: error('{} is not a valid stash reference'.format(stash)) patch = Popen(['git', 'stash', 'show', '--patch', '--no-color', stash], stdout=PIPE) restash_proc = Popen(['git', 'apply', '--reverse'], stdin=patch.stdout) patch.communicate() restash_proc.communicate() if not restash_proc.returncode: stash_sha = check_output(['git', 'rev-parse', stash]).splitlines()[0] print 'Restashed {} ({})'.format(stash, stash_sha) else: sys.exit(1)
"""Restash changes.""" import os import re import sys from subprocess import check_output, PIPE, Popen from utils.messages import error def _is_valid_stash(stash): """Determines if a stash reference is valid.""" if re.match('^stash@{.*}$', stash) is None: return False with open(os.devnull, 'w') as devnull: proc = Popen(('git', 'cat-file', '-t', stash), stdout=devnull, stderr=devnull) proc.wait() return proc.returncode == 0 def restash(stash='stash@{0}'): """Restashes a stash reference.""" if not _is_valid_stash(stash): error('{} is not a valid stash reference'.format(stash)) patch = Popen(['git', 'stash', 'show', '--patch', '--no-color', stash], stdout=PIPE) restash_proc = Popen(['git', 'apply', '--reverse'], stdin=patch.stdout) patch.communicate() restash_proc.communicate() if not restash_proc.returncode: stash_sha = check_output(['git', 'rev-parse', stash]).splitlines()[0] print 'Restashed {} ({})'.format(stash, stash_sha) else: sys.exit(1)
Fix error messages for bad stash references
Fix error messages for bad stash references
Python
mit
Brickstertwo/git-commands
--- +++ @@ -1,5 +1,6 @@ """Restash changes.""" +import os import re import sys from subprocess import check_output, PIPE, Popen @@ -7,10 +8,21 @@ from utils.messages import error +def _is_valid_stash(stash): + """Determines if a stash reference is valid.""" + + if re.match('^stash@{.*}$', stash) is None: + return False + + with open(os.devnull, 'w') as devnull: + proc = Popen(('git', 'cat-file', '-t', stash), stdout=devnull, stderr=devnull) + proc.wait() + return proc.returncode == 0 + def restash(stash='stash@{0}'): """Restashes a stash reference.""" - if re.match('^stash@{.*}$', stash) is None: + if not _is_valid_stash(stash): error('{} is not a valid stash reference'.format(stash)) patch = Popen(['git', 'stash', 'show', '--patch', '--no-color', stash], stdout=PIPE)
c7f7337b8f86786cd74f46cee9cff7f6d8eb8ec3
config/test/__init__.py
config/test/__init__.py
from SCons.Script import * import subprocess import sys import shlex def run_tests(env): subprocess.call(shlex.split(env.get('TEST_COMMAND'))) sys.exit(0) def generate(env): env.CBAddVariables(('TEST_COMMAND', 'Command to run for `test` target', 'tests/testHarness -C tests --no-color --diff-failed ' '--view-failed --view-unfiltered --save-failed ' '--build')) if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigFinishCB(run_tests) def exists(): return 1
from SCons.Script import * def run_tests(env): import shlex import subprocess import sys subprocess.call(shlex.split(env.get('TEST_COMMAND'))) sys.exit(0) def generate(env): import os cmd = 'tests/testHarness -C tests --diff-failed --view-failed ' \ '--view-unfiltered --save-failed --build' if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color' env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd)) if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigFinishCB(run_tests) def exists(): return 1
Use color output for tests outside of dockbot
Use color output for tests outside of dockbot
Python
lgpl-2.1
CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang
--- +++ @@ -1,19 +1,24 @@ from SCons.Script import * -import subprocess -import sys -import shlex def run_tests(env): + import shlex + import subprocess + import sys + subprocess.call(shlex.split(env.get('TEST_COMMAND'))) sys.exit(0) def generate(env): - env.CBAddVariables(('TEST_COMMAND', 'Command to run for `test` target', - 'tests/testHarness -C tests --no-color --diff-failed ' - '--view-failed --view-unfiltered --save-failed ' - '--build')) + import os + + cmd = 'tests/testHarness -C tests --diff-failed --view-failed ' \ + '--view-unfiltered --save-failed --build' + + if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color' + + env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd)) if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigFinishCB(run_tests)
8639f4e32be8e264cca0831ecacec2d4a177cceb
citrination_client/models/design/target.py
citrination_client/models/design/target.py
from citrination_client.base.errors import CitrinationClientError class Target(object): """ The optimization target for a design run. Consists of the name of the output column to optimize and the objective (either "Max" or "Min") """ def __init__(self, name, objective): """ Constructor. :param name: The name of the target output column :type name: str :param objective: The optimization objective; either "Min" or "Max" :type objective: str """ try: self._objective = float(objective) except ValueError: if objective.lower() not in ["max", "min"]: raise CitrinationClientError( "Target objective must either be \"min\" or \"max\"" ) self._objective = objective self._name = name def to_dict(self): return { "descriptor": self._name, "objective": self._objective }
from citrination_client.base.errors import CitrinationClientError class Target(object): """ The optimization target for a design run. Consists of the name of the output column to optimize and the objective (either "Max" or "Min") """ def __init__(self, name, objective): """ Constructor. :param name: The name of the target output column :type name: str :param objective: The optimization objective; "Min", "Max", or a scalar value (such as "5.0") :type objective: str """ try: self._objective = float(objective) except ValueError: if objective.lower() not in ["max", "min"]: raise CitrinationClientError( "Target objective must either be \"min\" or \"max\"" ) self._objective = objective self._name = name def to_dict(self): return { "descriptor": self._name, "objective": self._objective }
Fix docstring for Target values
Fix docstring for Target values
Python
apache-2.0
CitrineInformatics/python-citrination-client
--- +++ @@ -14,8 +14,7 @@ :param name: The name of the target output column :type name: str - :param objective: The optimization objective; either "Min" - or "Max" + :param objective: The optimization objective; "Min", "Max", or a scalar value (such as "5.0") :type objective: str """
ce04fc96bf6653419acb81db0f1894934517f33b
fireplace/cards/blackrock/collectible.py
fireplace/cards/blackrock/collectible.py
from ..utils import * ## # Minions # Flamewaker class BRM_002: events = [ OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2) ] # Imp Gang Boss class BRM_006: events = [ Damage(SELF).on(Summon(CONTROLLER, "BRM_006t")) ] ## # Spells # Solemn Vigil class BRM_001: action = [Draw(CONTROLLER) * 2] def cost(self, value): return value - self.game.minionsKilledThisTurn # Dragon's Breath class BRM_003: action = [Hit(TARGET, 4)] def cost(self, value): return value - self.game.minionsKilledThisTurn # Demonwrath class BRM_005: action = [Hit(ALL_MINIONS - DEMON, 2)]
from ..utils import * ## # Minions # Flamewaker class BRM_002: events = [ OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2) ] # Imp Gang Boss class BRM_006: events = [ Damage(SELF).on(Summon(CONTROLLER, "BRM_006t")) ] # Dark Iron Skulker class BRM_008: action = [Hit(ENEMY_MINIONS - DAMAGED, 2)] # Volcanic Lumberer class BRM_009: def cost(self, value): return value - self.game.minionsKilledThisTurn ## # Spells # Solemn Vigil class BRM_001: action = [Draw(CONTROLLER) * 2] def cost(self, value): return value - self.game.minionsKilledThisTurn # Dragon's Breath class BRM_003: action = [Hit(TARGET, 4)] def cost(self, value): return value - self.game.minionsKilledThisTurn # Demonwrath class BRM_005: action = [Hit(ALL_MINIONS - DEMON, 2)]
Implement Dark Iron Skulker and Volcanic Lumberer
Implement Dark Iron Skulker and Volcanic Lumberer
Python
agpl-3.0
oftc-ftw/fireplace,NightKev/fireplace,Meerkov/fireplace,smallnamespace/fireplace,smallnamespace/fireplace,liujimj/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,Ragowit/fireplace,Meerkov/fireplace,amw2104/fireplace,amw2104/fireplace,jleclanche/fireplace,liujimj/fireplace,beheh/fireplace,butozerca/fireplace,butozerca/fireplace
--- +++ @@ -16,6 +16,17 @@ events = [ Damage(SELF).on(Summon(CONTROLLER, "BRM_006t")) ] + + +# Dark Iron Skulker +class BRM_008: + action = [Hit(ENEMY_MINIONS - DAMAGED, 2)] + + +# Volcanic Lumberer +class BRM_009: + def cost(self, value): + return value - self.game.minionsKilledThisTurn ##
87b5fe729ef398722c2db1c8eb85a96f075ef82c
examples/GoBot/gobot.py
examples/GoBot/gobot.py
from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo import math import time L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): def __init__(self): Bot.__init__(self, "GoBot") self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15)) self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15)) self.l_motor.set(17) self.r_motor.set(13) def run(self): pass if __name__ == "__main__": bot = GoBot() while True: bot.run()
""" GoBot Example """ from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): """ GoBot """ def __init__(self): Bot.__init__(self, "GoBot") self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15)) self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15)) self.l_motor.set(17) self.r_motor.set(13) def run(self): pass if __name__ == "__main__": bot = GoBot() while True: bot.run()
Fix linting errors in GoBot
Fix linting errors in GoBot
Python
apache-2.0
cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot
--- +++ @@ -1,14 +1,18 @@ +""" +GoBot Example +""" + from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo - -import math -import time L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): + """ + GoBot + """ def __init__(self): Bot.__init__(self, "GoBot")
b7438eb833887c207cc8b848e549a30c7a981373
polling_stations/apps/data_finder/forms.py
polling_stations/apps/data_finder/forms.py
from django import forms from localflavor.gb.forms import GBPostcodeField class PostcodeLookupForm(forms.Form): postcode = GBPostcodeField(label="Enter your postcode") class AddressSelectForm(forms.Form): address = forms.ChoiceField( choices=(), label="", initial="", widget=forms.Select( attrs={ "class": "select_multirow", "size": 10, "aria-describedby": "address_picker", } ), required=True, ) postcode = None def __init__(self, choices, postcode, *args, **kwargs): super(AddressSelectForm, self).__init__(*args, **kwargs) self.fields["address"].choices = choices self.postcode = postcode
from django import forms from django.utils.translation import gettext_lazy as _ from localflavor.gb.forms import GBPostcodeField class PostcodeLookupForm(forms.Form): postcode = GBPostcodeField(label=_("Enter your postcode")) class AddressSelectForm(forms.Form): address = forms.ChoiceField( choices=(), label="", initial="", widget=forms.Select( attrs={ "class": "select_multirow", "size": 10, "aria-describedby": "address_picker", } ), required=True, ) postcode = None def __init__(self, choices, postcode, *args, **kwargs): super(AddressSelectForm, self).__init__(*args, **kwargs) self.fields["address"].choices = choices self.postcode = postcode
Mark "Enter your postcode" for translation in a form field label
Mark "Enter your postcode" for translation in a form field label
Python
bsd-3-clause
DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
--- +++ @@ -1,10 +1,11 @@ from django import forms +from django.utils.translation import gettext_lazy as _ from localflavor.gb.forms import GBPostcodeField class PostcodeLookupForm(forms.Form): - postcode = GBPostcodeField(label="Enter your postcode") + postcode = GBPostcodeField(label=_("Enter your postcode")) class AddressSelectForm(forms.Form):
bb82e3a8519009311ede80f877844565c49384b4
examples/qidle/qidle.py
examples/qidle/qidle.py
#! /usr/bin/python3 # -*- coding: utf-8 -*- from qidle import main import logging if __name__ == '__main__': logging.basicConfig(level=logging.INFO) main()
#! /usr/bin/python3 # -*- coding: utf-8 -*- import sys from qidle import main import logging if __name__ == '__main__': filename = None if sys.platform == 'win32': filename = 'qidle.log' logging.basicConfig(level=logging.INFO, filename=filename) main()
Add a log file on windows
Add a log file on windows
Python
mit
pyQode/pyqode.python,pyQode/pyqode.python,zwadar/pyqode.python,mmolero/pyqode.python
--- +++ @@ -1,8 +1,12 @@ #! /usr/bin/python3 # -*- coding: utf-8 -*- +import sys from qidle import main import logging if __name__ == '__main__': - logging.basicConfig(level=logging.INFO) + filename = None + if sys.platform == 'win32': + filename = 'qidle.log' + logging.basicConfig(level=logging.INFO, filename=filename) main()
e1f15a29bb947666740ec250120e3bdf451f0477
pythonwarrior/towers/beginner/level_006.py
pythonwarrior/towers/beginner/level_006.py
# -------- # |C @ S aa| # -------- level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") level.tip("You can walk backward by passing 'backward' as an argument to walk_. Same goes for feel, rescue_ and attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west')
# -------- # |C @ S aa| # -------- level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") level.tip("You can walk backward by passing 'backward' as an argument to warrior.walk_. Same goes for warrior.feel, warrior.rescue_ and warrior.attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55) level.ace_score(105) level.size(8, 1) level.stairs(7, 0) level.warrior(2, 0, 'east') level.unit('captive', 0, 0, 'east') level.unit('thick_sludge', 4, 0, 'west') level.unit('archer', 6, 0, 'west') level.unit('archer', 7, 0, 'west')
Update description of the level 06
Update description of the level 06
Python
mit
arbylee/python-warrior
--- +++ @@ -3,7 +3,7 @@ # -------- level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.") -level.tip("You can walk backward by passing 'backward' as an argument to walk_. Same goes for feel, rescue_ and attack_. Archers have a limited attack distance.") +level.tip("You can walk backward by passing 'backward' as an argument to warrior.walk_. Same goes for warrior.feel, warrior.rescue_ and warrior.attack_. Archers have a limited attack distance.") level.clue("Walk backward if you are taking damage from afar and do not have enough health to attack. You may also want to consider walking backward until warrior.feel('backward').is_wall().") level.time_bonus(55)
72358efa2bf9ff45377ef8ab3478b9433c67c574
candidates/feeds.py
candidates/feeds.py
from django.contrib.syndication.views import Feed from django.core.urlresolvers import reverse from django.utils.feedgenerator import Atom1Feed from .models import LoggedAction class RecentChangesFeed(Feed): title = "YourNextMP recent changes" description = "Changes to YNMP candidates" link = "/feeds/changes.xml" feed_type = Atom1Feed def items(self): return LoggedAction.objects.order_by('-updated')[:50] def item_title(self, item): return "{0} - {1}".format( item.popit_person_id, item.action_type ) def item_description(self, item): description = """ {0} Updated by {1} at {2} """.format( item.source, item.ip_address, str(item.updated), ) return description def item_link(self, item): return reverse('person-view', args=[item.popit_person_id])
from django.contrib.syndication.views import Feed from django.core.urlresolvers import reverse from django.utils.feedgenerator import Atom1Feed from .models import LoggedAction class RecentChangesFeed(Feed): title = "YourNextMP recent changes" description = "Changes to YNMP candidates" link = "/feeds/changes.xml" feed_type = Atom1Feed def items(self): return LoggedAction.objects.order_by('-updated')[:50] def item_title(self, item): return "{0} - {1}".format( item.popit_person_id, item.action_type ) def item_description(self, item): description = """ {0} Updated at {1} """.format( item.source, str(item.updated), ) return description def item_link(self, item): return reverse('person-view', args=[item.popit_person_id])
Remove IP address from feed description
Remove IP address from feed description
Python
agpl-3.0
DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,neavouli/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,YoQuieroSaber/yournextrepresentative,datamade/yournextmp-popit,openstate/yournextrepresentative,neavouli/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextrepresentative,YoQuieroSaber/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextmp-popit,openstate/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextrepresentative
--- +++ @@ -23,10 +23,9 @@ description = """ {0} - Updated by {1} at {2} + Updated at {1} """.format( item.source, - item.ip_address, str(item.updated), )
20cc6c1edca69c946261c6bd8587d6cf5bb7a6e8
tests/core/eth-module/test_eth_contract.py
tests/core/eth-module/test_eth_contract.py
import sys import pytest if sys.version_info >= (3, 3): from unittest.mock import Mock ABI = [{}] ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601' INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601' @pytest.mark.parametrize( 'args,kwargs,expected', ( ((ADDRESS,), {}, None), ((INVALID_CHECKSUM_ADDRESS,), {}, ValueError), ((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError), ((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError), ) ) def test_contract_address_validation(web3, args, kwargs, expected): if isinstance(expected, type) and issubclass(expected, Exception): with pytest.raises(expected): web3.eth.contract(*args, **kwargs) return # run without errors web3.eth.contract(*args, **kwargs) @pytest.mark.skipif(sys.version_info < (3, 3), reason="needs Mock library from 3.3") def test_set_contract_factory(web3): factoryClass = Mock() web3.eth.setContractFactory(factoryClass) web3.eth.contract(contract_name='myname') factoryClass.factory.assert_called_once_with(web3, contract_name='myname')
import sys import pytest if sys.version_info >= (3, 3): from unittest.mock import Mock ABI = [{}] ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601' INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601' @pytest.mark.parametrize( 'args,kwargs,expected', ( ((ADDRESS,), {}, None), ((INVALID_CHECKSUM_ADDRESS,), {}, ValueError), ((), {'address': ADDRESS}, None), ((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError), ) ) def test_contract_address_validation(web3, args, kwargs, expected): if isinstance(expected, type) and issubclass(expected, Exception): with pytest.raises(expected): web3.eth.contract(*args, **kwargs) return # run without errors web3.eth.contract(*args, **kwargs) @pytest.mark.skipif(sys.version_info < (3, 3), reason="needs Mock library from 3.3") def test_set_contract_factory(web3): factoryClass = Mock() web3.eth.setContractFactory(factoryClass) web3.eth.contract(contract_name='myname') factoryClass.factory.assert_called_once_with(web3, contract_name='myname')
Replace duplicate test with valid address kwarg
Replace duplicate test with valid address kwarg
Python
mit
pipermerriam/web3.py
--- +++ @@ -16,7 +16,7 @@ ( ((ADDRESS,), {}, None), ((INVALID_CHECKSUM_ADDRESS,), {}, ValueError), - ((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError), + ((), {'address': ADDRESS}, None), ((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError), ) )
16765ebf41e2c7adea3ed1c1021bf1ca9db83d15
fmn/lib/__init__.py
fmn/lib/__init__.py
""" fedmsg-notifications internal API """ import fmn.lib.models import logging log = logging.getLogger(__name__) def recipients(session, config, valid_paths, message): """ The main API function. Accepts a fedmsg message as an argument. Returns a dict mapping context names to lists of recipients. """ res = {} for context in session.query(fmn.lib.models.Context).all(): res[context.name] = recipients_for_context( session, config, valid_paths, context, message) return res def recipients_for_context(session, config, valid_paths, context, message): """ Returns the recipients for a given fedmsg message and stated context. Context may be either the name of a context or an instance of fmn.lib.models.Context. """ if isinstance(context, basestring): context = session.query(fmn.lib.models.Context)\ .filter_by(name=context).one() return context.recipients(session, config, valid_paths, message) def load_filters(root='fmn.filters'): """ Load the big list of allowed callable filters. """ module = __import__(root, fromlist=[root.split('.')[0]]) filters = {} for name in dir(module): obj = getattr(module, name) if not callable(obj): continue log.info("Found filter %r %r" % (name, obj)) filters[name] = obj return {root: filters}
""" fedmsg-notifications internal API """ import fmn.lib.models import inspect import logging log = logging.getLogger(__name__) def recipients(session, config, valid_paths, message): """ The main API function. Accepts a fedmsg message as an argument. Returns a dict mapping context names to lists of recipients. """ res = {} for context in session.query(fmn.lib.models.Context).all(): res[context.name] = recipients_for_context( session, config, valid_paths, context, message) return res def recipients_for_context(session, config, valid_paths, context, message): """ Returns the recipients for a given fedmsg message and stated context. Context may be either the name of a context or an instance of fmn.lib.models.Context. """ if isinstance(context, basestring): context = session.query(fmn.lib.models.Context)\ .filter_by(name=context).one() return context.recipients(session, config, valid_paths, message) def load_filters(root='fmn.filters'): """ Load the big list of allowed callable filters. """ module = __import__(root, fromlist=[root.split('.')[0]]) filters = {} for name in dir(module): obj = getattr(module, name) if not callable(obj): continue log.info("Found filter %r %r" % (name, obj)) filters[name] = {'func': obj, 'args': inspect.getargspec(obj)[0]} return {root: filters}
Use inspect to get the list of arguments each filter accepts
Use inspect to get the list of arguments each filter accepts
Python
lgpl-2.1
jeremycline/fmn,jeremycline/fmn,jeremycline/fmn
--- +++ @@ -2,6 +2,7 @@ import fmn.lib.models +import inspect import logging log = logging.getLogger(__name__) @@ -48,6 +49,7 @@ if not callable(obj): continue log.info("Found filter %r %r" % (name, obj)) - filters[name] = obj + + filters[name] = {'func': obj, 'args': inspect.getargspec(obj)[0]} return {root: filters}
cbe773d051168e05118774708ff7a0ce881617f4
ganglia/settings.py
ganglia/settings.py
DEBUG = True GANGLIA_PATH = '/usr/local/etc' # where gmetad.conf is located API_SERVER = 'http://ganglia-api.example.com:8080' # where ganglia-api.py is hosted BASE_URL = '/ganglia/api/v2' LOGFILE = '/var/log/ganglia-api.log' PIDFILE = '/var/run/ganglia-api.pid'
DEBUG = True GANGLIA_PATH = '/etc/ganglia' # where gmetad.conf is located API_SERVER = 'http://ganglia-api.example.com:8080' # where ganglia-api.py is hosted BASE_URL = '/ganglia/api/v2' LOGFILE = '/var/log/ganglia-api.log' PIDFILE = '/var/run/ganglia-api.pid'
Make GANGLIA_PATH default to /etc/ganglia
Make GANGLIA_PATH default to /etc/ganglia
Python
apache-2.0
guardian/ganglia-api
--- +++ @@ -1,6 +1,6 @@ DEBUG = True -GANGLIA_PATH = '/usr/local/etc' # where gmetad.conf is located +GANGLIA_PATH = '/etc/ganglia' # where gmetad.conf is located API_SERVER = 'http://ganglia-api.example.com:8080' # where ganglia-api.py is hosted BASE_URL = '/ganglia/api/v2'
bab17ba4b22192848ab7e2b9649b6e83f0d947ac
src/load_remote_data.py
src/load_remote_data.py
#!/usr/bin/env python import os import requests # local configuration remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote') # URLs at which data can be found csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv' with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'w') as f: # load the data to write to the file # TODO: Add error handling - URL loading response = requests.get(csv_url_summary_stats) if not response.ok: print('There was a problem loading the Summary Statistics data') # TODO: Add error handling - file writing f.write(response.text) # TODO: Add mention of __main__ and main()
#!/usr/bin/env python import os import requests # local configuration remote_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data', 'remote') # URLs at which data can be found csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv' with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f: # load the data to write to the file # TODO: Add error handling - URL loading response = requests.get(csv_url_summary_stats) if not response.ok: print('There was a problem loading the Summary Statistics data') # TODO: Add error handling - file writing f.write(response.text.encode('utf-8')) # TODO: Add mention of __main__ and main()
Fix encoding after fetching remote data
Fix encoding after fetching remote data Adds opening of csv file in binary format, plus conversion of fetched data to utf-8. This resolves a UnicodeEncodeError exception.
Python
mit
devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring
--- +++ @@ -12,7 +12,7 @@ csv_url_summary_stats = 'http://dashboard.iatistandard.org/summary_stats.csv' -with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'w') as f: +with open(os.path.join(remote_data_path, 'summary_stats.csv'), 'wb') as f: # load the data to write to the file # TODO: Add error handling - URL loading response = requests.get(csv_url_summary_stats) @@ -21,7 +21,7 @@ print('There was a problem loading the Summary Statistics data') # TODO: Add error handling - file writing - f.write(response.text) + f.write(response.text.encode('utf-8')) # TODO: Add mention of __main__ and main()
09db47bd68f71560cde9509472b114c9ed5a6d54
kolibri/__init__.py
kolibri/__init__.py
from __future__ import absolute_import, print_function, unicode_literals # NB! This is not necessarily the version scheme we want, however having a good # tracking of releases once we start doing lots of pre-releases is essential. from .utils.version import get_version #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 4, 0, 'beta', 10) __author__ = 'Learning Equality' __email__ = 'info@learningequality.org' __version__ = str(get_version(VERSION))
from __future__ import absolute_import, print_function, unicode_literals # NB! This is not necessarily the version scheme we want, however having a good # tracking of releases once we start doing lots of pre-releases is essential. from .utils.version import get_version #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 6, 0, 'alpha', 0) __author__ = 'Learning Equality' __email__ = 'info@learningequality.org' __version__ = str(get_version(VERSION))
Develop branch bumped to 0.6.0dev with new versioning mechanism introduced
Develop branch bumped to 0.6.0dev with new versioning mechanism introduced
Python
mit
jonboiser/kolibri,mrpau/kolibri,lyw07/kolibri,DXCanas/kolibri,lyw07/kolibri,DXCanas/kolibri,indirectlylit/kolibri,jonboiser/kolibri,learningequality/kolibri,christianmemije/kolibri,learningequality/kolibri,indirectlylit/kolibri,mrpau/kolibri,lyw07/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,christianmemije/kolibri,DXCanas/kolibri,christianmemije/kolibri,christianmemije/kolibri,benjaoming/kolibri,lyw07/kolibri,jonboiser/kolibri,mrpau/kolibri,mrpau/kolibri,benjaoming/kolibri,benjaoming/kolibri,benjaoming/kolibri,DXCanas/kolibri,jonboiser/kolibri,learningequality/kolibri,learningequality/kolibri
--- +++ @@ -6,7 +6,7 @@ #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. -VERSION = (0, 4, 0, 'beta', 10) +VERSION = (0, 6, 0, 'alpha', 0) __author__ = 'Learning Equality' __email__ = 'info@learningequality.org'
0d8a9a83fdd896aa5690c1c32db1d1658748a94a
tests/test_schemaorg.py
tests/test_schemaorg.py
import unittest from recipe_scrapers._exceptions import SchemaOrgException from recipe_scrapers._schemaorg import SchemaOrg class TestSchemaOrg(unittest.TestCase): def setUp(self): with open("tests/test_data/schemaorg.testhtml", encoding="utf-8") as pagedata: self.schema = SchemaOrg(pagedata.read()) def test_total_time_with_schema_missing_all_data_should_raise_exception(self): keys = ["totalTime", "cookTime", "prepTime"] for k in keys: if k in self.schema.data: del self.schema.data[k] with self.assertRaises(SchemaOrgException): self.assertEqual(self.schema.total_time(), None) def test_total_time_with_schema__all_zeros(self): keys = ["totalTime", "cookTime", "prepTime"] for k in keys: self.schema.data[k] = "PT0M" self.assertEqual(self.schema.total_time(), 0) del self.schema.data["totalTime"] self.assertEqual(self.schema.total_time(), 0) def test_graph_schema_without_context(self): with open( "tests/test_data/schemaorg_graph.testhtml", encoding="utf-8" ) as pagedata: schema = SchemaOrg(pagedata.read()) self.assertNotEqual(schema.data, {})
import unittest from recipe_scrapers._exceptions import SchemaOrgException from recipe_scrapers._schemaorg import SchemaOrg class TestSchemaOrg(unittest.TestCase): def setUp(self): with open("tests/test_data/schemaorg.testhtml", encoding="utf-8") as pagedata: self.schema = SchemaOrg(pagedata.read()) def test_total_time_with_schema_missing_all_data_should_raise_exception(self): keys = ["totalTime", "cookTime", "prepTime"] for k in keys: if k in self.schema.data: del self.schema.data[k] with self.assertRaises(SchemaOrgException): self.assertEqual(self.schema.total_time(), None) def test_total_time_with_schema__all_zeros(self): keys = ["totalTime", "cookTime", "prepTime"] for k in keys: self.schema.data[k] = "PT0M" self.assertEqual(self.schema.total_time(), 0) del self.schema.data["totalTime"] self.assertEqual(self.schema.total_time(), 0) def test_nutrient_retrieval(self): expected_nutrients = { "calories": "240 calories", "fatContent": "9 grams fat", } self.assertEqual(self.schema.nutrients(), expected_nutrients) def test_graph_schema_without_context(self): with open( "tests/test_data/schemaorg_graph.testhtml", encoding="utf-8" ) as pagedata: schema = SchemaOrg(pagedata.read()) self.assertNotEqual(schema.data, {})
Add test coverage for expected nutrient retrieval behaviour
Add test coverage for expected nutrient retrieval behaviour
Python
mit
hhursev/recipe-scraper
--- +++ @@ -25,6 +25,13 @@ del self.schema.data["totalTime"] self.assertEqual(self.schema.total_time(), 0) + def test_nutrient_retrieval(self): + expected_nutrients = { + "calories": "240 calories", + "fatContent": "9 grams fat", + } + self.assertEqual(self.schema.nutrients(), expected_nutrients) + def test_graph_schema_without_context(self): with open( "tests/test_data/schemaorg_graph.testhtml", encoding="utf-8"
1f3f0b50d8cd740e09983b3dbd8796f1e4afa66c
linkatos/message.py
linkatos/message.py
import re url_re = re.compile("(?:\s|^)<(https?://[\w./?+&+%$!#=\-_]+)>(?:\s|$)") def extract_url(message): """ Returns the first url in a message. If there aren't any returns None """ answer = url_re.search(message) if answer is not None: answer = answer.group(1).strip() return answer def to_bot(message, bot_id): bot_re = "^<@" + bot_id + '>' to_bot_re = re.compile(bot_re) bot_found = to_bot_re.search(message) return bot_found is not None def is_list_request(message): list_re = re.compile("list") list_found = list_re.search(message) return list_found is not None def purge_request(message): purge_re = re.compile("(purge) (\d+)") index_found = purge_re.search(message) if index_found is None: return None return int(index_found.group(2))
import re url_re = re.compile("(?:\s|^)<(https?://[\w./?+&+%$!#=\-_]+)>(?:\s|$)") purge_re = re.compile("(purge) (\d+)") list_re = re.compile("list") def extract_url(message): """ Returns the first url in a message. If there aren't any returns None """ answer = url_re.search(message) if answer is not None: answer = answer.group(1).strip() return answer def to_bot(message, bot_id): bot_re = "^<@" + bot_id + '>' to_bot_re = re.compile(bot_re) bot_found = to_bot_re.search(message) return bot_found is not None def is_list_request(message): list_found = list_re.search(message) return list_found is not None def purge_request(message): index_found = purge_re.search(message) if index_found is None: return None return int(index_found.group(2))
Change location of regex compilation
refactor: Change location of regex compilation
Python
mit
iwi/linkatos,iwi/linkatos
--- +++ @@ -1,7 +1,8 @@ import re url_re = re.compile("(?:\s|^)<(https?://[\w./?+&+%$!#=\-_]+)>(?:\s|$)") - +purge_re = re.compile("(purge) (\d+)") +list_re = re.compile("list") def extract_url(message): """ @@ -24,14 +25,12 @@ def is_list_request(message): - list_re = re.compile("list") list_found = list_re.search(message) return list_found is not None def purge_request(message): - purge_re = re.compile("(purge) (\d+)") index_found = purge_re.search(message) if index_found is None:
e5c8379c987d2d7ae60d5f9321bb96f278549167
apel/parsers/__init__.py
apel/parsers/__init__.py
''' Copyright (C) 2012 STFC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Package with Apel parsers. @author: Will Rogers, Konrad Jopek ''' LOGGER_ID = 'parser' from parser import Parser from blah import BlahParser from lsf import LSFParser from pbs import PBSParser from sge import SGEParser from slurm import SlurmParser
''' Copyright (C) 2012 STFC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Package with Apel parsers. @author: Will Rogers, Konrad Jopek ''' LOGGER_ID = 'parser' from parser import Parser from blah import BlahParser from htcondor import HTCondorParser from lsf import LSFParser from pbs import PBSParser from sge import SGEParser from slurm import SlurmParser
Add HTCondorParser to init imports
Add HTCondorParser to init imports
Python
apache-2.0
apel/apel,tofu-rocketry/apel,tofu-rocketry/apel,stfc/apel,apel/apel,stfc/apel
--- +++ @@ -22,6 +22,7 @@ from parser import Parser from blah import BlahParser +from htcondor import HTCondorParser from lsf import LSFParser from pbs import PBSParser from sge import SGEParser
fdcc7f0e45fe5f0d284f47941238a92cbe9a1b36
attest/tests/__init__.py
attest/tests/__init__.py
from attest import Tests suite = lambda mod: 'attest.tests.' + mod + '.suite' all = Tests([suite('asserts'), suite('collections'), suite('classy'), suite('reporters'), suite('eval'), ])
from attest import Tests all = Tests('.'.join((__name__, mod, 'suite')) for mod in ('asserts', 'collections', 'classy', 'reporters', 'eval'))
Simplify our own test suite
Simplify our own test suite
Python
bsd-2-clause
dag/attest
--- +++ @@ -1,11 +1,8 @@ from attest import Tests - -suite = lambda mod: 'attest.tests.' + mod + '.suite' - -all = Tests([suite('asserts'), - suite('collections'), - suite('classy'), - suite('reporters'), - suite('eval'), - ]) +all = Tests('.'.join((__name__, mod, 'suite')) + for mod in ('asserts', + 'collections', + 'classy', + 'reporters', + 'eval'))
f096b5d2944dc19de8aa79696c137fe3f45927da
sistr/src/logger.py
sistr/src/logger.py
import logging LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' def init_console_logger(logging_verbosity=3): logging_levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG] if logging_verbosity > len(logging_levels): logging_verbosity = 3 lvl = logging_levels[logging_verbosity] logging.basicConfig(format=LOG_FORMAT, level=lvl)
import logging LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' def init_console_logger(logging_verbosity=3): logging_levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG] if logging_verbosity > (len(logging_levels) - 1): logging_verbosity = 3 lvl = logging_levels[logging_verbosity] logging.basicConfig(format=LOG_FORMAT, level=lvl)
Fix verbose level index out of range error
Fix verbose level index out of range error
Python
apache-2.0
peterk87/sistr_cmd
--- +++ @@ -4,7 +4,7 @@ def init_console_logger(logging_verbosity=3): logging_levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG] - if logging_verbosity > len(logging_levels): + if logging_verbosity > (len(logging_levels) - 1): logging_verbosity = 3 lvl = logging_levels[logging_verbosity]
1ed1ac9a9a07a4b43ed1e96060a40b1ffd3fe97d
src/hunter/const.py
src/hunter/const.py
import os import site import sys import this from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SITE_PACKAGES_PATHS.add(get_python_lib()) SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__))) SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS) SYS_PREFIX_PATHS = { '<frozen zipimport>', '<frozen importlib._bootstrap>', '<frozen importlib._bootstrap_external>', sys.prefix, sys.exec_prefix, os.path.dirname(os.__file__), os.path.dirname(this.__file__), } for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop): SYS_PREFIX_PATHS.add(getattr(sys, prop)) SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
import os import site import sys import stat from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SITE_PACKAGES_PATHS.add(get_python_lib()) SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__))) SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS) SYS_PREFIX_PATHS = { '<frozen zipimport>', '<frozen importlib._bootstrap>', '<frozen importlib._bootstrap_external>', sys.prefix, sys.exec_prefix, os.path.dirname(os.__file__), os.path.dirname(stat.__file__), } for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop): SYS_PREFIX_PATHS.add(getattr(sys, prop)) SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
Use stat instead of this.
Use stat instead of this.
Python
bsd-2-clause
ionelmc/python-hunter
--- +++ @@ -1,7 +1,7 @@ import os import site import sys -import this +import stat from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() @@ -20,7 +20,7 @@ sys.prefix, sys.exec_prefix, os.path.dirname(os.__file__), - os.path.dirname(this.__file__), + os.path.dirname(stat.__file__), } for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix': if hasattr(sys, prop):
4219cb35c877d7838ed5ff4483a028f05f8433bd
testapp/__init__.py
testapp/__init__.py
__author__ = 'Igor Davydenko <playpauseandstop@gmail.com>' __description__ = 'Flask-And-Redis test project' __license__ = 'BSD License' __version__ = '0.2.3'
Add metadata to ``testapp`` package.
Add metadata to ``testapp`` package.
Python
bsd-3-clause
playpauseandstop/Flask-And-Redis,playpauseandstop/Flask-And-Redis
--- +++ @@ -0,0 +1,4 @@ +__author__ = 'Igor Davydenko <playpauseandstop@gmail.com>' +__description__ = 'Flask-And-Redis test project' +__license__ = 'BSD License' +__version__ = '0.2.3'
012f93ae03aded72b64ac9bbfb6d2995199d4d8f
tests/test_api_views.py
tests/test_api_views.py
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings") import django from django.test import TestCase from rest_framework.test import APIRequestFactory from api.webview.views import DocumentList django.setup() class APIViewTests(TestCase): def setUp(self): self.factory = APIRequestFactory() def test_document_view(self): view = DocumentList.as_view() request = self.factory.get( '/documents/' ) response = view(request) self.assertEqual(response.status_code, 200) def test_source_view(self): view = DocumentList.as_view() request = self.factory.get( '/documents/dudley_weekly/' ) response = view(request) self.assertEqual(response.status_code, 200) def test_individual_view(self): view = DocumentList.as_view() request = self.factory.get( '/documents/dudley_weekly/dudley1' ) response = view(request) self.assertEqual(response.status_code, 200)
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings") import django from django.test import TestCase from rest_framework.test import APIRequestFactory from api.webview.views import DocumentList, status django.setup() class APIViewTests(TestCase): def setUp(self): self.factory = APIRequestFactory() def test_document_view(self): view = DocumentList.as_view() request = self.factory.get( '/documents/' ) response = view(request) self.assertEqual(response.status_code, 200) def test_source_view(self): view = DocumentList.as_view() request = self.factory.get( '/documents/dudley_weekly/' ) response = view(request) self.assertEqual(response.status_code, 200) def test_individual_view(self): view = DocumentList.as_view() request = self.factory.get( '/documents/dudley_weekly/dudley1' ) response = view(request) self.assertEqual(response.status_code, 200) def test_status(self): view = status request = self.factory.get( '/status' ) response = view(request) self.assertEqual(response.status_code, 200)
Add test for status view
Add test for status view
Python
apache-2.0
erinspace/scrapi,erinspace/scrapi,felliott/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi
--- +++ @@ -5,7 +5,7 @@ from django.test import TestCase from rest_framework.test import APIRequestFactory -from api.webview.views import DocumentList +from api.webview.views import DocumentList, status django.setup() @@ -41,3 +41,12 @@ response = view(request) self.assertEqual(response.status_code, 200) + + def test_status(self): + view = status + request = self.factory.get( + '/status' + ) + response = view(request) + + self.assertEqual(response.status_code, 200)
0168836c6bb2c04ac7a9d4ac6682fca47512ea4c
tests/test_cli_parse.py
tests/test_cli_parse.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest import tempfile from click.testing import CliRunner import tbmodels from tbmodels._cli import cli @pytest.mark.parametrize('prefix', ['silicon', 'bi']) def test_cli_parse(models_equal, prefix, sample): runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, ['parse', '-o', out_file.name, '-f', sample(''), '-p', prefix], catch_exceptions=False ) print(run.output) model_res = tbmodels.Model.from_hdf5_file(out_file.name) model_reference = tbmodels.Model.from_wannier_folder( folder=sample(''), prefix=prefix ) models_equal(model_res, model_reference)
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest import tempfile from click.testing import CliRunner import tbmodels from tbmodels._cli import cli @pytest.mark.parametrize('pos_kind', ['wannier', 'nearest_atom']) @pytest.mark.parametrize('prefix', ['silicon', 'bi']) def test_cli_parse(models_equal, prefix, sample, pos_kind): runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'parse', '-o', out_file.name, '-f', sample(''), '-p', prefix, '--pos-kind', pos_kind ], catch_exceptions=False ) print(run.output) model_res = tbmodels.Model.from_hdf5_file(out_file.name) model_reference = tbmodels.Model.from_wannier_folder( folder=sample(''), prefix=prefix, pos_kind=pos_kind ) models_equal(model_res, model_reference)
Add tests for parse CLI with pos_kind
Add tests for parse CLI with pos_kind
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
--- +++ @@ -9,19 +9,21 @@ from tbmodels._cli import cli +@pytest.mark.parametrize('pos_kind', ['wannier', 'nearest_atom']) @pytest.mark.parametrize('prefix', ['silicon', 'bi']) -def test_cli_parse(models_equal, prefix, sample): +def test_cli_parse(models_equal, prefix, sample, pos_kind): runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( - cli, - ['parse', '-o', out_file.name, '-f', - sample(''), '-p', prefix], + cli, [ + 'parse', '-o', out_file.name, '-f', + sample(''), '-p', prefix, '--pos-kind', pos_kind + ], catch_exceptions=False ) print(run.output) model_res = tbmodels.Model.from_hdf5_file(out_file.name) model_reference = tbmodels.Model.from_wannier_folder( - folder=sample(''), prefix=prefix + folder=sample(''), prefix=prefix, pos_kind=pos_kind ) models_equal(model_res, model_reference)
b1a91fc4e843197a12be653aa60d5cdf32f31423
tests/test_recursion.py
tests/test_recursion.py
from tests import utils def test_recursion(): uwhois = utils.create_uwhois() expected = 'whois.markmonitor.com' transcript = utils.read_transcript('google.com.txt') # Make sure there's nothing wrong with the WHOIS transcript. assert transcript.count(expected) == 1 assert uwhois.get_registrar_whois_server('com', transcript) == expected
from tests import utils def test_recursion(): uwhois = utils.create_uwhois() expected = 'whois.markmonitor.com' transcript = utils.read_transcript('google.com.txt') # Make sure there's nothing wrong with the WHOIS transcript. assert transcript.count(expected) == 1 server, port = uwhois.get_whois_server('com') pattern = uwhois.get_recursion_pattern(server) assert uwhois.get_registrar_whois_server(pattern, transcript) == expected
Fix test for the fork
Fix test for the fork
Python
mit
Rafiot/uwhoisd,Rafiot/uwhoisd
--- +++ @@ -7,4 +7,6 @@ transcript = utils.read_transcript('google.com.txt') # Make sure there's nothing wrong with the WHOIS transcript. assert transcript.count(expected) == 1 - assert uwhois.get_registrar_whois_server('com', transcript) == expected + server, port = uwhois.get_whois_server('com') + pattern = uwhois.get_recursion_pattern(server) + assert uwhois.get_registrar_whois_server(pattern, transcript) == expected
754d2949ce0c2fa2b36615af755b3b8aaf9876b5
tests/test_resources.py
tests/test_resources.py
import pytest from micromanager.resources import Resource from micromanager.resources import BQDataset from micromanager.resources import Bucket from micromanager.resources import SQLInstance test_cases = [ ( {'resource_kind': 'storage#bucket'}, Bucket ), ( {'resource_kind': 'sql#instance'}, SQLInstance ), ( {'resource_kind': 'bigquery#dataset'}, BQDataset ) ] @pytest.mark.parametrize( "input,expected", test_cases, ids=[cls.__name__ for (_, cls) in test_cases]) def test_resource_factory(input, expected): r = Resource.factory(input) assert r.__class__ == expected def test_resource_factory_invalid(): with pytest.raises(AssertionError): r = Resource.factory({})
import pytest from .util import load_test_data from .util import discovery_cache from .mock import HttpMockSequenceEx from googleapiclient.http import HttpMockSequence from micromanager.resources import Resource from micromanager.resources.gcp import GcpBigqueryDataset from micromanager.resources.gcp import GcpComputeInstance from micromanager.resources.gcp import GcpSqlInstance from micromanager.resources.gcp import GcpStorageBucket from micromanager.resources.gcp import GcpStorageBucketIamPolicy test_cases = [ ( {'resource_type': 'bigquery.datasets', 'resource_name': '', 'project_id': ''}, GcpBigqueryDataset, 'gcp.bigquery.datasets' ), ( {'resource_type': 'compute.instances', 'resource_name': '', 'project_id': ''}, GcpComputeInstance, 'gcp.compute.instances' ), ( {'resource_type': 'sqladmin.instances', 'resource_name': '', 'project_id': ''}, GcpSqlInstance, 'gcp.sqladmin.instances' ), ( {'resource_type': 'storage.buckets', 'resource_name': '', 'project_id': ''}, GcpStorageBucket, 'gcp.storage.buckets' ), ( {'resource_type': 'storage.buckets.iam', 'resource_name': '', 'project_id': ''}, GcpStorageBucketIamPolicy, 'gcp.storage.buckets.iam' ) ] @pytest.mark.parametrize( "input,cls,rtype", test_cases, ids=[cls.__name__ for (_, cls, _) in test_cases]) def test_gcp_resource_factory(input, cls, rtype): r = Resource.factory("gcp", input) assert r.__class__ == cls assert r.type() == rtype def test_gcp_resource_factory_invalid(): with pytest.raises(AssertionError): r = Resource.factory('gcp', {})
Update tests after lots of work on Resources
Update tests after lots of work on Resources
Python
apache-2.0
forseti-security/resource-policy-evaluation-library
--- +++ @@ -1,34 +1,57 @@ import pytest +from .util import load_test_data +from .util import discovery_cache + +from .mock import HttpMockSequenceEx + +from googleapiclient.http import HttpMockSequence + from micromanager.resources import Resource -from micromanager.resources import BQDataset -from micromanager.resources import Bucket -from micromanager.resources import SQLInstance +from micromanager.resources.gcp import GcpBigqueryDataset +from micromanager.resources.gcp import GcpComputeInstance +from micromanager.resources.gcp import GcpSqlInstance +from micromanager.resources.gcp import GcpStorageBucket +from micromanager.resources.gcp import GcpStorageBucketIamPolicy test_cases = [ ( - {'resource_kind': 'storage#bucket'}, - Bucket + {'resource_type': 'bigquery.datasets', 'resource_name': '', 'project_id': ''}, + GcpBigqueryDataset, + 'gcp.bigquery.datasets' ), ( - {'resource_kind': 'sql#instance'}, - SQLInstance + {'resource_type': 'compute.instances', 'resource_name': '', 'project_id': ''}, + GcpComputeInstance, + 'gcp.compute.instances' ), ( - {'resource_kind': 'bigquery#dataset'}, - BQDataset + {'resource_type': 'sqladmin.instances', 'resource_name': '', 'project_id': ''}, + GcpSqlInstance, + 'gcp.sqladmin.instances' + ), + ( + {'resource_type': 'storage.buckets', 'resource_name': '', 'project_id': ''}, + GcpStorageBucket, + 'gcp.storage.buckets' + ), + ( + {'resource_type': 'storage.buckets.iam', 'resource_name': '', 'project_id': ''}, + GcpStorageBucketIamPolicy, + 'gcp.storage.buckets.iam' ) ] @pytest.mark.parametrize( - "input,expected", + "input,cls,rtype", test_cases, - ids=[cls.__name__ for (_, cls) in test_cases]) -def test_resource_factory(input, expected): - r = Resource.factory(input) - assert r.__class__ == expected + ids=[cls.__name__ for (_, cls, _) in test_cases]) +def test_gcp_resource_factory(input, cls, rtype): + r = Resource.factory("gcp", input) + assert r.__class__ == cls + assert r.type() == rtype -def test_resource_factory_invalid(): - with pytest.raises(AssertionError): - r = Resource.factory({}) +def test_gcp_resource_factory_invalid(): + with pytest.raises(AssertionError): + r = Resource.factory('gcp', {})
0b32ae7a09dd961f379104b6628eaf5700cca785
tests/test_unlocking.py
tests/test_unlocking.py
# Tests for SecretStorage # Author: Dmitry Shachnev, 2018 # License: 3-clause BSD, see LICENSE file import unittest from secretstorage import dbus_init, get_any_collection from secretstorage.util import BUS_NAME from secretstorage.exceptions import LockedException @unittest.skipIf(BUS_NAME == "org.freedesktop.secrets", "This test should only be run with the mocked server.") class LockingUnlockingTest(unittest.TestCase): def setUp(self) -> None: self.connection = dbus_init() self.collection = get_any_collection(self.connection) def test_lock_unlock(self) -> None: self.collection.lock() self.assertTrue(self.collection.is_locked()) self.assertRaises(LockedException, self.collection.ensure_not_locked) self.assertIs(self.collection.unlock(), False) self.assertFalse(self.collection.is_locked()) self.collection.ensure_not_locked()
# Tests for SecretStorage # Author: Dmitry Shachnev, 2018 # License: 3-clause BSD, see LICENSE file import unittest from secretstorage import dbus_init, Collection from secretstorage.util import BUS_NAME from secretstorage.exceptions import LockedException @unittest.skipIf(BUS_NAME == "org.freedesktop.secrets", "This test should only be run with the mocked server.") class LockingUnlockingTest(unittest.TestCase): def setUp(self) -> None: self.connection = dbus_init() collection_path = "/org/freedesktop/secrets/collection/english" self.collection = Collection(self.connection, collection_path) def test_lock_unlock(self) -> None: self.assertFalse(self.collection.is_locked()) self.collection.lock() self.assertTrue(self.collection.is_locked()) self.assertRaises(LockedException, self.collection.ensure_not_locked) item, = self.collection.search_items({"number": "1"}) self.assertRaises(LockedException, item.ensure_not_locked) self.assertIs(self.collection.unlock(), False) self.assertFalse(self.collection.is_locked()) self.collection.ensure_not_locked()
Add test coverage for Item.ensure_not_locked() method
Add test coverage for Item.ensure_not_locked() method
Python
bsd-3-clause
mitya57/secretstorage
--- +++ @@ -4,7 +4,7 @@ import unittest -from secretstorage import dbus_init, get_any_collection +from secretstorage import dbus_init, Collection from secretstorage.util import BUS_NAME from secretstorage.exceptions import LockedException @@ -14,12 +14,16 @@ class LockingUnlockingTest(unittest.TestCase): def setUp(self) -> None: self.connection = dbus_init() - self.collection = get_any_collection(self.connection) + collection_path = "/org/freedesktop/secrets/collection/english" + self.collection = Collection(self.connection, collection_path) def test_lock_unlock(self) -> None: + self.assertFalse(self.collection.is_locked()) self.collection.lock() self.assertTrue(self.collection.is_locked()) self.assertRaises(LockedException, self.collection.ensure_not_locked) + item, = self.collection.search_items({"number": "1"}) + self.assertRaises(LockedException, item.ensure_not_locked) self.assertIs(self.collection.unlock(), False) self.assertFalse(self.collection.is_locked()) self.collection.ensure_not_locked()
d59635e9542ca54b39eaa10f31b53da46df68e61
neutron/plugins/ml2/drivers/mlnx/config.py
neutron/plugins/ml2/drivers/mlnx/config.py
# Copyright (c) 2014 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo.config import cfg from neutron.extensions import portbindings eswitch_opts = [ cfg.StrOpt('vnic_type', default=portbindings.VIF_TYPE_MLNX_DIRECT, help=_("Type of VM network interface: mlnx_direct or " "hostdev")), cfg.BoolOpt('apply_profile_patch', default=False, help=_("Enable server compatibility with old nova ")), ] cfg.CONF.register_opts(eswitch_opts, "ESWITCH")
# Copyright (c) 2014 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo.config import cfg from neutron.extensions import portbindings eswitch_opts = [ cfg.StrOpt('vnic_type', default=portbindings.VIF_TYPE_MLNX_DIRECT, help=_("Type of VM network interface: mlnx_direct or " "hostdev")), cfg.BoolOpt('apply_profile_patch', default=False, help=_("Enable server compatibility with old nova")), ] cfg.CONF.register_opts(eswitch_opts, "ESWITCH")
Remove extra space in help string
Remove extra space in help string Extra spaces make the openstack-manuals tests fail with a niceness error. This patch removes an extra space at the end of a help string. Change-Id: I29bab90ea5a6f648c4539c7cd20cd9b2b63055c2
Python
apache-2.0
gkotton/vmware-nsx,gkotton/vmware-nsx
--- +++ @@ -25,7 +25,7 @@ "hostdev")), cfg.BoolOpt('apply_profile_patch', default=False, - help=_("Enable server compatibility with old nova ")), + help=_("Enable server compatibility with old nova")), ]
aa3029f962e47a6c0cd3023192616acb8eff5b75
third_party/__init__.py
third_party/__init__.py
import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.append(os.path.dirname(__file__))
import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.insert(1, os.path.dirname(__file__))
Insert third_party into the second slot of sys.path rather than the last slot
Insert third_party into the second slot of sys.path rather than the last slot
Python
apache-2.0
protron/namebench,google/namebench,rogers0/namebench,google/namebench,google/namebench
--- +++ @@ -2,4 +2,4 @@ import sys # This bit of evil should inject third_party into the path for relative imports. -sys.path.append(os.path.dirname(__file__)) +sys.path.insert(1, os.path.dirname(__file__))
bbeb9b780908cf1322722669f1c68259345fe261
readthedocs/v3/routers.py
readthedocs/v3/routers.py
from rest_framework.routers import DefaultRouter from rest_framework_extensions.routers import NestedRouterMixin class DefaultRouterWithNesting(NestedRouterMixin, DefaultRouter): pass
from rest_framework.routers import DefaultRouter, APIRootView from rest_framework_extensions.routers import NestedRouterMixin class DocsAPIRootView(APIRootView): # Overridden only to add documentation for BrowsableAPIRenderer. """ Read the Docs APIv3 root endpoint. Full documentation at [https://docs.readthedocs.io/en/latest/api/v3.html](https://docs.readthedocs.io/en/latest/api/v3.html). """ def get_view_name(self): return 'Read the Docs APIv3' class DefaultRouterWithNesting(NestedRouterMixin, DefaultRouter): APIRootView = DocsAPIRootView root_view_name = 'api-v3-root'
Add documentation to the root view of BrowsableAPI
Add documentation to the root view of BrowsableAPI
Python
mit
rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org
--- +++ @@ -1,6 +1,21 @@ -from rest_framework.routers import DefaultRouter +from rest_framework.routers import DefaultRouter, APIRootView from rest_framework_extensions.routers import NestedRouterMixin +class DocsAPIRootView(APIRootView): + + # Overridden only to add documentation for BrowsableAPIRenderer. + + """ + Read the Docs APIv3 root endpoint. + + Full documentation at [https://docs.readthedocs.io/en/latest/api/v3.html](https://docs.readthedocs.io/en/latest/api/v3.html). + """ + + def get_view_name(self): + return 'Read the Docs APIv3' + + class DefaultRouterWithNesting(NestedRouterMixin, DefaultRouter): - pass + APIRootView = DocsAPIRootView + root_view_name = 'api-v3-root'
20696d6f236afc1bc0e2b3db570363540e70ca84
test/test_serve.py
test/test_serve.py
import unittest import asyncio import io import multiprocessing import urllib.request import time import grole def simple_server(): app = grole.Grole() @app.route('/') def hello(env, req): return 'Hello, World!' app.run() class TestServe(unittest.TestCase): def test_simple(self): p = multiprocessing.Process(target=simple_server) p.start() time.sleep(0.1) with urllib.request.urlopen('http://localhost:1234') as response: html = response.read() self.assertEqual(html, b'Hello, World!') p.terminate() def test_fileserver(self): p = multiprocessing.Process(target=grole.main, args=[[]]) p.start() time.sleep(0.1) with urllib.request.urlopen('http://localhost:1234/test/test.dat') as response: html = response.read() self.assertEqual(html, b'foo\n') p.terminate()
import unittest import asyncio import io import multiprocessing import urllib.request import time import grole def simple_server(): app = grole.Grole() @app.route('/') def hello(env, req): return 'Hello, World!' app.run(host='127.0.0.1') class TestServe(unittest.TestCase): def test_simple(self): p = multiprocessing.Process(target=simple_server) p.start() time.sleep(0.1) with urllib.request.urlopen('http://127.0.0.1:1234') as response: html = response.read() self.assertEqual(html, b'Hello, World!') p.terminate() def test_fileserver(self): p = multiprocessing.Process(target=grole.main, args=[['-a', '127.0.0.1']]) p.start() time.sleep(0.1) with urllib.request.urlopen('http://127.0.0.1:1234/test/test.dat') as response: html = response.read() self.assertEqual(html, b'foo\n') p.terminate()
Use ip instead of localhost for travis
Use ip instead of localhost for travis
Python
mit
witchard/grole
--- +++ @@ -14,7 +14,7 @@ def hello(env, req): return 'Hello, World!' - app.run() + app.run(host='127.0.0.1') class TestServe(unittest.TestCase): @@ -22,16 +22,16 @@ p = multiprocessing.Process(target=simple_server) p.start() time.sleep(0.1) - with urllib.request.urlopen('http://localhost:1234') as response: + with urllib.request.urlopen('http://127.0.0.1:1234') as response: html = response.read() self.assertEqual(html, b'Hello, World!') p.terminate() def test_fileserver(self): - p = multiprocessing.Process(target=grole.main, args=[[]]) + p = multiprocessing.Process(target=grole.main, args=[['-a', '127.0.0.1']]) p.start() time.sleep(0.1) - with urllib.request.urlopen('http://localhost:1234/test/test.dat') as response: + with urllib.request.urlopen('http://127.0.0.1:1234/test/test.dat') as response: html = response.read() self.assertEqual(html, b'foo\n') p.terminate()
5e0e22eb6e709eb5291ac50a28b96c2c05909a2d
src/artgraph/miner.py
src/artgraph/miner.py
import pymw import pymw.interfaces import artgraph.plugins.infobox from artgraph.node import NodeTypes from artgraph.node import Node class Miner(object): nodes = [] relationships = [] master = None task_queue = [] def __init__(self, debug=False): mwinterface = pymw.interfaces.GenericInterface() self.master = pymw.PyMW_Master(mwinterface, delete_files=not debug) def mine(self, artist): self.mine_internal(Node(artist, NodeTypes.ARTIST)) new_relationships = self.master.get_result() while new_relationships: for n in new_relationships: self.relationships.append(n) if n.get_predicate() not in self.nodes: self.mine_internal(n.get_predicate()) def mine_internal(self, current_node, level=0, parent=None, relationship=None): self.nodes.append(current_node) infoboxplugin = artgraph.plugins.infobox.InfoboxPlugin(current_node) self.task_queue.append(self.master.submit_task(infoboxplugin.get_nodes, input_data=(infoboxplugin,), modules=("artgraph",), data_files=("my.cnf",)))
import pymw import pymw.interfaces import artgraph.plugins.infobox from artgraph.node import NodeTypes from artgraph.node import Node class Miner(object): nodes = [] relationships = [] master = None task_queue = [] def __init__(self, debug=False): mwinterface = pymw.interfaces.GenericInterface() self.master = pymw.PyMW_Master(mwinterface, delete_files=not debug) def mine(self, artist): self.mine_internal(Node(artist, NodeTypes.ARTIST)) (finished_task, new_relationships) = self.master.get_result() while new_relationships: for n in new_relationships: self.relationships.append(n) if n.get_predicate() not in self.nodes: self.mine_internal(n.get_predicate()) def mine_internal(self, current_node, level=0, parent=None, relationship=None): self.nodes.append(current_node) infoboxplugin = artgraph.plugins.infobox.InfoboxPlugin(current_node) self.task_queue.append(self.master.submit_task(infoboxplugin.get_nodes, input_data=(infoboxplugin,), modules=("artgraph",), data_files=("my.cnf",)))
Return value of get_result is a pair of (task, result data)
Return value of get_result is a pair of (task, result data)
Python
mit
dMaggot/ArtistGraph
--- +++ @@ -18,7 +18,7 @@ def mine(self, artist): self.mine_internal(Node(artist, NodeTypes.ARTIST)) - new_relationships = self.master.get_result() + (finished_task, new_relationships) = self.master.get_result() while new_relationships: for n in new_relationships:
bfbb1e4fb8324df9a039c18359c053190f9e7e64
dusty/commands/manage_config.py
dusty/commands/manage_config.py
import textwrap from prettytable import PrettyTable from ..config import get_config, save_config_value from .. import constants from ..log import log_to_client def _eligible_config_keys_for_setting(): config = get_config() return [key for key in sorted(constants.CONFIG_SETTINGS.keys()) if key not in config or isinstance(config[key], basestring)] def list_config(): config = get_config() table = PrettyTable(['Key', 'Description', 'Value']) for key, description in constants.CONFIG_SETTINGS.iteritems(): table.add_row([key, '\n'.join(textwrap.wrap(description, 80)), config.get(key)]) log_to_client(table.get_string(sortby='Key')) def list_config_values(): log_to_client(get_config()) def save_value(key, value): config = get_config() if key not in constants.CONFIG_SETTINGS: raise KeyError('Your key {} must be in the list {}'.format(key, sorted(constants.CONFIG_SETTINGS.keys()))) if key in config and not isinstance(config[key], basestring): raise KeyError('You can only modify string values in your config. {} has type {}'.format(key, type(config[key]))) else: save_config_value(key, value) log_to_client('Set {} to {} in your config'.format(key, value))
import textwrap from prettytable import PrettyTable from ..config import get_config, save_config_value from .. import constants from ..log import log_to_client def _eligible_config_keys_for_setting(): config = get_config() return [key for key in sorted(constants.CONFIG_SETTINGS.keys()) if key not in config or isinstance(config[key], basestring)] def list_config(): config = get_config() table = PrettyTable(['Key', 'Description', 'Value']) for key, description in constants.CONFIG_SETTINGS.iteritems(): table.add_row([key, '\n'.join(textwrap.wrap(description, 80)), '\n'.join(textwrap.wrap(str(config.get(key)), 80))]) log_to_client(table.get_string(sortby='Key')) def list_config_values(): log_to_client(get_config()) def save_value(key, value): config = get_config() if key not in constants.CONFIG_SETTINGS: raise KeyError('Your key {} must be in the list {}'.format(key, sorted(constants.CONFIG_SETTINGS.keys()))) if key in config and not isinstance(config[key], basestring): raise KeyError('You can only modify string values in your config. {} has type {}'.format(key, type(config[key]))) else: save_config_value(key, value) log_to_client('Set {} to {} in your config'.format(key, value))
Make config list able to handle long values
Make config list able to handle long values
Python
mit
gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty
--- +++ @@ -15,7 +15,9 @@ config = get_config() table = PrettyTable(['Key', 'Description', 'Value']) for key, description in constants.CONFIG_SETTINGS.iteritems(): - table.add_row([key, '\n'.join(textwrap.wrap(description, 80)), config.get(key)]) + table.add_row([key, + '\n'.join(textwrap.wrap(description, 80)), + '\n'.join(textwrap.wrap(str(config.get(key)), 80))]) log_to_client(table.get_string(sortby='Key')) def list_config_values():
d34fbc70d5873d159c311caed41b745b05534ce9
lib/solution.py
lib/solution.py
class Solution: def __init__(self, nr): self.nr = nr self.test = False self.input = "" self.solution = ["(not calculated)", "(not calculated)"] self.calculated = [False, False] def __str__(self): return "Solution 1: {}\nSolution 2: {}".format(self.solution[0], self.solution[1]) def calculate(self, test=False): raise NotImplementedError('users must define calculate to use this base class') def get_solution(self, nr): if nr in [1, 2]: return self.solution[nr-1] def set_solution(self, nr, value): if nr in [1, 2]: self.solution[nr-1] = value self.calculated[nr-1] = True def is_calculated(self, nr): if nr in [1, 2]: return self.calculated[nr-1] def read_input(self): with open(self.nr+"/input.txt", "r") as f: self.input = f.read()
class Solution: def __init__(self, nr): self.nr = nr self.test = False self.input = "" self.solution = ["(not calculated)", "(not calculated)"] self.calculated = [False, False] def __str__(self): return "Solution 1: {}\nSolution 2: {}".format(self.solution[0], self.solution[1]) def calculate(self, test=False): raise NotImplementedError('users must define calculate to use this base class') def get_solution(self, nr): if nr in [1, 2]: return self.solution[nr-1] def set_solution(self, nr, value): if nr in [1, 2]: self.solution[nr-1] = value self.calculated[nr-1] = True def is_calculated(self, nr): if nr in [1, 2]: return self.calculated[nr-1] def read_input(self, lines=False): with open(self.nr+"/input.txt", "r") as f: if lines: self.input = f.readlines() else: self.input = f.read()
Read Input: Read file complete or by lines
Read Input: Read file complete or by lines
Python
mit
unstko/adventofcode2016
--- +++ @@ -25,6 +25,9 @@ if nr in [1, 2]: return self.calculated[nr-1] - def read_input(self): + def read_input(self, lines=False): with open(self.nr+"/input.txt", "r") as f: - self.input = f.read() + if lines: + self.input = f.readlines() + else: + self.input = f.read()
0f8b6f4a12c23e5498e8135a3f39da40c4333788
tests/hexdumper.py
tests/hexdumper.py
# This hack by: Raymond Hettinger class hexdumper: """Given a byte array, turn it into a string. hex bytes to stdout.""" def __init__(self): self.FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' \ for x in range(256)]) def dump(self, src, length=8): result=[] for i in xrange(0, len(src), length): s = src[i:i+length] hexa = ' '.join(["%02X"%ord(x) for x in s]) printable = s.translate(self.FILTER) result.append("%04X %-*s %s\n" % \ (i, length*3, hexa, printable)) return ''.join(result)
# This hack by: Raymond Hettinger class hexdumper: """Given a byte array, turn it into a string. hex bytes to stdout.""" def __init__(self): self.FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' \ for x in range(256)]) # pretty dumping hate machine. def dump(self, src, length=8): result=[] for i in xrange(0, len(src), length): s = src[i:i+length] hexa = ' '.join(["%02X"%ord(x) for x in s]) printable = s.translate(self.FILTER) result.append("%04X %-*s %s\n" % \ (i, length*3, hexa, printable)) return ''.join(result) # dump in a way which can be embedded in a python string. def dump2(self, src, length=8): result=[] for i in xrange(0, len(src), length): s = src[i:i+length] hexa = ''.join(["\\x%02X"%ord(x) for x in s]) result.append("\"%-*s\"" % (length*3, hexa)) if i + length < len(src): result.append(" \\") result.append("\n") return ''.join(result)
Add a function which allows packet dumps to be produced easily for inserting into regression tests.
Add a function which allows packet dumps to be produced easily for inserting into regression tests.
Python
bsd-3-clause
gvnn3/PCS,gvnn3/PCS
--- +++ @@ -5,6 +5,7 @@ self.FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' \ for x in range(256)]) + # pretty dumping hate machine. def dump(self, src, length=8): result=[] for i in xrange(0, len(src), length): @@ -14,3 +15,15 @@ result.append("%04X %-*s %s\n" % \ (i, length*3, hexa, printable)) return ''.join(result) + + # dump in a way which can be embedded in a python string. + def dump2(self, src, length=8): + result=[] + for i in xrange(0, len(src), length): + s = src[i:i+length] + hexa = ''.join(["\\x%02X"%ord(x) for x in s]) + result.append("\"%-*s\"" % (length*3, hexa)) + if i + length < len(src): + result.append(" \\") + result.append("\n") + return ''.join(result)
06e84c25bb783490c963963ccb44cf07d521a197
spam_lists/exceptions.py
spam_lists/exceptions.py
# -*- coding: utf-8 -*- class SpamBLError(Exception): ''' Base exception class for spambl module ''' class UnknownCodeError(SpamBLError): ''' Raise when trying to use an unexpected value of dnsbl return code ''' class UnathorizedAPIKeyError(SpamBLError): ''' Raise when trying to use an unathorized api key '''
# -*- coding: utf-8 -*- class SpamBLError(Exception): '''There was an error during testing a url or host''' class UnknownCodeError(SpamBLError): '''The classification code from the service was not recognized''' class UnathorizedAPIKeyError(SpamBLError): '''The API key used to query the service was not authorized'''
Reword docstrings for exception classes
Reword docstrings for exception classes
Python
mit
piotr-rusin/spam-lists
--- +++ @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- class SpamBLError(Exception): - ''' Base exception class for spambl module ''' + '''There was an error during testing a url or host''' class UnknownCodeError(SpamBLError): - ''' Raise when trying to use an unexpected value of dnsbl return code ''' + '''The classification code from the service was not recognized''' class UnathorizedAPIKeyError(SpamBLError): - ''' Raise when trying to use an unathorized api key ''' + '''The API key used to query the service was not authorized'''
4ca292e53710dd4ef481e7fa5965e22d3f94e65b
l10n_br_account_payment_order/models/cnab_return_move_code.py
l10n_br_account_payment_order/models/cnab_return_move_code.py
# Copyright 2020 Akretion # @author Magno Costa <magno.costa@akretion.com.br> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models, api, fields class CNABReturnMoveCode(models.Model): """ CNAB return code, each Bank can has a list of Codes """ _name = 'cnab.return.move.code' _description = 'CNAB Return Move Code' name = fields.Char(string='Name') code = fields.Char(string='Code') bank_id = fields.Many2one( string='Bank', comodel_name='res.bank' ) payment_method_id = fields.Many2one( 'account.payment.method', string='Payment Method' ) # Fields used to create domain bank_code_bc = fields.Char( related='bank_id.code_bc', ) payment_method_code = fields.Char(related='payment_method_id.code') @api.multi def name_get(self): result = [] for record in self: result.append(( record.id, '%s - %s' % ( record.code, record.name) )) return result
# Copyright 2020 Akretion # @author Magno Costa <magno.costa@akretion.com.br> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models, api, fields class CNABReturnMoveCode(models.Model): """ CNAB return code, each Bank can has a list of Codes """ _name = 'cnab.return.move.code' _description = 'CNAB Return Move Code' name = fields.Char( string='Name', index=True, ) code = fields.Char( string='Code', index=True, ) bank_id = fields.Many2one( string='Bank', comodel_name='res.bank', index=True, ) payment_method_id = fields.Many2one( comodel_name='account.payment.method', string='Payment Method', index=True, ) # Fields used to create domain bank_code_bc = fields.Char( related='bank_id.code_bc', store=True, ) payment_method_code = fields.Char( related='payment_method_id.code', store=True, ) @api.multi def name_get(self): result = [] for record in self: result.append(( record.id, '%s - %s' % ( record.code, record.name) )) return result
Index and code improve cnab.return.move.code
[REF] Index and code improve cnab.return.move.code Signed-off-by: Luis Felipe Mileo <c9a5b4d335634d99740001a1172b3e56e4fc5aa8@kmee.com.br>
Python
agpl-3.0
akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil
--- +++ @@ -12,19 +12,33 @@ _name = 'cnab.return.move.code' _description = 'CNAB Return Move Code' - name = fields.Char(string='Name') - code = fields.Char(string='Code') + name = fields.Char( + string='Name', + index=True, + ) + code = fields.Char( + string='Code', + index=True, + ) bank_id = fields.Many2one( - string='Bank', comodel_name='res.bank' + string='Bank', + comodel_name='res.bank', + index=True, ) payment_method_id = fields.Many2one( - 'account.payment.method', string='Payment Method' + comodel_name='account.payment.method', + string='Payment Method', + index=True, ) # Fields used to create domain bank_code_bc = fields.Char( related='bank_id.code_bc', + store=True, ) - payment_method_code = fields.Char(related='payment_method_id.code') + payment_method_code = fields.Char( + related='payment_method_id.code', + store=True, + ) @api.multi def name_get(self):
f0766ff22a7ee7c3e9a48c468f7e1f41e9d7e92c
vizier/__init__.py
vizier/__init__.py
"""Init file.""" import os import sys THIS_DIR = os.path.dirname(os.path.realpath(__file__)) PROTO_ROOT = os.path.realpath(os.path.join(THIS_DIR, "service")) sys.path.append(PROTO_ROOT) __version__ = "0.0.3.alpha"
"""Init file.""" import os import sys THIS_DIR = os.path.dirname(os.path.realpath(__file__)) PROTO_ROOT = os.path.realpath(os.path.join(THIS_DIR, "service")) sys.path.append(PROTO_ROOT) __version__ = "0.0.5.dev"
Update repo version to v0.0.5.dev
Update repo version to v0.0.5.dev PiperOrigin-RevId: 471307548
Python
apache-2.0
google/vizier,google/vizier
--- +++ @@ -7,4 +7,4 @@ sys.path.append(PROTO_ROOT) -__version__ = "0.0.3.alpha" +__version__ = "0.0.5.dev"
1891469e5d3eb34efbe3c5feed1f7770e680120e
automata/nfa.py
automata/nfa.py
#!/usr/bin/env python3 import automata.automaton as automaton class NFA(automaton.Automaton): """a deterministic finite automaton""" def validate_automaton(self): """returns True if this NFA is internally consistent; raises the appropriate exception if this NFA is invalid""" for state in self.states: if state not in self.transitions: raise automaton.MissingStateError( 'state {} is missing from transition function'.format( state)) for start_state, paths in self.transitions.items(): invalid_states = set().union(*paths.values()).difference( self.states) if invalid_states: raise automaton.InvalidStateError( 'states are not valid ({})'.format( ', '.join(invalid_states))) if self.initial_state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(self.initial_state)) for state in self.final_states: if state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(state)) return True # TODO def validate_input(self, input_str): """returns True if the given string is accepted by this NFA; raises the appropriate exception if the string is not accepted""" return True
#!/usr/bin/env python3 import automata.automaton as automaton class NFA(automaton.Automaton): """a nondeterministic finite automaton""" def validate_automaton(self): """returns True if this NFA is internally consistent; raises the appropriate exception if this NFA is invalid""" for state in self.states: if state not in self.transitions: raise automaton.MissingStateError( 'state {} is missing from transition function'.format( state)) for start_state, paths in self.transitions.items(): invalid_states = set().union(*paths.values()).difference( self.states) if invalid_states: raise automaton.InvalidStateError( 'states are not valid ({})'.format( ', '.join(invalid_states))) if self.initial_state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(self.initial_state)) for state in self.final_states: if state not in self.states: raise automaton.InvalidStateError( '{} is not a valid state'.format(state)) return True # TODO def validate_input(self, input_str): """returns True if the given string is accepted by this NFA; raises the appropriate exception if the string is not accepted""" return True
Fix incorrect docstring for NFA class
Fix incorrect docstring for NFA class
Python
mit
caleb531/automata
--- +++ @@ -4,7 +4,7 @@ class NFA(automaton.Automaton): - """a deterministic finite automaton""" + """a nondeterministic finite automaton""" def validate_automaton(self): """returns True if this NFA is internally consistent;
440fcebdcc06c0fbb26341764a0df529cec6587d
flask_wiki/frontend/frontend.py
flask_wiki/frontend/frontend.py
from flask import Flask, render_template, abort, redirect, url_for from flask.ext.script import Manager from jinja2 import TemplateNotFound app = Flask(__name__) app.config['TESTING'] = True manager = Manager(app) @app.route('/', endpoint='frontend-index') def root(): # Redirect Base URL for the real Index Page. return redirect(url_for('frontend-pages', page='index')) @app.route('/<page>', endpoint='frontend-pages') def show(page='index'): """ Try to Deliver a page. :param page: name of the page :return: template. """ try: return render_template('pages/%s.html' % page) except (TemplateNotFound,): abort(404) if __name__ == '__main__': manager.run()
from flask import Flask, render_template, abort, redirect, url_for from flask.ext.script import Manager from jinja2 import TemplateNotFound app = Flask(__name__) app.config['TESTING'] = True manager = Manager(app) @app.route('/', endpoint='frontend-index') def root(): # Redirect Base URL for the real Index Page. return redirect(url_for('frontend-pages', page='index')) @app.route('/<page>', endpoint='frontend-pages') def show(page='index'): """ Try to Deliver a page. :param page: name of the page :return: template. """ try: return render_template('pages/index.html') except (TemplateNotFound,): abort(404) if __name__ == '__main__': manager.run()
Support for angular + API added.
Support for angular + API added.
Python
bsd-2-clause
gcavalcante8808/flask-wiki,gcavalcante8808/flask-wiki,gcavalcante8808/flask-wiki
--- +++ @@ -1,6 +1,5 @@ from flask import Flask, render_template, abort, redirect, url_for from flask.ext.script import Manager - from jinja2 import TemplateNotFound app = Flask(__name__) @@ -22,7 +21,7 @@ :return: template. """ try: - return render_template('pages/%s.html' % page) + return render_template('pages/index.html') except (TemplateNotFound,): abort(404)
fb6e5b11492675b7a7c94424737c91acbb541d69
tests/test_message_body.py
tests/test_message_body.py
from tddcommitmessage.messagebody import MessageBody from tddcommitmessage import Kind def test_message_is_wrapped_in_quotes(): msg = MessageBody(Kind.red, 'Forty-two') assert str(msg) == '"RED Forty-two"' def test_message_with_double_quote_is_wrapped_with_single(): msg = MessageBody(Kind.red, 'But what are "Birds"?') assert str(msg) == r"""'RED But what are "Birds"?'""" def test_first_letter_capitalised(): msg = MessageBody(Kind.red, 'forty-two') assert str(msg) == '"RED Forty-two"'
from tddcommitmessage.messagebody import MessageBody from tddcommitmessage import Kind def test_message_is_wrapped_in_quotes(): msg = MessageBody(Kind.red, 'Forty-two') assert str(msg) == '"RED Forty-two"' def test_first_letter_capitalised(): msg = MessageBody(Kind.red, 'forty-two') assert str(msg) == '"RED Forty-two"' def test_message_with_double_quote_is_wrapped_with_single(): msg = MessageBody(Kind.red, 'But what are "Birds"?') assert str(msg) == r"""'RED But what are "Birds"?'"""
REFACTOR Change order of tests.
REFACTOR Change order of tests.
Python
mit
matatk/tdd-bdd-commit,matatk/tdd-bdd-commit
--- +++ @@ -5,10 +5,10 @@ msg = MessageBody(Kind.red, 'Forty-two') assert str(msg) == '"RED Forty-two"' +def test_first_letter_capitalised(): + msg = MessageBody(Kind.red, 'forty-two') + assert str(msg) == '"RED Forty-two"' + def test_message_with_double_quote_is_wrapped_with_single(): msg = MessageBody(Kind.red, 'But what are "Birds"?') assert str(msg) == r"""'RED But what are "Birds"?'""" - -def test_first_letter_capitalised(): - msg = MessageBody(Kind.red, 'forty-two') - assert str(msg) == '"RED Forty-two"'
ef617d4e98d9c029225a32098cc81aeab1d6deb5
genes/gnu_coreutils/commands.py
genes/gnu_coreutils/commands.py
#!/usr/bin/env python from genes.posix.traits import only_posix from genes.process.commands import run @only_posix() def chgrp(path, group): run(['chgrp', group, path]) @only_posix() def chown(path, user): run(['chown', user, path]) @only_posix() def groupadd(*args): run(['groupadd'] + list(*args)) @only_posix() def mkdir(path, mode=None): if mode: run(['mkdir', '-m', mode, path]) else: run(['mkdir', path]) @only_posix() def useradd(*args): # FIXME: this is a bad way to do things # FIXME: sigh. this is going to be a pain to make it idempotent run(['useradd'] + list(*args)) @only_posix() def usermod(*args): # FIXME: this is a bad way to do things run(['usermod'] + list(*args))
#!/usr/bin/env python from genes.posix.traits import only_posix from genes.process.commands import run @only_posix() def chgrp(path, group): run(['chgrp', group, path]) @only_posix() def chown(path, user): run(['chown', user, path]) @only_posix() def groupadd(*args): run(['groupadd'] + list(*args)) @only_posix() def ln(*args): run(['ln'] + list(*args)) @only_posix() def mkdir(path, mode=None): if mode: run(['mkdir', '-m', mode, path]) else: run(['mkdir', path]) @only_posix() def useradd(*args): # FIXME: this is a bad way to do things # FIXME: sigh. this is going to be a pain to make it idempotent run(['useradd'] + list(*args)) @only_posix() def usermod(*args): # FIXME: this is a bad way to do things run(['usermod'] + list(*args))
Add link to gnu coreutils
Add link to gnu coreutils
Python
mit
hatchery/Genepool2,hatchery/genepool
--- +++ @@ -20,6 +20,11 @@ @only_posix() +def ln(*args): + run(['ln'] + list(*args)) + + +@only_posix() def mkdir(path, mode=None): if mode: run(['mkdir', '-m', mode, path])
8ac142af2afc577a47197fe9bc821cb796883f38
virtual_machine.py
virtual_machine.py
class VirtualMachine: def __init__(self, bytecodes, ram_size=256, executing=True): self.bytecodes = bytecodes self.data = [None]*ram_size self.stack = [] self.executing = executing self.pc = 0 def push(self, value): """Push something onto the stack.""" self.stack += [value] def pop(self): """Pop something from the stack. Crash if empty.""" return self.stack.pop() def read_memory(self, index): """Read from memory, crashing if index is out of bounds.""" return self.data[index] def write_memory(self, index, value): """Write to memory. Crash if index is out of bounds.""" self.data[index] = value def run(self): while self.executing: self.bytecodes[self.pc].execute(self) if self.bytecodes[self.pc].autoincrement: self.pc += 1
class VirtualMachine: def __init__(self, bytecodes, ram_size=256, executing=True): self.bytecodes = bytecodes self.data = [None]*ram_size self.stack = [] self.executing = executing self.pc = 0 def push(self, value): """Push something onto the stack.""" self.stack += [value] def pop(self): """Pop something from the stack. Crash if empty.""" return self.stack.pop() def read_memory(self, index): """Read from memory, crashing if index is out of bounds.""" return self.data[index] def write_memory(self, index, value): """Write to memory. Crash if index is out of bounds.""" self.data[index] = value def run(self): while self.executing: increment = self.bytecodes[self.pc].autoincrement self.bytecodes[self.pc].execute(self) if increment: self.pc += 1
Check for autoincrement before executing the instruction
Check for autoincrement before executing the instruction
Python
bsd-3-clause
darbaga/simple_compiler
--- +++ @@ -24,7 +24,8 @@ def run(self): while self.executing: + increment = self.bytecodes[self.pc].autoincrement self.bytecodes[self.pc].execute(self) - if self.bytecodes[self.pc].autoincrement: + if increment: self.pc += 1
450b72dd97534c7317a6256ec2b2cd30bc0a0e59
ocookie/httplibadapter.py
ocookie/httplibadapter.py
from . import CookieParser, CookieDict def parse_cookies(httplib_headers): cookies = [ CookieParser.parse_set_cookie_value( header[1] ) for header in httplib_headers if header[0].lower() == 'set-cookie' ] return cookies
from . import CookieParser, CookieDict def parse_cookies(httplib_set_cookie_headers): cookies = [] for header in httplib_set_cookie_headers: header = header.strip() name, value = header.split(' ', 1) value = value.strip() cookie = CookieParser.parse_set_cookie_value(value) cookies.append(cookie) return cookies def parse_response_cookies(httplib_response): # RFC 2616 specifies that multiple headers can be combined into # a single header by joining their values with commas # (http://stackoverflow.com/questions/2454494/urllib2-multiple-set-cookie-headers-in-response). # However, Set-Cookie headers simply cannot be combined in that way # as they have commas in dates and also there is no standard # way of quoting cookie values, which may also have commas. # Therefore the correct way of accessing Set-Cookie headers # is via httplib_response.msg.getallmatchingheaders() call. # http://mail.python.org/pipermail/python-bugs-list/2007-March/037618.html # Also: # http://stackoverflow.com/questions/1649401/how-to-handle-multiple-set-cookie-header-in-http-response headers = httplib_response.msg.getallmatchingheaders('set-cookie') headers.extend(httplib_response.msg.getallmatchingheaders('set-cookie2')) return parse_cookies(headers)
Change API for parsing httplib cookies
Change API for parsing httplib cookies
Python
bsd-2-clause
p/ocookie
--- +++ @@ -1,9 +1,27 @@ from . import CookieParser, CookieDict -def parse_cookies(httplib_headers): - cookies = [ - CookieParser.parse_set_cookie_value( - header[1] - ) for header in httplib_headers if header[0].lower() == 'set-cookie' - ] +def parse_cookies(httplib_set_cookie_headers): + cookies = [] + for header in httplib_set_cookie_headers: + header = header.strip() + name, value = header.split(' ', 1) + value = value.strip() + cookie = CookieParser.parse_set_cookie_value(value) + cookies.append(cookie) return cookies + +def parse_response_cookies(httplib_response): + # RFC 2616 specifies that multiple headers can be combined into + # a single header by joining their values with commas + # (http://stackoverflow.com/questions/2454494/urllib2-multiple-set-cookie-headers-in-response). + # However, Set-Cookie headers simply cannot be combined in that way + # as they have commas in dates and also there is no standard + # way of quoting cookie values, which may also have commas. + # Therefore the correct way of accessing Set-Cookie headers + # is via httplib_response.msg.getallmatchingheaders() call. + # http://mail.python.org/pipermail/python-bugs-list/2007-March/037618.html + # Also: + # http://stackoverflow.com/questions/1649401/how-to-handle-multiple-set-cookie-header-in-http-response + headers = httplib_response.msg.getallmatchingheaders('set-cookie') + headers.extend(httplib_response.msg.getallmatchingheaders('set-cookie2')) + return parse_cookies(headers)
de60844c82c9b569228aa830d36235b5a377859d
rpath_tools/client/sysdisco/descriptors.py
rpath_tools/client/sysdisco/descriptors.py
#!/usr/bin/python from xml.etree import cElementTree as etree from conary import conarycfg from conary import conaryclient from rpath_tools.client.utils.config_descriptor_cache import ConfigDescriptorCache class Descriptors(object): def __init__(self): self.cfg = conarycfg.ConaryConfiguration(True) self.client = conaryclient.ConaryClient(self.cfg) def gather(self): group = [ x for x in self.client.getUpdateItemList() if x[0].startswith('group-') and x[0].endswith('-appliance') ][0] desc = ConfigDescriptorCache(self.client.getDatabase()).getDescriptor(group) if desc: desc.setDisplayName('ConfigurationDescriptor') desc.addDescription('ConfigurationDescriptor') return desc def toxml(self, validate=False): desc = self.gather() if desc: return desc.toxml(validate=validate) return desc if __name__ == '__main__': import sys from conary.lib import util sys.excepthook = util.genExcepthook() descriptors = Descriptors() xml = etree.fromstring(descriptors.toxml()) print etree.tostring(xml)
#!/usr/bin/python from xml.etree import cElementTree as etree from conary import conarycfg from conary import conaryclient from rpath_tools.client.utils.config_descriptor_cache import ConfigDescriptorCache class Descriptors(object): def __init__(self): self.cfg = conarycfg.ConaryConfiguration(True) self.client = conaryclient.ConaryClient(self.cfg) def gather(self): desc = None groups = [ x for x in self.client.getUpdateItemList() if x[0].startswith('group-') and x[0].endswith('-appliance') ] if len(group): group = groups[0] desc = ConfigDescriptorCache(self.client.getDatabase()).getDescriptor(group) if desc: desc.setDisplayName('ConfigurationDescriptor') desc.addDescription('ConfigurationDescriptor') return desc def toxml(self, validate=False): desc = self.gather() if desc: return desc.toxml(validate=validate) return desc if __name__ == '__main__': import sys from conary.lib import util sys.excepthook = util.genExcepthook() descriptors = Descriptors() xml = etree.fromstring(descriptors.toxml()) print etree.tostring(xml)
Fix descriptor module to support assimilation
Fix descriptor module to support assimilation
Python
apache-2.0
sassoftware/rpath-tools,sassoftware/rpath-tools
--- +++ @@ -12,11 +12,13 @@ self.client = conaryclient.ConaryClient(self.cfg) def gather(self): - group = [ x for x in self.client.getUpdateItemList() - if x[0].startswith('group-') and - x[0].endswith('-appliance') ][0] - - desc = ConfigDescriptorCache(self.client.getDatabase()).getDescriptor(group) + desc = None + groups = [ x for x in self.client.getUpdateItemList() + if x[0].startswith('group-') and + x[0].endswith('-appliance') ] + if len(group): + group = groups[0] + desc = ConfigDescriptorCache(self.client.getDatabase()).getDescriptor(group) if desc: desc.setDisplayName('ConfigurationDescriptor') desc.addDescription('ConfigurationDescriptor')
3c218dff3e00ece3a84de727fa217d2d7d01b82d
wger/email/urls.py
wger/email/urls.py
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License from django.conf.urls import url, include from wger.email.forms import EmailListForm from wger.email.views import email_lists # sub patterns for email lists patterns_email = [ url(r'^overview/(?P<gym_pk>\d+)$', email_lists.EmailLogListView.as_view(), name='overview'), url(r'^add/(?P<gym_pk>\d+)$', email_lists.EmailListFormPreview(EmailListForm), name='add'), ] urlpatterns = [ url(r'^email/', include(patterns_email, namespace="email")), ]
# -*- coding: utf-8 -*- # This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License from django.conf.urls import url, include from wger.email.forms import EmailListForm from wger.email.views import email_lists # sub patterns for email lists patterns_email = [ url(r'^overview/gym/(?P<gym_pk>\d+)$', email_lists.EmailLogListView.as_view(), name='overview'), url(r'^add/gym/(?P<gym_pk>\d+)$', email_lists.EmailListFormPreview(EmailListForm), name='add'), ] urlpatterns = [ url(r'^email/', include(patterns_email, namespace="email")), ]
Add 'gym' prefix to URL in email app
Add 'gym' prefix to URL in email app The email app is supposed to be used in other parts of the application, not only in the gym.
Python
agpl-3.0
wger-project/wger,rolandgeider/wger,wger-project/wger,petervanderdoes/wger,DeveloperMal/wger,DeveloperMal/wger,rolandgeider/wger,kjagoo/wger_stark,petervanderdoes/wger,wger-project/wger,rolandgeider/wger,kjagoo/wger_stark,kjagoo/wger_stark,petervanderdoes/wger,DeveloperMal/wger,wger-project/wger,DeveloperMal/wger,rolandgeider/wger,petervanderdoes/wger,kjagoo/wger_stark
--- +++ @@ -22,10 +22,10 @@ # sub patterns for email lists patterns_email = [ - url(r'^overview/(?P<gym_pk>\d+)$', + url(r'^overview/gym/(?P<gym_pk>\d+)$', email_lists.EmailLogListView.as_view(), name='overview'), - url(r'^add/(?P<gym_pk>\d+)$', + url(r'^add/gym/(?P<gym_pk>\d+)$', email_lists.EmailListFormPreview(EmailListForm), name='add'), ]
853744e82f2740a47a3f36e003ea8d2784bafff6
accelerator/tests/factories/user_deferrable_modal_factory.py
accelerator/tests/factories/user_deferrable_modal_factory.py
import swapper from datetime import ( datetime, timedelta, ) from factory import SubFactory from factory.django import DjangoModelFactory from simpleuser.tests.factories.user_factory import UserFactory from .deferrable_modal_factory import DeferrableModalFactory UserDeferrableModal = swapper.load_model('accelerator', 'UserDeferrableModal') class UserDeferrableModalFactory(DjangoModelFactory): class Meta: django_get_or_create = ('deferrable_modal', 'user',) model = UserDeferrableModal user = SubFactory(UserFactory) deferrable_modal = SubFactory(DeferrableModalFactory) is_deferred = False deferred_to = datetime.now() + timedelta(days=1)
import swapper from datetime import ( datetime, timedelta, ) from factory import SubFactory from factory.django import DjangoModelFactory from pytz import utc from simpleuser.tests.factories.user_factory import UserFactory from .deferrable_modal_factory import DeferrableModalFactory UserDeferrableModal = swapper.load_model('accelerator', 'UserDeferrableModal') class UserDeferrableModalFactory(DjangoModelFactory): class Meta: django_get_or_create = ('deferrable_modal', 'user',) model = UserDeferrableModal user = SubFactory(UserFactory) deferrable_modal = SubFactory(DeferrableModalFactory) is_deferred = False deferred_to = utc.localize(datetime.now()) + timedelta(days=1)
Fix bare datetime.now() in factory
[AC-8673] Fix bare datetime.now() in factory
Python
mit
masschallenge/django-accelerator,masschallenge/django-accelerator
--- +++ @@ -6,6 +6,8 @@ ) from factory import SubFactory from factory.django import DjangoModelFactory +from pytz import utc + from simpleuser.tests.factories.user_factory import UserFactory from .deferrable_modal_factory import DeferrableModalFactory @@ -20,4 +22,4 @@ user = SubFactory(UserFactory) deferrable_modal = SubFactory(DeferrableModalFactory) is_deferred = False - deferred_to = datetime.now() + timedelta(days=1) + deferred_to = utc.localize(datetime.now()) + timedelta(days=1)
e0b7217caaf4b94c879f43f2ee95584c469687db
csrv/model/read_o8d.py
csrv/model/read_o8d.py
# Read an OCTGN deck from xml.etree import ElementTree def read_file(filename): filedata = open(filename).read() return read(filedata) def read(filedata): root = ElementTree.fromstring(filedata) identity = [] cards = [] for section in root.getchildren(): if len(section) == 1: dest = identity else: dest = cards for card in section.getchildren(): for i in range(int(card.get('qty'))): dest.append(card.text) return (identity[0], cards)
# Read an OCTGN deck from xml.etree import ElementTree def read_file(filename): filedata = open(filename).read() return read(filedata) def read(filedata): root = ElementTree.fromstring(filedata) identity = [] cards = [] for section in root.getchildren(): if len(section) == 1: dest = identity else: dest = cards for card in section.getchildren(): for i in range(int(card.get('qty'))): # Read the last 5 digits of card#id dest.append("Card{}".format(card.get('id')[-5:])) return (identity[0], cards)
Fix o8d importer to read card IDs to make the sanitized cards
Fix o8d importer to read card IDs to make the sanitized cards
Python
apache-2.0
mrroach/CentralServer,mrroach/CentralServer,mrroach/CentralServer
--- +++ @@ -16,5 +16,6 @@ dest = cards for card in section.getchildren(): for i in range(int(card.get('qty'))): - dest.append(card.text) + # Read the last 5 digits of card#id + dest.append("Card{}".format(card.get('id')[-5:])) return (identity[0], cards)
eac2211956d49d9da957492bbac1bcdc85b1e40d
openprescribing/frontend/management/commands/load_development_data.py
openprescribing/frontend/management/commands/load_development_data.py
from django.core.management import call_command from django.core.management.base import BaseCommand from frontend.tests.test_api_spending import TestAPISpendingViewsPPUTable class Command(BaseCommand): help = 'Loads sample data intended for use in local development' def handle(self, *args, **options): # For now we just piggyback off the set of test fixtures used by the # API tests fixtures = TestAPISpendingViewsPPUTable.fixtures call_command('loaddata', *fixtures)
from django.core.management import call_command from django.core.management.base import BaseCommand from frontend.models import ImportLog, PPUSaving from frontend.tests.test_api_spending import ApiTestBase, TestAPISpendingViewsPPUTable class Command(BaseCommand): help = 'Loads sample data intended for use in local development' def handle(self, *args, **options): # For now we just piggyback off the set of test fixtures used by the # API tests fixtures = TestAPISpendingViewsPPUTable.fixtures call_command('loaddata', *fixtures) ApiTestBase.setUpTestData() max_ppu_date = PPUSaving.objects.order_by('-date')[0].date ImportLog.objects.create(current_at=max_ppu_date, category='ppu')
Add extra development data so the All England page loads
Add extra development data so the All England page loads Previously the absence of the PPU ImportLog entry caused the page to throw an error.
Python
mit
ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing
--- +++ @@ -1,7 +1,8 @@ from django.core.management import call_command from django.core.management.base import BaseCommand -from frontend.tests.test_api_spending import TestAPISpendingViewsPPUTable +from frontend.models import ImportLog, PPUSaving +from frontend.tests.test_api_spending import ApiTestBase, TestAPISpendingViewsPPUTable class Command(BaseCommand): @@ -13,3 +14,6 @@ # API tests fixtures = TestAPISpendingViewsPPUTable.fixtures call_command('loaddata', *fixtures) + ApiTestBase.setUpTestData() + max_ppu_date = PPUSaving.objects.order_by('-date')[0].date + ImportLog.objects.create(current_at=max_ppu_date, category='ppu')
13c1745e73b7d3be162ce228d6c6ccf53f2438eb
syncplay/__init__.py
syncplay/__init__.py
version = '1.6.6' revision = ' beta 2' milestone = 'Yoitsu' release_number = '89' projectURL = 'https://syncplay.pl/'
version = '1.6.6' revision = '' milestone = 'Yoitsu' release_number = '90' projectURL = 'https://syncplay.pl/'
Mark build 90 as 1.6.6 final
Mark build 90 as 1.6.6 final
Python
apache-2.0
alby128/syncplay,Syncplay/syncplay,Syncplay/syncplay,alby128/syncplay
--- +++ @@ -1,5 +1,5 @@ version = '1.6.6' -revision = ' beta 2' +revision = '' milestone = 'Yoitsu' -release_number = '89' +release_number = '90' projectURL = 'https://syncplay.pl/'
fa2ecdc0bcb30415699baf4f014b390d4473d43c
photutils/psf/__init__.py
photutils/psf/__init__.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This subpackage contains tools to perform point-spread-function (PSF) photometry. """ from .epsf import * # noqa from .epsf_stars import * # noqa from .groupstars import * # noqa from .matching import * # noqa from .models import * # noqa from .photometry import * # noqa from .utils import * # noqa
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This subpackage contains tools to perform point-spread-function (PSF) photometry. """ from . import epsf from .epsf import * # noqa from . import epsf_stars from .epsf_stars import * # noqa from . import groupstars from .groupstars import * # noqa from .matching import * # noqa from . import models from .models import * # noqa from . import photometry from .photometry import * # noqa from . import utils from .utils import * # noqa __all__ = [] __all__.extend(epsf.__all__) __all__.extend(epsf_stars.__all__) __all__.extend(groupstars.__all__) __all__.extend(models.__all__) __all__.extend(photometry.__all__) __all__.extend(utils.__all__)
Fix Sphinx warnings about duplicate objects
Fix Sphinx warnings about duplicate objects
Python
bsd-3-clause
astropy/photutils,larrybradley/photutils
--- +++ @@ -4,10 +4,24 @@ photometry. """ +from . import epsf from .epsf import * # noqa +from . import epsf_stars from .epsf_stars import * # noqa +from . import groupstars from .groupstars import * # noqa from .matching import * # noqa +from . import models from .models import * # noqa +from . import photometry from .photometry import * # noqa +from . import utils from .utils import * # noqa + +__all__ = [] +__all__.extend(epsf.__all__) +__all__.extend(epsf_stars.__all__) +__all__.extend(groupstars.__all__) +__all__.extend(models.__all__) +__all__.extend(photometry.__all__) +__all__.extend(utils.__all__)
a80b1292e9c9a29921a3e42c7c60d861b4bf7965
tests/testwith.py
tests/testwith.py
import sys if sys.version_info[:2] > (2, 5): from tests._testwith import * else: from tests.support import unittest2 class TestWith(unittest2.TestCase): @unittest2.skip('tests using with statement skipped on Python 2.4') def testWith(self): pass if __name__ == '__main__': unittest2.main()
import sys if sys.version_info[:2] >= (2, 5): from tests._testwith import * else: from tests.support import unittest2 class TestWith(unittest2.TestCase): @unittest2.skip('tests using with statement skipped on Python 2.4') def testWith(self): pass if __name__ == '__main__': unittest2.main()
Enable with statement tests for Python 2.5
Enable with statement tests for Python 2.5
Python
bsd-2-clause
frankier/mock,dannybtran/mock,testing-cabal/mock,sorenh/mock,scorphus/mock,nett55/mock,rbtcollins/mock,fladi/mock,OddBloke/mock,derwiki-adroll/mock,kostyll/mock,pypingou/mock,lord63-forks/mock,johndeng/mock
--- +++ @@ -1,6 +1,6 @@ import sys -if sys.version_info[:2] > (2, 5): +if sys.version_info[:2] >= (2, 5): from tests._testwith import * else: from tests.support import unittest2
6055b7eb6b34ed22eb3c7cd17a975d4728be1360
msmbuilder/tests/test_sampling.py
msmbuilder/tests/test_sampling.py
import numpy as np from msmbuilder.decomposition import tICA from msmbuilder.io.sampling import sample_dimension def test_sample_dimension(): np.random.seed(42) X = np.random.randn(500, 5) data = [X, X, X] tica = tICA(n_components=2, lag_time=1).fit(data) tica_trajs = {k: tica.partial_transform(v) for k, v in enumerate(data)} res = sample_dimension(tica_trajs, 0, 10, scheme="linear") res2 = sample_dimension(tica_trajs, 1, 10, scheme="linear") assert len(res) == len(res2) == 10
import numpy as np from msmbuilder.decomposition import tICA from msmbuilder.io.sampling import sample_dimension def test_sample_dimension(): np.random.seed(42) X = np.random.randn(500, 5) data = [X, X, X] tica = tICA(n_components=2, lag_time=1).fit(data) tica_trajs = {k: tica.partial_transform(v) for k, v in enumerate(data)} res = sample_dimension(tica_trajs, 0, 10, scheme="linear") res2 = sample_dimension(tica_trajs, 1, 10, scheme="linear") assert len(res) == len(res2) == 10 def test_sample_dimension_2(): np.random.seed(42) X = np.random.randn(500, 5) data = [X, X, X] tica = tICA(n_components=2, lag_time=1).fit(data) tica_trajs = {k: tica.partial_transform(v) for k, v in enumerate(data)} res = sample_dimension(tica_trajs, 0, 10, scheme="random") res2 = sample_dimension(tica_trajs, 1, 10, scheme="edge") assert len(res) == len(res2) == 10
Add test for new edge sampling
Add test for new edge sampling I think it would've failed before
Python
lgpl-2.1
Eigenstate/msmbuilder,Eigenstate/msmbuilder,msmbuilder/msmbuilder,msmbuilder/msmbuilder,Eigenstate/msmbuilder,brookehus/msmbuilder,brookehus/msmbuilder,brookehus/msmbuilder,brookehus/msmbuilder,Eigenstate/msmbuilder,msmbuilder/msmbuilder,msmbuilder/msmbuilder,brookehus/msmbuilder,msmbuilder/msmbuilder,Eigenstate/msmbuilder
--- +++ @@ -15,3 +15,15 @@ res2 = sample_dimension(tica_trajs, 1, 10, scheme="linear") assert len(res) == len(res2) == 10 + +def test_sample_dimension_2(): + np.random.seed(42) + X = np.random.randn(500, 5) + data = [X, X, X] + + tica = tICA(n_components=2, lag_time=1).fit(data) + tica_trajs = {k: tica.partial_transform(v) for k, v in enumerate(data)} + res = sample_dimension(tica_trajs, 0, 10, scheme="random") + res2 = sample_dimension(tica_trajs, 1, 10, scheme="edge") + + assert len(res) == len(res2) == 10
cebd4f1ee9a87cc2652ebf8981df20121ec257b2
steel/fields/numbers.py
steel/fields/numbers.py
import struct from steel.fields import Field __all__ = ['Integer'] class Integer(Field): "An integer represented as a sequence and bytes" # These map a number of bytes to a struct format code size_formats = { 1: 'B', # char 2: 'H', # short 4: 'L', # long 8: 'Q', # long long } def __init__(self, *args, endianness='<', **kwargs): super(Integer, self).__init__(*args, **kwargs) self.format_code = endianness + self.size_formats[self.size] def encode(self, value): return struct.pack(self.format_code, value) def decode(self, value): # The index on the end is because unpack always returns a tuple return struct.unpack(self.format_code, value)[0]
import struct from steel.fields import Field __all__ = ['Integer'] class Integer(Field): "An integer represented as a sequence and bytes" # These map a number of bytes to a struct format code size_formats = { 1: 'B', # char 2: 'H', # short 4: 'L', # long 8: 'Q', # long long } def __init__(self, *args, endianness='<', **kwargs): super(Integer, self).__init__(*args, **kwargs) self.format_code = endianness + self.size_formats[self.size] def encode(self, value): try: return struct.pack(self.format_code, value) except struct.error as e: raise ValueError(*e.args) def decode(self, value): # The index on the end is because unpack always returns a tuple try: return struct.unpack(self.format_code, value)[0] except struct.error as e: raise ValueError(*e.args)
Raise ValueError instead of struct.error
Raise ValueError instead of struct.error The protocol for field encoding and decoding is to raise ValueError, so this is a necessary translation.
Python
bsd-3-clause
gulopine/steel-experiment
--- +++ @@ -20,8 +20,14 @@ self.format_code = endianness + self.size_formats[self.size] def encode(self, value): - return struct.pack(self.format_code, value) + try: + return struct.pack(self.format_code, value) + except struct.error as e: + raise ValueError(*e.args) def decode(self, value): # The index on the end is because unpack always returns a tuple - return struct.unpack(self.format_code, value)[0] + try: + return struct.unpack(self.format_code, value)[0] + except struct.error as e: + raise ValueError(*e.args)
32f99cd7a9f20e2c8d7ebd140c23ac0e43b1284c
pulldb/users.py
pulldb/users.py
# Copyright 2013 Russell Heilling import logging from google.appengine.api import users from pulldb import base from pulldb import session from pulldb.models.users import User class Profile(session.SessionHandler): def get(self): app_user = users.get_current_user() template_values = self.base_template_values() template_values.update({ 'user': user_key(app_user).get(), }) template = self.templates.get_template('users_profile.html') self.response.write(template.render(template_values)) def user_key(app_user=users.get_current_user(), create=True): key = None user = User.query(User.userid == app_user.user_id()).get() if user: key = user.key elif create: logging.info('Adding user to datastore: %s', app_user.nickname()) user = User(userid=app_user.user_id(), nickname=app_user.nickname()) user.put() key = user.key return user.key app = base.create_app([ ('/users/me', Profile), ])
# Copyright 2013 Russell Heilling import logging from google.appengine.api import users from pulldb import base from pulldb import session from pulldb.models.users import User class Profile(session.SessionHandler): def get(self): app_user = users.get_current_user() template_values = self.base_template_values() template_values.update({ 'user': user_key(app_user).get(), }) template = self.templates.get_template('users_profile.html') self.response.write(template.render(template_values)) def user_key(app_user=users.get_current_user(), create=True): logging.debug("Looking up user key for: %r", app_user) key = None user = User.query(User.userid == app_user.user_id()).get() if user: key = user.key elif create: logging.info('Adding user to datastore: %s', app_user.nickname()) user = User(userid=app_user.user_id(), nickname=app_user.nickname()) user.put() key = user.key return user.key app = base.create_app([ ('/users/me', Profile), ])
Add logging to track down a bug
Add logging to track down a bug
Python
mit
xchewtoyx/pulldb
--- +++ @@ -18,6 +18,7 @@ self.response.write(template.render(template_values)) def user_key(app_user=users.get_current_user(), create=True): + logging.debug("Looking up user key for: %r", app_user) key = None user = User.query(User.userid == app_user.user_id()).get() if user: