commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 0
2.94k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
444
| message
stringlengths 16
3.45k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43.2k
| prompt
stringlengths 17
4.58k
| response
stringlengths 1
4.43k
| prompt_tagged
stringlengths 58
4.62k
| response_tagged
stringlengths 1
4.43k
| text
stringlengths 132
7.29k
| text_tagged
stringlengths 173
7.33k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f1d05060356f0bb31cc418c1d4abca9438c39d86
|
km3pipe/tests/test_srv.py
|
km3pipe/tests/test_srv.py
|
# Filename: test_srv.py
# pylint: disable=locally-disabled,C0111,R0904,C0103
from km3pipe.testing import TestCase, patch
from km3pipe.dataclasses import Table
from km3pipe.srv import srv_event
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestSrvEvent(TestCase):
@patch('km3pipe.srv.srv_data')
def test_call(self, srv_data_mock):
hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6],
'time': [100, 200], 'tot': [11, 22]})
srv_event('token', hits)
srv_data_mock.assert_called_once()
|
# Filename: test_srv.py
# pylint: disable=locally-disabled,C0111,R0904,C0103
from km3pipe.testing import TestCase, patch
from km3pipe.dataclasses import Table
from km3pipe.srv import srv_event
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestSrvEvent(TestCase):
@patch('km3pipe.srv.srv_data')
def test_call(self, srv_data_mock):
hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6],
'time': [100, 200], 'tot': [11, 22]})
srv_event('token', hits, 'rba_url')
srv_data_mock.assert_called_once()
|
Add rba url, since it's normally taken from the config
|
Add rba url, since it's normally taken from the config
|
Python
|
mit
|
tamasgal/km3pipe,tamasgal/km3pipe
|
# Filename: test_srv.py
# pylint: disable=locally-disabled,C0111,R0904,C0103
from km3pipe.testing import TestCase, patch
from km3pipe.dataclasses import Table
from km3pipe.srv import srv_event
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestSrvEvent(TestCase):
@patch('km3pipe.srv.srv_data')
def test_call(self, srv_data_mock):
hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6],
'time': [100, 200], 'tot': [11, 22]})
srv_event('token', hits)
srv_data_mock.assert_called_once()
Add rba url, since it's normally taken from the config
|
# Filename: test_srv.py
# pylint: disable=locally-disabled,C0111,R0904,C0103
from km3pipe.testing import TestCase, patch
from km3pipe.dataclasses import Table
from km3pipe.srv import srv_event
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestSrvEvent(TestCase):
@patch('km3pipe.srv.srv_data')
def test_call(self, srv_data_mock):
hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6],
'time': [100, 200], 'tot': [11, 22]})
srv_event('token', hits, 'rba_url')
srv_data_mock.assert_called_once()
|
<commit_before># Filename: test_srv.py
# pylint: disable=locally-disabled,C0111,R0904,C0103
from km3pipe.testing import TestCase, patch
from km3pipe.dataclasses import Table
from km3pipe.srv import srv_event
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestSrvEvent(TestCase):
@patch('km3pipe.srv.srv_data')
def test_call(self, srv_data_mock):
hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6],
'time': [100, 200], 'tot': [11, 22]})
srv_event('token', hits)
srv_data_mock.assert_called_once()
<commit_msg>Add rba url, since it's normally taken from the config<commit_after>
|
# Filename: test_srv.py
# pylint: disable=locally-disabled,C0111,R0904,C0103
from km3pipe.testing import TestCase, patch
from km3pipe.dataclasses import Table
from km3pipe.srv import srv_event
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestSrvEvent(TestCase):
@patch('km3pipe.srv.srv_data')
def test_call(self, srv_data_mock):
hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6],
'time': [100, 200], 'tot': [11, 22]})
srv_event('token', hits, 'rba_url')
srv_data_mock.assert_called_once()
|
# Filename: test_srv.py
# pylint: disable=locally-disabled,C0111,R0904,C0103
from km3pipe.testing import TestCase, patch
from km3pipe.dataclasses import Table
from km3pipe.srv import srv_event
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestSrvEvent(TestCase):
@patch('km3pipe.srv.srv_data')
def test_call(self, srv_data_mock):
hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6],
'time': [100, 200], 'tot': [11, 22]})
srv_event('token', hits)
srv_data_mock.assert_called_once()
Add rba url, since it's normally taken from the config# Filename: test_srv.py
# pylint: disable=locally-disabled,C0111,R0904,C0103
from km3pipe.testing import TestCase, patch
from km3pipe.dataclasses import Table
from km3pipe.srv import srv_event
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestSrvEvent(TestCase):
@patch('km3pipe.srv.srv_data')
def test_call(self, srv_data_mock):
hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6],
'time': [100, 200], 'tot': [11, 22]})
srv_event('token', hits, 'rba_url')
srv_data_mock.assert_called_once()
|
<commit_before># Filename: test_srv.py
# pylint: disable=locally-disabled,C0111,R0904,C0103
from km3pipe.testing import TestCase, patch
from km3pipe.dataclasses import Table
from km3pipe.srv import srv_event
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestSrvEvent(TestCase):
@patch('km3pipe.srv.srv_data')
def test_call(self, srv_data_mock):
hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6],
'time': [100, 200], 'tot': [11, 22]})
srv_event('token', hits)
srv_data_mock.assert_called_once()
<commit_msg>Add rba url, since it's normally taken from the config<commit_after># Filename: test_srv.py
# pylint: disable=locally-disabled,C0111,R0904,C0103
from km3pipe.testing import TestCase, patch
from km3pipe.dataclasses import Table
from km3pipe.srv import srv_event
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestSrvEvent(TestCase):
@patch('km3pipe.srv.srv_data')
def test_call(self, srv_data_mock):
hits = Table({'pos_x': [1, 2], 'pos_y': [3, 4], 'pos_z': [5, 6],
'time': [100, 200], 'tot': [11, 22]})
srv_event('token', hits, 'rba_url')
srv_data_mock.assert_called_once()
|
587ef854d97f1098a4eda9fbc959ce6698297260
|
simpleflow/swf/utils.py
|
simpleflow/swf/utils.py
|
from __future__ import absolute_import
import swf.models
import swf.querysets
from simpleflow.history import History
def get_workflow_history(domain_name, workflow_id, run_id):
domain = swf.models.Domain(domain_name)
workflow_execution = (
swf.querysets.WorkflowExecutionQuerySet(domain).get(
workflow_id=workflow_id,
run_id=run_id,
)
)
return History(workflow_execution.history())
|
from __future__ import absolute_import
import swf.models
import swf.querysets
from simpleflow.history import History
# TODO: move this function inside a QuerySet object when we merge the
# "simpleflow" and "swf" namespaces
def get_workflow_history(domain_name, workflow_id, run_id=None):
domain = swf.models.Domain(domain_name)
# if no run_id provided, we assume that the requester wanted the last
# execution with that workflow_id
if not run_id:
found_run_id = None
qs = swf.querysets.WorkflowExecutionQuerySet(domain)
wfe = qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_OPEN) or \
qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_CLOSED)
if wfe:
# by default, workflow executions are returned in descending start time order
# so the first returned is the last that has run
found_run_id = wfe[0].run_id
workflow_execution = (
swf.querysets.WorkflowExecutionQuerySet(domain).get(
workflow_id=workflow_id,
run_id=run_id or found_run_id,
)
)
return History(workflow_execution.history())
|
Improve get_workflow_history so it returns the last execution if no run_id given
|
Improve get_workflow_history so it returns the last execution if no run_id given
This helper method didn't seem to be used directly in simpleflow
codebase but it's actually useful. For a nicer usage in the "--repair"
feature we will introduce, we need to retrieve the latest execution for
a given "workflow ID", without knowing the "run ID" in advance.
|
Python
|
mit
|
botify-labs/simpleflow,botify-labs/simpleflow
|
from __future__ import absolute_import
import swf.models
import swf.querysets
from simpleflow.history import History
def get_workflow_history(domain_name, workflow_id, run_id):
domain = swf.models.Domain(domain_name)
workflow_execution = (
swf.querysets.WorkflowExecutionQuerySet(domain).get(
workflow_id=workflow_id,
run_id=run_id,
)
)
return History(workflow_execution.history())
Improve get_workflow_history so it returns the last execution if no run_id given
This helper method didn't seem to be used directly in simpleflow
codebase but it's actually useful. For a nicer usage in the "--repair"
feature we will introduce, we need to retrieve the latest execution for
a given "workflow ID", without knowing the "run ID" in advance.
|
from __future__ import absolute_import
import swf.models
import swf.querysets
from simpleflow.history import History
# TODO: move this function inside a QuerySet object when we merge the
# "simpleflow" and "swf" namespaces
def get_workflow_history(domain_name, workflow_id, run_id=None):
domain = swf.models.Domain(domain_name)
# if no run_id provided, we assume that the requester wanted the last
# execution with that workflow_id
if not run_id:
found_run_id = None
qs = swf.querysets.WorkflowExecutionQuerySet(domain)
wfe = qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_OPEN) or \
qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_CLOSED)
if wfe:
# by default, workflow executions are returned in descending start time order
# so the first returned is the last that has run
found_run_id = wfe[0].run_id
workflow_execution = (
swf.querysets.WorkflowExecutionQuerySet(domain).get(
workflow_id=workflow_id,
run_id=run_id or found_run_id,
)
)
return History(workflow_execution.history())
|
<commit_before>from __future__ import absolute_import
import swf.models
import swf.querysets
from simpleflow.history import History
def get_workflow_history(domain_name, workflow_id, run_id):
domain = swf.models.Domain(domain_name)
workflow_execution = (
swf.querysets.WorkflowExecutionQuerySet(domain).get(
workflow_id=workflow_id,
run_id=run_id,
)
)
return History(workflow_execution.history())
<commit_msg>Improve get_workflow_history so it returns the last execution if no run_id given
This helper method didn't seem to be used directly in simpleflow
codebase but it's actually useful. For a nicer usage in the "--repair"
feature we will introduce, we need to retrieve the latest execution for
a given "workflow ID", without knowing the "run ID" in advance.<commit_after>
|
from __future__ import absolute_import
import swf.models
import swf.querysets
from simpleflow.history import History
# TODO: move this function inside a QuerySet object when we merge the
# "simpleflow" and "swf" namespaces
def get_workflow_history(domain_name, workflow_id, run_id=None):
domain = swf.models.Domain(domain_name)
# if no run_id provided, we assume that the requester wanted the last
# execution with that workflow_id
if not run_id:
found_run_id = None
qs = swf.querysets.WorkflowExecutionQuerySet(domain)
wfe = qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_OPEN) or \
qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_CLOSED)
if wfe:
# by default, workflow executions are returned in descending start time order
# so the first returned is the last that has run
found_run_id = wfe[0].run_id
workflow_execution = (
swf.querysets.WorkflowExecutionQuerySet(domain).get(
workflow_id=workflow_id,
run_id=run_id or found_run_id,
)
)
return History(workflow_execution.history())
|
from __future__ import absolute_import
import swf.models
import swf.querysets
from simpleflow.history import History
def get_workflow_history(domain_name, workflow_id, run_id):
domain = swf.models.Domain(domain_name)
workflow_execution = (
swf.querysets.WorkflowExecutionQuerySet(domain).get(
workflow_id=workflow_id,
run_id=run_id,
)
)
return History(workflow_execution.history())
Improve get_workflow_history so it returns the last execution if no run_id given
This helper method didn't seem to be used directly in simpleflow
codebase but it's actually useful. For a nicer usage in the "--repair"
feature we will introduce, we need to retrieve the latest execution for
a given "workflow ID", without knowing the "run ID" in advance.from __future__ import absolute_import
import swf.models
import swf.querysets
from simpleflow.history import History
# TODO: move this function inside a QuerySet object when we merge the
# "simpleflow" and "swf" namespaces
def get_workflow_history(domain_name, workflow_id, run_id=None):
domain = swf.models.Domain(domain_name)
# if no run_id provided, we assume that the requester wanted the last
# execution with that workflow_id
if not run_id:
found_run_id = None
qs = swf.querysets.WorkflowExecutionQuerySet(domain)
wfe = qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_OPEN) or \
qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_CLOSED)
if wfe:
# by default, workflow executions are returned in descending start time order
# so the first returned is the last that has run
found_run_id = wfe[0].run_id
workflow_execution = (
swf.querysets.WorkflowExecutionQuerySet(domain).get(
workflow_id=workflow_id,
run_id=run_id or found_run_id,
)
)
return History(workflow_execution.history())
|
<commit_before>from __future__ import absolute_import
import swf.models
import swf.querysets
from simpleflow.history import History
def get_workflow_history(domain_name, workflow_id, run_id):
domain = swf.models.Domain(domain_name)
workflow_execution = (
swf.querysets.WorkflowExecutionQuerySet(domain).get(
workflow_id=workflow_id,
run_id=run_id,
)
)
return History(workflow_execution.history())
<commit_msg>Improve get_workflow_history so it returns the last execution if no run_id given
This helper method didn't seem to be used directly in simpleflow
codebase but it's actually useful. For a nicer usage in the "--repair"
feature we will introduce, we need to retrieve the latest execution for
a given "workflow ID", without knowing the "run ID" in advance.<commit_after>from __future__ import absolute_import
import swf.models
import swf.querysets
from simpleflow.history import History
# TODO: move this function inside a QuerySet object when we merge the
# "simpleflow" and "swf" namespaces
def get_workflow_history(domain_name, workflow_id, run_id=None):
domain = swf.models.Domain(domain_name)
# if no run_id provided, we assume that the requester wanted the last
# execution with that workflow_id
if not run_id:
found_run_id = None
qs = swf.querysets.WorkflowExecutionQuerySet(domain)
wfe = qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_OPEN) or \
qs.filter(workflow_id=workflow_id, status=swf.models.WorkflowExecution.STATUS_CLOSED)
if wfe:
# by default, workflow executions are returned in descending start time order
# so the first returned is the last that has run
found_run_id = wfe[0].run_id
workflow_execution = (
swf.querysets.WorkflowExecutionQuerySet(domain).get(
workflow_id=workflow_id,
run_id=run_id or found_run_id,
)
)
return History(workflow_execution.history())
|
b844b5ea9f7df47a9c000699b6b2636fa16a20cd
|
lfc/context_processors.py
|
lfc/context_processors.py
|
# lfc imports
import lfc.utils
from django.conf import settings
from django.utils import translation
def main(request):
"""context processor for LFC.
"""
current_language = translation.get_language()
default_language = settings.LANGUAGE_CODE
return {
"PORTAL" : lfc.utils.get_portal(),
"LFC_MULTILANGUAGE" : settings.LFC_MULTILANGUAGE,
"DEFAULT_LANGUAGE" : default_language,
"CURRENT_LANGUAGE" : current_language,
"IS_DEFAULT_LANGUAGE" : default_language == current_language,
}
|
# lfc imports
import lfc.utils
from django.conf import settings
from django.utils import translation
def main(request):
"""context processor for LFC.
"""
current_language = translation.get_language()
default_language = settings.LANGUAGE_CODE
is_default_language = default_language == current_language
if current_language == "0" or is_default_language:
link_language = ""
else:
link_language = current_language
return {
"PORTAL" : lfc.utils.get_portal(),
"LFC_MULTILANGUAGE" : settings.LFC_MULTILANGUAGE,
"DEFAULT_LANGUAGE" : default_language,
"CURRENT_LANGUAGE" : current_language,
"IS_DEFAULT_LANGUAGE" : is_default_language,
"LINK_LANGUAGE" : link_language,
}
|
Return correct language for using within links
|
Improvement: Return correct language for using within links
|
Python
|
bsd-3-clause
|
diefenbach/django-lfc,diefenbach/django-lfc,diefenbach/django-lfc
|
# lfc imports
import lfc.utils
from django.conf import settings
from django.utils import translation
def main(request):
"""context processor for LFC.
"""
current_language = translation.get_language()
default_language = settings.LANGUAGE_CODE
return {
"PORTAL" : lfc.utils.get_portal(),
"LFC_MULTILANGUAGE" : settings.LFC_MULTILANGUAGE,
"DEFAULT_LANGUAGE" : default_language,
"CURRENT_LANGUAGE" : current_language,
"IS_DEFAULT_LANGUAGE" : default_language == current_language,
}
Improvement: Return correct language for using within links
|
# lfc imports
import lfc.utils
from django.conf import settings
from django.utils import translation
def main(request):
"""context processor for LFC.
"""
current_language = translation.get_language()
default_language = settings.LANGUAGE_CODE
is_default_language = default_language == current_language
if current_language == "0" or is_default_language:
link_language = ""
else:
link_language = current_language
return {
"PORTAL" : lfc.utils.get_portal(),
"LFC_MULTILANGUAGE" : settings.LFC_MULTILANGUAGE,
"DEFAULT_LANGUAGE" : default_language,
"CURRENT_LANGUAGE" : current_language,
"IS_DEFAULT_LANGUAGE" : is_default_language,
"LINK_LANGUAGE" : link_language,
}
|
<commit_before># lfc imports
import lfc.utils
from django.conf import settings
from django.utils import translation
def main(request):
"""context processor for LFC.
"""
current_language = translation.get_language()
default_language = settings.LANGUAGE_CODE
return {
"PORTAL" : lfc.utils.get_portal(),
"LFC_MULTILANGUAGE" : settings.LFC_MULTILANGUAGE,
"DEFAULT_LANGUAGE" : default_language,
"CURRENT_LANGUAGE" : current_language,
"IS_DEFAULT_LANGUAGE" : default_language == current_language,
}
<commit_msg>Improvement: Return correct language for using within links<commit_after>
|
# lfc imports
import lfc.utils
from django.conf import settings
from django.utils import translation
def main(request):
"""context processor for LFC.
"""
current_language = translation.get_language()
default_language = settings.LANGUAGE_CODE
is_default_language = default_language == current_language
if current_language == "0" or is_default_language:
link_language = ""
else:
link_language = current_language
return {
"PORTAL" : lfc.utils.get_portal(),
"LFC_MULTILANGUAGE" : settings.LFC_MULTILANGUAGE,
"DEFAULT_LANGUAGE" : default_language,
"CURRENT_LANGUAGE" : current_language,
"IS_DEFAULT_LANGUAGE" : is_default_language,
"LINK_LANGUAGE" : link_language,
}
|
# lfc imports
import lfc.utils
from django.conf import settings
from django.utils import translation
def main(request):
"""context processor for LFC.
"""
current_language = translation.get_language()
default_language = settings.LANGUAGE_CODE
return {
"PORTAL" : lfc.utils.get_portal(),
"LFC_MULTILANGUAGE" : settings.LFC_MULTILANGUAGE,
"DEFAULT_LANGUAGE" : default_language,
"CURRENT_LANGUAGE" : current_language,
"IS_DEFAULT_LANGUAGE" : default_language == current_language,
}
Improvement: Return correct language for using within links# lfc imports
import lfc.utils
from django.conf import settings
from django.utils import translation
def main(request):
"""context processor for LFC.
"""
current_language = translation.get_language()
default_language = settings.LANGUAGE_CODE
is_default_language = default_language == current_language
if current_language == "0" or is_default_language:
link_language = ""
else:
link_language = current_language
return {
"PORTAL" : lfc.utils.get_portal(),
"LFC_MULTILANGUAGE" : settings.LFC_MULTILANGUAGE,
"DEFAULT_LANGUAGE" : default_language,
"CURRENT_LANGUAGE" : current_language,
"IS_DEFAULT_LANGUAGE" : is_default_language,
"LINK_LANGUAGE" : link_language,
}
|
<commit_before># lfc imports
import lfc.utils
from django.conf import settings
from django.utils import translation
def main(request):
"""context processor for LFC.
"""
current_language = translation.get_language()
default_language = settings.LANGUAGE_CODE
return {
"PORTAL" : lfc.utils.get_portal(),
"LFC_MULTILANGUAGE" : settings.LFC_MULTILANGUAGE,
"DEFAULT_LANGUAGE" : default_language,
"CURRENT_LANGUAGE" : current_language,
"IS_DEFAULT_LANGUAGE" : default_language == current_language,
}
<commit_msg>Improvement: Return correct language for using within links<commit_after># lfc imports
import lfc.utils
from django.conf import settings
from django.utils import translation
def main(request):
"""context processor for LFC.
"""
current_language = translation.get_language()
default_language = settings.LANGUAGE_CODE
is_default_language = default_language == current_language
if current_language == "0" or is_default_language:
link_language = ""
else:
link_language = current_language
return {
"PORTAL" : lfc.utils.get_portal(),
"LFC_MULTILANGUAGE" : settings.LFC_MULTILANGUAGE,
"DEFAULT_LANGUAGE" : default_language,
"CURRENT_LANGUAGE" : current_language,
"IS_DEFAULT_LANGUAGE" : is_default_language,
"LINK_LANGUAGE" : link_language,
}
|
435fce76241d41eaffaf63bbd948eb306806d8f0
|
microdash/settings/production.py
|
microdash/settings/production.py
|
import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
|
import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
TWITTER_KEY = env('TWITTER_KEY')
TWITTER_SECRET = env('TWITTER_KEY')
|
Read settings from the environment.
|
Read settings from the environment.
|
Python
|
bsd-3-clause
|
alfredo/microdash,alfredo/microdash
|
import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
Read settings from the environment.
|
import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
TWITTER_KEY = env('TWITTER_KEY')
TWITTER_SECRET = env('TWITTER_KEY')
|
<commit_before>import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
<commit_msg>Read settings from the environment.<commit_after>
|
import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
TWITTER_KEY = env('TWITTER_KEY')
TWITTER_SECRET = env('TWITTER_KEY')
|
import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
Read settings from the environment.import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
TWITTER_KEY = env('TWITTER_KEY')
TWITTER_SECRET = env('TWITTER_KEY')
|
<commit_before>import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
<commit_msg>Read settings from the environment.<commit_after>import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
TWITTER_KEY = env('TWITTER_KEY')
TWITTER_SECRET = env('TWITTER_KEY')
|
9909fe549753d13355552c7462f16c42908d4b21
|
ligand/urls.py
|
ligand/urls.py
|
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
from ligand.views import *
urlpatterns = [
url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'),
url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'),
url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets$',TargetDetails, name='ligand_target_detail'),
url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'),
url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'),
url(r'^statistics', LigandStatistics.as_view(), name='ligand_statistics')
]
|
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
from ligand.views import *
urlpatterns = [
url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'),
url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'),
url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets$',TargetDetails, name='ligand_target_detail'),
url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'),
url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'),
url(r'^statistics', cache_page(3600*24*7)(LigandStatistics.as_view()), name='ligand_statistics')
]
|
Add caching to ligand statistics
|
Add caching to ligand statistics
|
Python
|
apache-2.0
|
cmunk/protwis,protwis/protwis,cmunk/protwis,cmunk/protwis,protwis/protwis,cmunk/protwis,protwis/protwis
|
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
from ligand.views import *
urlpatterns = [
url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'),
url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'),
url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets$',TargetDetails, name='ligand_target_detail'),
url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'),
url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'),
url(r'^statistics', LigandStatistics.as_view(), name='ligand_statistics')
]
Add caching to ligand statistics
|
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
from ligand.views import *
urlpatterns = [
url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'),
url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'),
url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets$',TargetDetails, name='ligand_target_detail'),
url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'),
url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'),
url(r'^statistics', cache_page(3600*24*7)(LigandStatistics.as_view()), name='ligand_statistics')
]
|
<commit_before>from django.conf.urls import url
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
from ligand.views import *
urlpatterns = [
url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'),
url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'),
url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets$',TargetDetails, name='ligand_target_detail'),
url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'),
url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'),
url(r'^statistics', LigandStatistics.as_view(), name='ligand_statistics')
]
<commit_msg>Add caching to ligand statistics<commit_after>
|
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
from ligand.views import *
urlpatterns = [
url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'),
url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'),
url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets$',TargetDetails, name='ligand_target_detail'),
url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'),
url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'),
url(r'^statistics', cache_page(3600*24*7)(LigandStatistics.as_view()), name='ligand_statistics')
]
|
from django.conf.urls import url
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
from ligand.views import *
urlpatterns = [
url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'),
url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'),
url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets$',TargetDetails, name='ligand_target_detail'),
url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'),
url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'),
url(r'^statistics', LigandStatistics.as_view(), name='ligand_statistics')
]
Add caching to ligand statisticsfrom django.conf.urls import url
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
from ligand.views import *
urlpatterns = [
url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'),
url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'),
url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets$',TargetDetails, name='ligand_target_detail'),
url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'),
url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'),
url(r'^statistics', cache_page(3600*24*7)(LigandStatistics.as_view()), name='ligand_statistics')
]
|
<commit_before>from django.conf.urls import url
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
from ligand.views import *
urlpatterns = [
url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'),
url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'),
url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets$',TargetDetails, name='ligand_target_detail'),
url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'),
url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'),
url(r'^statistics', LigandStatistics.as_view(), name='ligand_statistics')
]
<commit_msg>Add caching to ligand statistics<commit_after>from django.conf.urls import url
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
from ligand.views import *
urlpatterns = [
url(r'^$', cache_page(3600*24*7)(LigandBrowser.as_view()), name='ligand_browser'),
url(r'^target/all/(?P<slug>[-\w]+)/$',TargetDetails, name='ligand_target_detail'),
url(r'^target/compact/(?P<slug>[-\w]+)/$',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets$',TargetDetails, name='ligand_target_detail'),
url(r'^targets_compact',TargetDetailsCompact, name='ligand_target_detail_compact'),
url(r'^targets_purchasable',TargetPurchasabilityDetails, name='ligand_target_detail_purchasable'),
url(r'^(?P<ligand_id>[-\w]+)/$',LigandDetails, name='ligand_detail'),
url(r'^statistics', cache_page(3600*24*7)(LigandStatistics.as_view()), name='ligand_statistics')
]
|
281208f9ecfa3f5f5028df75fff86f1cdb752487
|
jasylibrary.py
|
jasylibrary.py
|
#import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
@share
def build(regenerate = False):
""" Build static website """
konstrukteur.Konstrukteur.build(regenerate)
|
#import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profile, regenerate = False):
""" Build static website """
def getPartUrl(part, type):
folder = ""
if type == "css":
folder = profile.getCssFolder()
outputPath = folder #os.path.join(profile.getDestinationPath(), folder)
filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type))
return filename
session.addCommand("part.url", getPartUrl, "url")
for permutation in profile.permutate():
konstrukteur.Konstrukteur.build(regenerate, profile)
|
Add support for part loading
|
Add support for part loading
|
Python
|
mit
|
fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur
|
#import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
@share
def build(regenerate = False):
""" Build static website """
konstrukteur.Konstrukteur.build(regenerate)
Add support for part loading
|
#import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profile, regenerate = False):
""" Build static website """
def getPartUrl(part, type):
folder = ""
if type == "css":
folder = profile.getCssFolder()
outputPath = folder #os.path.join(profile.getDestinationPath(), folder)
filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type))
return filename
session.addCommand("part.url", getPartUrl, "url")
for permutation in profile.permutate():
konstrukteur.Konstrukteur.build(regenerate, profile)
|
<commit_before>#import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
@share
def build(regenerate = False):
""" Build static website """
konstrukteur.Konstrukteur.build(regenerate)
<commit_msg>Add support for part loading<commit_after>
|
#import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profile, regenerate = False):
""" Build static website """
def getPartUrl(part, type):
folder = ""
if type == "css":
folder = profile.getCssFolder()
outputPath = folder #os.path.join(profile.getDestinationPath(), folder)
filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type))
return filename
session.addCommand("part.url", getPartUrl, "url")
for permutation in profile.permutate():
konstrukteur.Konstrukteur.build(regenerate, profile)
|
#import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
@share
def build(regenerate = False):
""" Build static website """
konstrukteur.Konstrukteur.build(regenerate)
Add support for part loading#import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profile, regenerate = False):
""" Build static website """
def getPartUrl(part, type):
folder = ""
if type == "css":
folder = profile.getCssFolder()
outputPath = folder #os.path.join(profile.getDestinationPath(), folder)
filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type))
return filename
session.addCommand("part.url", getPartUrl, "url")
for permutation in profile.permutate():
konstrukteur.Konstrukteur.build(regenerate, profile)
|
<commit_before>#import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
@share
def build(regenerate = False):
""" Build static website """
konstrukteur.Konstrukteur.build(regenerate)
<commit_msg>Add support for part loading<commit_after>#import os, json
#from jasy.core.Util import executeCommand
#import jasy.core.Console as Console
#import urllib.parse
# Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profile, regenerate = False):
""" Build static website """
def getPartUrl(part, type):
folder = ""
if type == "css":
folder = profile.getCssFolder()
outputPath = folder #os.path.join(profile.getDestinationPath(), folder)
filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type))
return filename
session.addCommand("part.url", getPartUrl, "url")
for permutation in profile.permutate():
konstrukteur.Konstrukteur.build(regenerate, profile)
|
b4ce232f050de073572f64c04b170a2e790fdc24
|
nefertari_mongodb/serializers.py
|
nefertari_mongodb/serializers.py
|
import logging
import datetime
import decimal
import elasticsearch
from bson import ObjectId, DBRef
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoder(_JSONEncoder):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, decimal.Decimal):
return float(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if hasattr(obj, 'to_dict'):
# If it got to this point, it means its a nested object.
# outter objects would have been handled with DataProxy.
return obj.to_dict(__nested=True)
return super(JSONEncoder, self).default(obj)
class ESJSONSerializer(elasticsearch.serializer.JSONSerializer):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if isinstance(obj, decimal.Decimal):
return float(obj)
try:
return super(ESJSONSerializer, self).default(obj)
except:
import traceback
log.error(traceback.format_exc())
|
import logging
import datetime
import decimal
import elasticsearch
from bson import ObjectId, DBRef
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoderMixin(object):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if isinstance(obj, decimal.Decimal):
return float(obj)
return super(JSONEncoderMixin, self).default(obj)
class JSONEncoder(JSONEncoderMixin, _JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_dict'):
# If it got to this point, it means its a nested object.
# outter objects would have been handled with DataProxy.
return obj.to_dict(__nested=True)
return super(JSONEncoder, self).default(obj)
class ESJSONSerializer(JSONEncoderMixin,
elasticsearch.serializer.JSONSerializer):
def default(self, obj):
try:
return super(ESJSONSerializer, self).default(obj)
except:
import traceback
log.error(traceback.format_exc())
|
Refactor encoders to have base class
|
Refactor encoders to have base class
|
Python
|
apache-2.0
|
brandicted/nefertari-mongodb,ramses-tech/nefertari-mongodb
|
import logging
import datetime
import decimal
import elasticsearch
from bson import ObjectId, DBRef
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoder(_JSONEncoder):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, decimal.Decimal):
return float(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if hasattr(obj, 'to_dict'):
# If it got to this point, it means its a nested object.
# outter objects would have been handled with DataProxy.
return obj.to_dict(__nested=True)
return super(JSONEncoder, self).default(obj)
class ESJSONSerializer(elasticsearch.serializer.JSONSerializer):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if isinstance(obj, decimal.Decimal):
return float(obj)
try:
return super(ESJSONSerializer, self).default(obj)
except:
import traceback
log.error(traceback.format_exc())
Refactor encoders to have base class
|
import logging
import datetime
import decimal
import elasticsearch
from bson import ObjectId, DBRef
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoderMixin(object):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if isinstance(obj, decimal.Decimal):
return float(obj)
return super(JSONEncoderMixin, self).default(obj)
class JSONEncoder(JSONEncoderMixin, _JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_dict'):
# If it got to this point, it means its a nested object.
# outter objects would have been handled with DataProxy.
return obj.to_dict(__nested=True)
return super(JSONEncoder, self).default(obj)
class ESJSONSerializer(JSONEncoderMixin,
elasticsearch.serializer.JSONSerializer):
def default(self, obj):
try:
return super(ESJSONSerializer, self).default(obj)
except:
import traceback
log.error(traceback.format_exc())
|
<commit_before>import logging
import datetime
import decimal
import elasticsearch
from bson import ObjectId, DBRef
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoder(_JSONEncoder):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, decimal.Decimal):
return float(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if hasattr(obj, 'to_dict'):
# If it got to this point, it means its a nested object.
# outter objects would have been handled with DataProxy.
return obj.to_dict(__nested=True)
return super(JSONEncoder, self).default(obj)
class ESJSONSerializer(elasticsearch.serializer.JSONSerializer):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if isinstance(obj, decimal.Decimal):
return float(obj)
try:
return super(ESJSONSerializer, self).default(obj)
except:
import traceback
log.error(traceback.format_exc())
<commit_msg>Refactor encoders to have base class<commit_after>
|
import logging
import datetime
import decimal
import elasticsearch
from bson import ObjectId, DBRef
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoderMixin(object):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if isinstance(obj, decimal.Decimal):
return float(obj)
return super(JSONEncoderMixin, self).default(obj)
class JSONEncoder(JSONEncoderMixin, _JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_dict'):
# If it got to this point, it means its a nested object.
# outter objects would have been handled with DataProxy.
return obj.to_dict(__nested=True)
return super(JSONEncoder, self).default(obj)
class ESJSONSerializer(JSONEncoderMixin,
elasticsearch.serializer.JSONSerializer):
def default(self, obj):
try:
return super(ESJSONSerializer, self).default(obj)
except:
import traceback
log.error(traceback.format_exc())
|
import logging
import datetime
import decimal
import elasticsearch
from bson import ObjectId, DBRef
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoder(_JSONEncoder):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, decimal.Decimal):
return float(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if hasattr(obj, 'to_dict'):
# If it got to this point, it means its a nested object.
# outter objects would have been handled with DataProxy.
return obj.to_dict(__nested=True)
return super(JSONEncoder, self).default(obj)
class ESJSONSerializer(elasticsearch.serializer.JSONSerializer):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if isinstance(obj, decimal.Decimal):
return float(obj)
try:
return super(ESJSONSerializer, self).default(obj)
except:
import traceback
log.error(traceback.format_exc())
Refactor encoders to have base classimport logging
import datetime
import decimal
import elasticsearch
from bson import ObjectId, DBRef
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoderMixin(object):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if isinstance(obj, decimal.Decimal):
return float(obj)
return super(JSONEncoderMixin, self).default(obj)
class JSONEncoder(JSONEncoderMixin, _JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_dict'):
# If it got to this point, it means its a nested object.
# outter objects would have been handled with DataProxy.
return obj.to_dict(__nested=True)
return super(JSONEncoder, self).default(obj)
class ESJSONSerializer(JSONEncoderMixin,
elasticsearch.serializer.JSONSerializer):
def default(self, obj):
try:
return super(ESJSONSerializer, self).default(obj)
except:
import traceback
log.error(traceback.format_exc())
|
<commit_before>import logging
import datetime
import decimal
import elasticsearch
from bson import ObjectId, DBRef
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoder(_JSONEncoder):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, decimal.Decimal):
return float(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if hasattr(obj, 'to_dict'):
# If it got to this point, it means its a nested object.
# outter objects would have been handled with DataProxy.
return obj.to_dict(__nested=True)
return super(JSONEncoder, self).default(obj)
class ESJSONSerializer(elasticsearch.serializer.JSONSerializer):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if isinstance(obj, decimal.Decimal):
return float(obj)
try:
return super(ESJSONSerializer, self).default(obj)
except:
import traceback
log.error(traceback.format_exc())
<commit_msg>Refactor encoders to have base class<commit_after>import logging
import datetime
import decimal
import elasticsearch
from bson import ObjectId, DBRef
from nefertari.renderers import _JSONEncoder
log = logging.getLogger(__name__)
class JSONEncoderMixin(object):
def default(self, obj):
if isinstance(obj, (ObjectId, DBRef)):
return str(obj)
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso
if isinstance(obj, datetime.time):
return obj.strftime('%H:%M:%S')
if isinstance(obj, datetime.timedelta):
return obj.seconds
if isinstance(obj, decimal.Decimal):
return float(obj)
return super(JSONEncoderMixin, self).default(obj)
class JSONEncoder(JSONEncoderMixin, _JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_dict'):
# If it got to this point, it means its a nested object.
# outter objects would have been handled with DataProxy.
return obj.to_dict(__nested=True)
return super(JSONEncoder, self).default(obj)
class ESJSONSerializer(JSONEncoderMixin,
elasticsearch.serializer.JSONSerializer):
def default(self, obj):
try:
return super(ESJSONSerializer, self).default(obj)
except:
import traceback
log.error(traceback.format_exc())
|
d726efa1116f95ced28994c7c6bbcfe4cf703b05
|
wavvy/views.py
|
wavvy/views.py
|
from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session['logged_in'] = False
if 'username' in session:
del session['username']
return 'You are logged out.'
|
from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
def clear_session(s):
if 'username' in s:
del s['username']
s['logged_in'] = False
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
clear_session(session)
return 'You are logged out.'
|
Generalize the logout a bit
|
Generalize the logout a bit
This is on the road to removing auth from this file.
|
Python
|
mit
|
john-patterson/wavvy,john-patterson/wavvy
|
from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session['logged_in'] = False
if 'username' in session:
del session['username']
return 'You are logged out.'
Generalize the logout a bit
This is on the road to removing auth from this file.
|
from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
def clear_session(s):
if 'username' in s:
del s['username']
s['logged_in'] = False
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
clear_session(session)
return 'You are logged out.'
|
<commit_before>from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session['logged_in'] = False
if 'username' in session:
del session['username']
return 'You are logged out.'
<commit_msg>Generalize the logout a bit
This is on the road to removing auth from this file.<commit_after>
|
from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
def clear_session(s):
if 'username' in s:
del s['username']
s['logged_in'] = False
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
clear_session(session)
return 'You are logged out.'
|
from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session['logged_in'] = False
if 'username' in session:
del session['username']
return 'You are logged out.'
Generalize the logout a bit
This is on the road to removing auth from this file.from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
def clear_session(s):
if 'username' in s:
del s['username']
s['logged_in'] = False
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
clear_session(session)
return 'You are logged out.'
|
<commit_before>from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session['logged_in'] = False
if 'username' in session:
del session['username']
return 'You are logged out.'
<commit_msg>Generalize the logout a bit
This is on the road to removing auth from this file.<commit_after>from wavvy import app
from flask import Flask, url_for, render_template, request, session, escape
def clear_session(s):
if 'username' in s:
del s['username']
s['logged_in'] = False
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
@app.route('/')
def index():
if session.get('logged_in', False):
return 'Logged in as {}'.format(escape(session['username']))
return 'You are not logged in.'
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
session['logged_in'] = True
session['username'] = request.form['username']
password = escape(request.form['password'])
return 'Validating a login! U:{} P:{}'.format(escape(session['username']), password)
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
clear_session(session)
return 'You are logged out.'
|
69a6ced2bb923c6a77c74443e8892cdba550651e
|
pyramda/iterable/reject.py
|
pyramda/iterable/reject.py
|
from pyramda.function.curry import curry
from . import filter
@curry
def reject(p, xs):
"""
Acts as a complement of `filter`
:param p: predicate
:param xs: Iterable. A sequence, a container which supports iteration or an iterator
:return: list
"""
return list(set(xs) - set(filter(p, xs)))
|
from pyramda.function.curry import curry
from pyramda.logic import complement
from . import filter
@curry
def reject(p, xs):
"""
Acts as a complement of `filter`
:param p: predicate
:param xs: Iterable. A sequence, a container which supports iteration or an iterator
:return: list
"""
return filter(complement(p), xs)
|
Refactor to use pyramdas complement function. The initial set implementaion did not respect the order of elements and removed duplicates
|
Refactor to use pyramdas complement function. The initial set implementaion did not respect the order of elements and removed duplicates
|
Python
|
mit
|
jackfirth/pyramda
|
from pyramda.function.curry import curry
from . import filter
@curry
def reject(p, xs):
"""
Acts as a complement of `filter`
:param p: predicate
:param xs: Iterable. A sequence, a container which supports iteration or an iterator
:return: list
"""
return list(set(xs) - set(filter(p, xs)))
Refactor to use pyramdas complement function. The initial set implementaion did not respect the order of elements and removed duplicates
|
from pyramda.function.curry import curry
from pyramda.logic import complement
from . import filter
@curry
def reject(p, xs):
"""
Acts as a complement of `filter`
:param p: predicate
:param xs: Iterable. A sequence, a container which supports iteration or an iterator
:return: list
"""
return filter(complement(p), xs)
|
<commit_before>from pyramda.function.curry import curry
from . import filter
@curry
def reject(p, xs):
"""
Acts as a complement of `filter`
:param p: predicate
:param xs: Iterable. A sequence, a container which supports iteration or an iterator
:return: list
"""
return list(set(xs) - set(filter(p, xs)))
<commit_msg>Refactor to use pyramdas complement function. The initial set implementaion did not respect the order of elements and removed duplicates<commit_after>
|
from pyramda.function.curry import curry
from pyramda.logic import complement
from . import filter
@curry
def reject(p, xs):
"""
Acts as a complement of `filter`
:param p: predicate
:param xs: Iterable. A sequence, a container which supports iteration or an iterator
:return: list
"""
return filter(complement(p), xs)
|
from pyramda.function.curry import curry
from . import filter
@curry
def reject(p, xs):
"""
Acts as a complement of `filter`
:param p: predicate
:param xs: Iterable. A sequence, a container which supports iteration or an iterator
:return: list
"""
return list(set(xs) - set(filter(p, xs)))
Refactor to use pyramdas complement function. The initial set implementaion did not respect the order of elements and removed duplicatesfrom pyramda.function.curry import curry
from pyramda.logic import complement
from . import filter
@curry
def reject(p, xs):
"""
Acts as a complement of `filter`
:param p: predicate
:param xs: Iterable. A sequence, a container which supports iteration or an iterator
:return: list
"""
return filter(complement(p), xs)
|
<commit_before>from pyramda.function.curry import curry
from . import filter
@curry
def reject(p, xs):
"""
Acts as a complement of `filter`
:param p: predicate
:param xs: Iterable. A sequence, a container which supports iteration or an iterator
:return: list
"""
return list(set(xs) - set(filter(p, xs)))
<commit_msg>Refactor to use pyramdas complement function. The initial set implementaion did not respect the order of elements and removed duplicates<commit_after>from pyramda.function.curry import curry
from pyramda.logic import complement
from . import filter
@curry
def reject(p, xs):
"""
Acts as a complement of `filter`
:param p: predicate
:param xs: Iterable. A sequence, a container which supports iteration or an iterator
:return: list
"""
return filter(complement(p), xs)
|
78af31feb8ac731eda18a5fff8075bb7dde90dde
|
scripts/test_deployment.py
|
scripts/test_deployment.py
|
import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
|
import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/api/images/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/api/images/custom/test.png"
"?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
|
Use API route in promotion tests
|
Use API route in promotion tests
|
Python
|
mit
|
jacebrowning/memegen,jacebrowning/memegen
|
import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
Use API route in promotion tests
|
import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/api/images/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/api/images/custom/test.png"
"?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
|
<commit_before>import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
<commit_msg>Use API route in promotion tests<commit_after>
|
import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/api/images/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/api/images/custom/test.png"
"?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
|
import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
Use API route in promotion testsimport os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/api/images/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/api/images/custom/test.png"
"?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
|
<commit_before>import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
<commit_msg>Use API route in promotion tests<commit_after>import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/api/images/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/api/images/custom/test.png"
"?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
|
d6432aa912f6d654f45c9bbfd27df46529816caf
|
rakuten/apis/travel_api.py
|
rakuten/apis/travel_api.py
|
import requests
from .api_exception import RakutenApiException
from .base_api import BaseApi
class TravelApi(BaseApi):
def __init__(self, options):
super(TravelApi, self).__init__(options)
def vacant_hotel_search(self, **kwargs):
params = self._dict_to_camel_case(kwargs)
params.update(self._default_params)
url = self._make_url('/Travel/VacantHotelSearch/20131024')
r = requests.get(url, params=params)
if r.status_code == 200:
result = r.json()
hotels = [self._parse_hotel(r) for r in result['hotels']]
return hotels
else:
raise RakutenApiException(r.status_code, r.text)
def _parse_hotel(self, hotel_info):
hotel = hotel_info['hotel'][0]['hotelBasicInfo']
room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r]
hotel['room_infos'] = room_infos
return hotel
|
import requests
from .api_exception import RakutenApiException
from .base_api import BaseApi
class TravelApi(BaseApi):
def __init__(self, options):
super(TravelApi, self).__init__(options)
self._default_params['datumType'] = 1
def vacant_hotel_search(self, **kwargs):
params = self._dict_to_camel_case(kwargs)
params.update(self._default_params)
url = self._make_url('/Travel/VacantHotelSearch/20131024')
r = requests.get(url, params=params)
if r.status_code == 200:
result = r.json()
hotels = [self._parse_hotel(r) for r in result['hotels']]
return hotels
else:
raise RakutenApiException(r.status_code, r.text)
def _parse_hotel(self, hotel_info):
hotel = hotel_info['hotel'][0]['hotelBasicInfo']
room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r]
hotel['room_infos'] = room_infos
return hotel
|
Change default format to normal longitude/latitude.
|
Change default format to normal longitude/latitude.
|
Python
|
mit
|
claudetech/python_rakuten
|
import requests
from .api_exception import RakutenApiException
from .base_api import BaseApi
class TravelApi(BaseApi):
def __init__(self, options):
super(TravelApi, self).__init__(options)
def vacant_hotel_search(self, **kwargs):
params = self._dict_to_camel_case(kwargs)
params.update(self._default_params)
url = self._make_url('/Travel/VacantHotelSearch/20131024')
r = requests.get(url, params=params)
if r.status_code == 200:
result = r.json()
hotels = [self._parse_hotel(r) for r in result['hotels']]
return hotels
else:
raise RakutenApiException(r.status_code, r.text)
def _parse_hotel(self, hotel_info):
hotel = hotel_info['hotel'][0]['hotelBasicInfo']
room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r]
hotel['room_infos'] = room_infos
return hotel
Change default format to normal longitude/latitude.
|
import requests
from .api_exception import RakutenApiException
from .base_api import BaseApi
class TravelApi(BaseApi):
def __init__(self, options):
super(TravelApi, self).__init__(options)
self._default_params['datumType'] = 1
def vacant_hotel_search(self, **kwargs):
params = self._dict_to_camel_case(kwargs)
params.update(self._default_params)
url = self._make_url('/Travel/VacantHotelSearch/20131024')
r = requests.get(url, params=params)
if r.status_code == 200:
result = r.json()
hotels = [self._parse_hotel(r) for r in result['hotels']]
return hotels
else:
raise RakutenApiException(r.status_code, r.text)
def _parse_hotel(self, hotel_info):
hotel = hotel_info['hotel'][0]['hotelBasicInfo']
room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r]
hotel['room_infos'] = room_infos
return hotel
|
<commit_before>import requests
from .api_exception import RakutenApiException
from .base_api import BaseApi
class TravelApi(BaseApi):
def __init__(self, options):
super(TravelApi, self).__init__(options)
def vacant_hotel_search(self, **kwargs):
params = self._dict_to_camel_case(kwargs)
params.update(self._default_params)
url = self._make_url('/Travel/VacantHotelSearch/20131024')
r = requests.get(url, params=params)
if r.status_code == 200:
result = r.json()
hotels = [self._parse_hotel(r) for r in result['hotels']]
return hotels
else:
raise RakutenApiException(r.status_code, r.text)
def _parse_hotel(self, hotel_info):
hotel = hotel_info['hotel'][0]['hotelBasicInfo']
room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r]
hotel['room_infos'] = room_infos
return hotel
<commit_msg>Change default format to normal longitude/latitude.<commit_after>
|
import requests
from .api_exception import RakutenApiException
from .base_api import BaseApi
class TravelApi(BaseApi):
def __init__(self, options):
super(TravelApi, self).__init__(options)
self._default_params['datumType'] = 1
def vacant_hotel_search(self, **kwargs):
params = self._dict_to_camel_case(kwargs)
params.update(self._default_params)
url = self._make_url('/Travel/VacantHotelSearch/20131024')
r = requests.get(url, params=params)
if r.status_code == 200:
result = r.json()
hotels = [self._parse_hotel(r) for r in result['hotels']]
return hotels
else:
raise RakutenApiException(r.status_code, r.text)
def _parse_hotel(self, hotel_info):
hotel = hotel_info['hotel'][0]['hotelBasicInfo']
room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r]
hotel['room_infos'] = room_infos
return hotel
|
import requests
from .api_exception import RakutenApiException
from .base_api import BaseApi
class TravelApi(BaseApi):
def __init__(self, options):
super(TravelApi, self).__init__(options)
def vacant_hotel_search(self, **kwargs):
params = self._dict_to_camel_case(kwargs)
params.update(self._default_params)
url = self._make_url('/Travel/VacantHotelSearch/20131024')
r = requests.get(url, params=params)
if r.status_code == 200:
result = r.json()
hotels = [self._parse_hotel(r) for r in result['hotels']]
return hotels
else:
raise RakutenApiException(r.status_code, r.text)
def _parse_hotel(self, hotel_info):
hotel = hotel_info['hotel'][0]['hotelBasicInfo']
room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r]
hotel['room_infos'] = room_infos
return hotel
Change default format to normal longitude/latitude.import requests
from .api_exception import RakutenApiException
from .base_api import BaseApi
class TravelApi(BaseApi):
def __init__(self, options):
super(TravelApi, self).__init__(options)
self._default_params['datumType'] = 1
def vacant_hotel_search(self, **kwargs):
params = self._dict_to_camel_case(kwargs)
params.update(self._default_params)
url = self._make_url('/Travel/VacantHotelSearch/20131024')
r = requests.get(url, params=params)
if r.status_code == 200:
result = r.json()
hotels = [self._parse_hotel(r) for r in result['hotels']]
return hotels
else:
raise RakutenApiException(r.status_code, r.text)
def _parse_hotel(self, hotel_info):
hotel = hotel_info['hotel'][0]['hotelBasicInfo']
room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r]
hotel['room_infos'] = room_infos
return hotel
|
<commit_before>import requests
from .api_exception import RakutenApiException
from .base_api import BaseApi
class TravelApi(BaseApi):
def __init__(self, options):
super(TravelApi, self).__init__(options)
def vacant_hotel_search(self, **kwargs):
params = self._dict_to_camel_case(kwargs)
params.update(self._default_params)
url = self._make_url('/Travel/VacantHotelSearch/20131024')
r = requests.get(url, params=params)
if r.status_code == 200:
result = r.json()
hotels = [self._parse_hotel(r) for r in result['hotels']]
return hotels
else:
raise RakutenApiException(r.status_code, r.text)
def _parse_hotel(self, hotel_info):
hotel = hotel_info['hotel'][0]['hotelBasicInfo']
room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r]
hotel['room_infos'] = room_infos
return hotel
<commit_msg>Change default format to normal longitude/latitude.<commit_after>import requests
from .api_exception import RakutenApiException
from .base_api import BaseApi
class TravelApi(BaseApi):
def __init__(self, options):
super(TravelApi, self).__init__(options)
self._default_params['datumType'] = 1
def vacant_hotel_search(self, **kwargs):
params = self._dict_to_camel_case(kwargs)
params.update(self._default_params)
url = self._make_url('/Travel/VacantHotelSearch/20131024')
r = requests.get(url, params=params)
if r.status_code == 200:
result = r.json()
hotels = [self._parse_hotel(r) for r in result['hotels']]
return hotels
else:
raise RakutenApiException(r.status_code, r.text)
def _parse_hotel(self, hotel_info):
hotel = hotel_info['hotel'][0]['hotelBasicInfo']
room_infos = [r['roomInfo'][0]['roomBasicInfo'] for r in hotel_info['hotel'] if 'roomInfo' in r]
hotel['room_infos'] = room_infos
return hotel
|
fc345d692e325566ae26419857bfaadb7194400f
|
promgen/sender/__init__.py
|
promgen/sender/__init__.py
|
import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def send(self, data):
sent = 0
for alert in data['alerts']:
for label, klass in self.MAPPING:
logger.debug('Checking for %s', label)
if label in alert['labels']:
logger.debug('Checking for %s %s', label, klass)
for obj in klass.objects.filter(name=alert['labels'][label]):
for sender in obj.sender.filter(sender=self.__module__):
logger.debug('Sending to %s', sender)
if self._send(sender.value, alert, data):
sent += 1
if sent == 0:
logger.debug('No senders configured for project or service')
return sent
def test(self, target, alert):
logger.debug('Sending test message to %s', target)
self._send(target, alert, {'externalURL': ''})
|
import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def _send(self, target, alert, data):
'''
Sender specific implmentation
This function will receive some kind of target value, such as an email
address or post endpoint and an individual alert combined with some
additional alert meta data
'''
raise NotImplementedError()
def send(self, data):
'''
Send out an alert
This handles looping through the alerts from Alert Manager and checks
to see if there are any notification senders configured for the
combination of project/service and sender type.
See tests/examples/alertmanager.json for an example payload
'''
sent = 0
for alert in data['alerts']:
for label, klass in self.MAPPING:
logger.debug('Checking for %s', label)
if label in alert['labels']:
logger.debug('Checking for %s %s', label, klass)
for obj in klass.objects.filter(name=alert['labels'][label]):
for sender in obj.sender.filter(sender=self.__module__):
logger.debug('Sending to %s', sender)
if self._send(sender.value, alert, data):
sent += 1
if sent == 0:
logger.debug('No senders configured for project or service')
return sent
def test(self, target, alert):
'''
Send out test notification
Combine a simple test alert from our view, with the remaining required
parameters for our sender child classes
'''
logger.debug('Sending test message to %s', target)
self._send(target, alert, {'externalURL': ''})
|
Add documentation to SenderBase plugin
|
Add documentation to SenderBase plugin
|
Python
|
mit
|
kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen
|
import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def send(self, data):
sent = 0
for alert in data['alerts']:
for label, klass in self.MAPPING:
logger.debug('Checking for %s', label)
if label in alert['labels']:
logger.debug('Checking for %s %s', label, klass)
for obj in klass.objects.filter(name=alert['labels'][label]):
for sender in obj.sender.filter(sender=self.__module__):
logger.debug('Sending to %s', sender)
if self._send(sender.value, alert, data):
sent += 1
if sent == 0:
logger.debug('No senders configured for project or service')
return sent
def test(self, target, alert):
logger.debug('Sending test message to %s', target)
self._send(target, alert, {'externalURL': ''})
Add documentation to SenderBase plugin
|
import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def _send(self, target, alert, data):
'''
Sender specific implmentation
This function will receive some kind of target value, such as an email
address or post endpoint and an individual alert combined with some
additional alert meta data
'''
raise NotImplementedError()
def send(self, data):
'''
Send out an alert
This handles looping through the alerts from Alert Manager and checks
to see if there are any notification senders configured for the
combination of project/service and sender type.
See tests/examples/alertmanager.json for an example payload
'''
sent = 0
for alert in data['alerts']:
for label, klass in self.MAPPING:
logger.debug('Checking for %s', label)
if label in alert['labels']:
logger.debug('Checking for %s %s', label, klass)
for obj in klass.objects.filter(name=alert['labels'][label]):
for sender in obj.sender.filter(sender=self.__module__):
logger.debug('Sending to %s', sender)
if self._send(sender.value, alert, data):
sent += 1
if sent == 0:
logger.debug('No senders configured for project or service')
return sent
def test(self, target, alert):
'''
Send out test notification
Combine a simple test alert from our view, with the remaining required
parameters for our sender child classes
'''
logger.debug('Sending test message to %s', target)
self._send(target, alert, {'externalURL': ''})
|
<commit_before>import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def send(self, data):
sent = 0
for alert in data['alerts']:
for label, klass in self.MAPPING:
logger.debug('Checking for %s', label)
if label in alert['labels']:
logger.debug('Checking for %s %s', label, klass)
for obj in klass.objects.filter(name=alert['labels'][label]):
for sender in obj.sender.filter(sender=self.__module__):
logger.debug('Sending to %s', sender)
if self._send(sender.value, alert, data):
sent += 1
if sent == 0:
logger.debug('No senders configured for project or service')
return sent
def test(self, target, alert):
logger.debug('Sending test message to %s', target)
self._send(target, alert, {'externalURL': ''})
<commit_msg>Add documentation to SenderBase plugin<commit_after>
|
import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def _send(self, target, alert, data):
'''
Sender specific implmentation
This function will receive some kind of target value, such as an email
address or post endpoint and an individual alert combined with some
additional alert meta data
'''
raise NotImplementedError()
def send(self, data):
'''
Send out an alert
This handles looping through the alerts from Alert Manager and checks
to see if there are any notification senders configured for the
combination of project/service and sender type.
See tests/examples/alertmanager.json for an example payload
'''
sent = 0
for alert in data['alerts']:
for label, klass in self.MAPPING:
logger.debug('Checking for %s', label)
if label in alert['labels']:
logger.debug('Checking for %s %s', label, klass)
for obj in klass.objects.filter(name=alert['labels'][label]):
for sender in obj.sender.filter(sender=self.__module__):
logger.debug('Sending to %s', sender)
if self._send(sender.value, alert, data):
sent += 1
if sent == 0:
logger.debug('No senders configured for project or service')
return sent
def test(self, target, alert):
'''
Send out test notification
Combine a simple test alert from our view, with the remaining required
parameters for our sender child classes
'''
logger.debug('Sending test message to %s', target)
self._send(target, alert, {'externalURL': ''})
|
import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def send(self, data):
sent = 0
for alert in data['alerts']:
for label, klass in self.MAPPING:
logger.debug('Checking for %s', label)
if label in alert['labels']:
logger.debug('Checking for %s %s', label, klass)
for obj in klass.objects.filter(name=alert['labels'][label]):
for sender in obj.sender.filter(sender=self.__module__):
logger.debug('Sending to %s', sender)
if self._send(sender.value, alert, data):
sent += 1
if sent == 0:
logger.debug('No senders configured for project or service')
return sent
def test(self, target, alert):
logger.debug('Sending test message to %s', target)
self._send(target, alert, {'externalURL': ''})
Add documentation to SenderBase pluginimport logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def _send(self, target, alert, data):
'''
Sender specific implmentation
This function will receive some kind of target value, such as an email
address or post endpoint and an individual alert combined with some
additional alert meta data
'''
raise NotImplementedError()
def send(self, data):
'''
Send out an alert
This handles looping through the alerts from Alert Manager and checks
to see if there are any notification senders configured for the
combination of project/service and sender type.
See tests/examples/alertmanager.json for an example payload
'''
sent = 0
for alert in data['alerts']:
for label, klass in self.MAPPING:
logger.debug('Checking for %s', label)
if label in alert['labels']:
logger.debug('Checking for %s %s', label, klass)
for obj in klass.objects.filter(name=alert['labels'][label]):
for sender in obj.sender.filter(sender=self.__module__):
logger.debug('Sending to %s', sender)
if self._send(sender.value, alert, data):
sent += 1
if sent == 0:
logger.debug('No senders configured for project or service')
return sent
def test(self, target, alert):
'''
Send out test notification
Combine a simple test alert from our view, with the remaining required
parameters for our sender child classes
'''
logger.debug('Sending test message to %s', target)
self._send(target, alert, {'externalURL': ''})
|
<commit_before>import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def send(self, data):
sent = 0
for alert in data['alerts']:
for label, klass in self.MAPPING:
logger.debug('Checking for %s', label)
if label in alert['labels']:
logger.debug('Checking for %s %s', label, klass)
for obj in klass.objects.filter(name=alert['labels'][label]):
for sender in obj.sender.filter(sender=self.__module__):
logger.debug('Sending to %s', sender)
if self._send(sender.value, alert, data):
sent += 1
if sent == 0:
logger.debug('No senders configured for project or service')
return sent
def test(self, target, alert):
logger.debug('Sending test message to %s', target)
self._send(target, alert, {'externalURL': ''})
<commit_msg>Add documentation to SenderBase plugin<commit_after>import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def _send(self, target, alert, data):
'''
Sender specific implmentation
This function will receive some kind of target value, such as an email
address or post endpoint and an individual alert combined with some
additional alert meta data
'''
raise NotImplementedError()
def send(self, data):
'''
Send out an alert
This handles looping through the alerts from Alert Manager and checks
to see if there are any notification senders configured for the
combination of project/service and sender type.
See tests/examples/alertmanager.json for an example payload
'''
sent = 0
for alert in data['alerts']:
for label, klass in self.MAPPING:
logger.debug('Checking for %s', label)
if label in alert['labels']:
logger.debug('Checking for %s %s', label, klass)
for obj in klass.objects.filter(name=alert['labels'][label]):
for sender in obj.sender.filter(sender=self.__module__):
logger.debug('Sending to %s', sender)
if self._send(sender.value, alert, data):
sent += 1
if sent == 0:
logger.debug('No senders configured for project or service')
return sent
def test(self, target, alert):
'''
Send out test notification
Combine a simple test alert from our view, with the remaining required
parameters for our sender child classes
'''
logger.debug('Sending test message to %s', target)
self._send(target, alert, {'externalURL': ''})
|
76d45475090144903ec3421491dc5f998f67e236
|
mqueue/apps.py
|
mqueue/apps.py
|
import importlib
from django.utils.translation import ugettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
verbose_name = _(u"Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from mqueue.tracking import mqueue_tracker
registered_models = getattr(settings, 'MQUEUE_AUTOREGISTER', [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split('.')
path = '.'.join(modsplit[:-1])
modname = '.'.join(modsplit[-1:])
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level)
# watchers
from mqueue.watchers import init_watchers
from mqueue.conf import WATCH
init_watchers(WATCH)
|
import importlib
from django.utils.translation import ugettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
verbose_name = _(u"Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from mqueue.tracking import mqueue_tracker
registered_models = getattr(settings, 'MQUEUE_AUTOREGISTER', [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split('.')
path = '.'.join(modsplit[:-1])
modname = '.'.join(modsplit[-1:])
try:
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level)
except ImportError:
from mqueue.models import MEvent
msg = "ERROR from Django Mqueue : can not import model " + modpath
MEvent.objects.create(
name=msg, event_class="Error")
# watchers
from mqueue.watchers import init_watchers
from mqueue.conf import WATCH
init_watchers(WATCH)
|
Add error handling on module import at initilization time
|
Add error handling on module import at initilization time
|
Python
|
mit
|
synw/django-mqueue,synw/django-mqueue,synw/django-mqueue
|
import importlib
from django.utils.translation import ugettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
verbose_name = _(u"Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from mqueue.tracking import mqueue_tracker
registered_models = getattr(settings, 'MQUEUE_AUTOREGISTER', [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split('.')
path = '.'.join(modsplit[:-1])
modname = '.'.join(modsplit[-1:])
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level)
# watchers
from mqueue.watchers import init_watchers
from mqueue.conf import WATCH
init_watchers(WATCH)
Add error handling on module import at initilization time
|
import importlib
from django.utils.translation import ugettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
verbose_name = _(u"Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from mqueue.tracking import mqueue_tracker
registered_models = getattr(settings, 'MQUEUE_AUTOREGISTER', [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split('.')
path = '.'.join(modsplit[:-1])
modname = '.'.join(modsplit[-1:])
try:
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level)
except ImportError:
from mqueue.models import MEvent
msg = "ERROR from Django Mqueue : can not import model " + modpath
MEvent.objects.create(
name=msg, event_class="Error")
# watchers
from mqueue.watchers import init_watchers
from mqueue.conf import WATCH
init_watchers(WATCH)
|
<commit_before>import importlib
from django.utils.translation import ugettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
verbose_name = _(u"Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from mqueue.tracking import mqueue_tracker
registered_models = getattr(settings, 'MQUEUE_AUTOREGISTER', [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split('.')
path = '.'.join(modsplit[:-1])
modname = '.'.join(modsplit[-1:])
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level)
# watchers
from mqueue.watchers import init_watchers
from mqueue.conf import WATCH
init_watchers(WATCH)
<commit_msg>Add error handling on module import at initilization time<commit_after>
|
import importlib
from django.utils.translation import ugettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
verbose_name = _(u"Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from mqueue.tracking import mqueue_tracker
registered_models = getattr(settings, 'MQUEUE_AUTOREGISTER', [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split('.')
path = '.'.join(modsplit[:-1])
modname = '.'.join(modsplit[-1:])
try:
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level)
except ImportError:
from mqueue.models import MEvent
msg = "ERROR from Django Mqueue : can not import model " + modpath
MEvent.objects.create(
name=msg, event_class="Error")
# watchers
from mqueue.watchers import init_watchers
from mqueue.conf import WATCH
init_watchers(WATCH)
|
import importlib
from django.utils.translation import ugettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
verbose_name = _(u"Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from mqueue.tracking import mqueue_tracker
registered_models = getattr(settings, 'MQUEUE_AUTOREGISTER', [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split('.')
path = '.'.join(modsplit[:-1])
modname = '.'.join(modsplit[-1:])
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level)
# watchers
from mqueue.watchers import init_watchers
from mqueue.conf import WATCH
init_watchers(WATCH)
Add error handling on module import at initilization timeimport importlib
from django.utils.translation import ugettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
verbose_name = _(u"Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from mqueue.tracking import mqueue_tracker
registered_models = getattr(settings, 'MQUEUE_AUTOREGISTER', [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split('.')
path = '.'.join(modsplit[:-1])
modname = '.'.join(modsplit[-1:])
try:
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level)
except ImportError:
from mqueue.models import MEvent
msg = "ERROR from Django Mqueue : can not import model " + modpath
MEvent.objects.create(
name=msg, event_class="Error")
# watchers
from mqueue.watchers import init_watchers
from mqueue.conf import WATCH
init_watchers(WATCH)
|
<commit_before>import importlib
from django.utils.translation import ugettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
verbose_name = _(u"Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from mqueue.tracking import mqueue_tracker
registered_models = getattr(settings, 'MQUEUE_AUTOREGISTER', [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split('.')
path = '.'.join(modsplit[:-1])
modname = '.'.join(modsplit[-1:])
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level)
# watchers
from mqueue.watchers import init_watchers
from mqueue.conf import WATCH
init_watchers(WATCH)
<commit_msg>Add error handling on module import at initilization time<commit_after>import importlib
from django.utils.translation import ugettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
verbose_name = _(u"Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from mqueue.tracking import mqueue_tracker
registered_models = getattr(settings, 'MQUEUE_AUTOREGISTER', [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split('.')
path = '.'.join(modsplit[:-1])
modname = '.'.join(modsplit[-1:])
try:
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level)
except ImportError:
from mqueue.models import MEvent
msg = "ERROR from Django Mqueue : can not import model " + modpath
MEvent.objects.create(
name=msg, event_class="Error")
# watchers
from mqueue.watchers import init_watchers
from mqueue.conf import WATCH
init_watchers(WATCH)
|
32a238838778fb74ee269b891feca59048e78a3a
|
api/management/commands/update_account_center_cache.py
|
api/management/commands/update_account_center_cache.py
|
from django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from api import models
def update_account_center_cache(opt={}):
print '# Update account center'
accounts = models.Account.objects.filter(center__isnull=False).select_related('center', 'center__card')
for account in accounts:
account.center_card_transparent_image = account.center.card.transparent_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.transparent_image
account.center_card_round_image = account.center.card.round_card_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.round_card_image
account.center_card_attribute = account.center.card.attribute
account.center_alt_text = unicode(account.center.card)
account.center_card_id = account.center.card.id
print 'Account #{} center {}'.format(account, account.center)
account.save()
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
update_account_center_cache({})
|
from django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from api import models
def update_account_center_cache(opt={}):
print '# Update account center'
accounts = models.Account.objects.filter(center__isnull=False, center_card_id__isnull=True).select_related('center', 'center__card')
for account in accounts:
account.center_card_transparent_image = account.center.card.transparent_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.transparent_image
account.center_card_round_image = account.center.card.round_card_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.round_card_image
account.center_card_attribute = account.center.card.attribute
account.center_alt_text = unicode(account.center.card)
account.center_card_id = account.center.card.id
print 'Account #{} center {}'.format(account, account.center)
account.save()
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
update_account_center_cache({})
|
Allow to restart the account center cache script without reloading everything
|
Allow to restart the account center cache script without reloading everything
|
Python
|
apache-2.0
|
rdsathene/SchoolIdolAPI,dburr/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,dburr/SchoolIdolAPI,dburr/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI,rdsathene/SchoolIdolAPI,rdsathene/SchoolIdolAPI,SchoolIdolTomodachi/SchoolIdolAPI
|
from django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from api import models
def update_account_center_cache(opt={}):
print '# Update account center'
accounts = models.Account.objects.filter(center__isnull=False).select_related('center', 'center__card')
for account in accounts:
account.center_card_transparent_image = account.center.card.transparent_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.transparent_image
account.center_card_round_image = account.center.card.round_card_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.round_card_image
account.center_card_attribute = account.center.card.attribute
account.center_alt_text = unicode(account.center.card)
account.center_card_id = account.center.card.id
print 'Account #{} center {}'.format(account, account.center)
account.save()
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
update_account_center_cache({})
Allow to restart the account center cache script without reloading everything
|
from django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from api import models
def update_account_center_cache(opt={}):
print '# Update account center'
accounts = models.Account.objects.filter(center__isnull=False, center_card_id__isnull=True).select_related('center', 'center__card')
for account in accounts:
account.center_card_transparent_image = account.center.card.transparent_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.transparent_image
account.center_card_round_image = account.center.card.round_card_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.round_card_image
account.center_card_attribute = account.center.card.attribute
account.center_alt_text = unicode(account.center.card)
account.center_card_id = account.center.card.id
print 'Account #{} center {}'.format(account, account.center)
account.save()
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
update_account_center_cache({})
|
<commit_before>from django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from api import models
def update_account_center_cache(opt={}):
print '# Update account center'
accounts = models.Account.objects.filter(center__isnull=False).select_related('center', 'center__card')
for account in accounts:
account.center_card_transparent_image = account.center.card.transparent_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.transparent_image
account.center_card_round_image = account.center.card.round_card_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.round_card_image
account.center_card_attribute = account.center.card.attribute
account.center_alt_text = unicode(account.center.card)
account.center_card_id = account.center.card.id
print 'Account #{} center {}'.format(account, account.center)
account.save()
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
update_account_center_cache({})
<commit_msg>Allow to restart the account center cache script without reloading everything<commit_after>
|
from django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from api import models
def update_account_center_cache(opt={}):
print '# Update account center'
accounts = models.Account.objects.filter(center__isnull=False, center_card_id__isnull=True).select_related('center', 'center__card')
for account in accounts:
account.center_card_transparent_image = account.center.card.transparent_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.transparent_image
account.center_card_round_image = account.center.card.round_card_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.round_card_image
account.center_card_attribute = account.center.card.attribute
account.center_alt_text = unicode(account.center.card)
account.center_card_id = account.center.card.id
print 'Account #{} center {}'.format(account, account.center)
account.save()
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
update_account_center_cache({})
|
from django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from api import models
def update_account_center_cache(opt={}):
print '# Update account center'
accounts = models.Account.objects.filter(center__isnull=False).select_related('center', 'center__card')
for account in accounts:
account.center_card_transparent_image = account.center.card.transparent_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.transparent_image
account.center_card_round_image = account.center.card.round_card_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.round_card_image
account.center_card_attribute = account.center.card.attribute
account.center_alt_text = unicode(account.center.card)
account.center_card_id = account.center.card.id
print 'Account #{} center {}'.format(account, account.center)
account.save()
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
update_account_center_cache({})
Allow to restart the account center cache script without reloading everythingfrom django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from api import models
def update_account_center_cache(opt={}):
print '# Update account center'
accounts = models.Account.objects.filter(center__isnull=False, center_card_id__isnull=True).select_related('center', 'center__card')
for account in accounts:
account.center_card_transparent_image = account.center.card.transparent_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.transparent_image
account.center_card_round_image = account.center.card.round_card_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.round_card_image
account.center_card_attribute = account.center.card.attribute
account.center_alt_text = unicode(account.center.card)
account.center_card_id = account.center.card.id
print 'Account #{} center {}'.format(account, account.center)
account.save()
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
update_account_center_cache({})
|
<commit_before>from django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from api import models
def update_account_center_cache(opt={}):
print '# Update account center'
accounts = models.Account.objects.filter(center__isnull=False).select_related('center', 'center__card')
for account in accounts:
account.center_card_transparent_image = account.center.card.transparent_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.transparent_image
account.center_card_round_image = account.center.card.round_card_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.round_card_image
account.center_card_attribute = account.center.card.attribute
account.center_alt_text = unicode(account.center.card)
account.center_card_id = account.center.card.id
print 'Account #{} center {}'.format(account, account.center)
account.save()
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
update_account_center_cache({})
<commit_msg>Allow to restart the account center cache script without reloading everything<commit_after>from django.core.management.base import BaseCommand, CommandError
from django.db.models import F, Q
from api import models
def update_account_center_cache(opt={}):
print '# Update account center'
accounts = models.Account.objects.filter(center__isnull=False, center_card_id__isnull=True).select_related('center', 'center__card')
for account in accounts:
account.center_card_transparent_image = account.center.card.transparent_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.transparent_image
account.center_card_round_image = account.center.card.round_card_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.round_card_image
account.center_card_attribute = account.center.card.attribute
account.center_alt_text = unicode(account.center.card)
account.center_card_id = account.center.card.id
print 'Account #{} center {}'.format(account, account.center)
account.save()
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
update_account_center_cache({})
|
61465e1df2f43d2d82b40ddb15c17bee4ddcccda
|
src/poliastro/ephem.py
|
src/poliastro/ephem.py
|
import numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from poliastro.bodies import Moon
from poliastro.twobody.orbit import Orbit
from poliastro.coordinates import transform
from astropy.coordinates import ICRS, GCRS
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
body_t = Orbit.from_body_ephem(body, epoch)
if body != Moon:
body_t = transform(body_t, ICRS, GCRS)
r_values[i] = body_t.r
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
|
import numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from astropy.coordinates import get_body_barycentric, ICRS, GCRS, CartesianRepresentation
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
r = get_body_barycentric(body.name, epoch)
r = (ICRS(x=r.x, y=r.y, z=r.z, representation_type=CartesianRepresentation)
.transform_to(GCRS(obstime=epoch))
.represent_as(CartesianRepresentation)
)
r_values[i] = r.xyz.to(u.km)
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
|
Fix 3rd body tests for Moon, simplify interpolant code
|
Fix 3rd body tests for Moon, simplify interpolant code
|
Python
|
mit
|
Juanlu001/poliastro,Juanlu001/poliastro,newlawrence/poliastro,Juanlu001/poliastro,newlawrence/poliastro,poliastro/poliastro,newlawrence/poliastro
|
import numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from poliastro.bodies import Moon
from poliastro.twobody.orbit import Orbit
from poliastro.coordinates import transform
from astropy.coordinates import ICRS, GCRS
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
body_t = Orbit.from_body_ephem(body, epoch)
if body != Moon:
body_t = transform(body_t, ICRS, GCRS)
r_values[i] = body_t.r
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
Fix 3rd body tests for Moon, simplify interpolant code
|
import numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from astropy.coordinates import get_body_barycentric, ICRS, GCRS, CartesianRepresentation
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
r = get_body_barycentric(body.name, epoch)
r = (ICRS(x=r.x, y=r.y, z=r.z, representation_type=CartesianRepresentation)
.transform_to(GCRS(obstime=epoch))
.represent_as(CartesianRepresentation)
)
r_values[i] = r.xyz.to(u.km)
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
|
<commit_before>import numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from poliastro.bodies import Moon
from poliastro.twobody.orbit import Orbit
from poliastro.coordinates import transform
from astropy.coordinates import ICRS, GCRS
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
body_t = Orbit.from_body_ephem(body, epoch)
if body != Moon:
body_t = transform(body_t, ICRS, GCRS)
r_values[i] = body_t.r
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
<commit_msg>Fix 3rd body tests for Moon, simplify interpolant code<commit_after>
|
import numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from astropy.coordinates import get_body_barycentric, ICRS, GCRS, CartesianRepresentation
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
r = get_body_barycentric(body.name, epoch)
r = (ICRS(x=r.x, y=r.y, z=r.z, representation_type=CartesianRepresentation)
.transform_to(GCRS(obstime=epoch))
.represent_as(CartesianRepresentation)
)
r_values[i] = r.xyz.to(u.km)
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
|
import numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from poliastro.bodies import Moon
from poliastro.twobody.orbit import Orbit
from poliastro.coordinates import transform
from astropy.coordinates import ICRS, GCRS
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
body_t = Orbit.from_body_ephem(body, epoch)
if body != Moon:
body_t = transform(body_t, ICRS, GCRS)
r_values[i] = body_t.r
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
Fix 3rd body tests for Moon, simplify interpolant codeimport numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from astropy.coordinates import get_body_barycentric, ICRS, GCRS, CartesianRepresentation
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
r = get_body_barycentric(body.name, epoch)
r = (ICRS(x=r.x, y=r.y, z=r.z, representation_type=CartesianRepresentation)
.transform_to(GCRS(obstime=epoch))
.represent_as(CartesianRepresentation)
)
r_values[i] = r.xyz.to(u.km)
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
|
<commit_before>import numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from poliastro.bodies import Moon
from poliastro.twobody.orbit import Orbit
from poliastro.coordinates import transform
from astropy.coordinates import ICRS, GCRS
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
body_t = Orbit.from_body_ephem(body, epoch)
if body != Moon:
body_t = transform(body_t, ICRS, GCRS)
r_values[i] = body_t.r
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
<commit_msg>Fix 3rd body tests for Moon, simplify interpolant code<commit_after>import numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from astropy.coordinates import get_body_barycentric, ICRS, GCRS, CartesianRepresentation
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
r = get_body_barycentric(body.name, epoch)
r = (ICRS(x=r.x, y=r.y, z=r.z, representation_type=CartesianRepresentation)
.transform_to(GCRS(obstime=epoch))
.represent_as(CartesianRepresentation)
)
r_values[i] = r.xyz.to(u.km)
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
|
89190bef876b17e56c4dee5796be9f64b7e1e1a7
|
logspit/streamers/syslog.py
|
logspit/streamers/syslog.py
|
__author__ = 'nhumrich'
import os
import socket
syslog_host = os.getenv('SYSLOG_HOST', 'localhost')
syslog_port = os.getenv('SYSLOG_PORT', 514)
debug = os.getenv('DEBUG', 'False')
def send(log):
if isinstance(log, str):
log = log.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(log, (syslog_host, syslog_port))
if bool(debug):
print(log)
# if __name__ == "__main__":
# send('this is a python test')
|
__author__ = 'nhumrich'
import os
import socket
syslog_host = os.getenv('SYSLOG_HOST', 'localhost')
syslog_port = os.getenv('SYSLOG_PORT', 514)
debug = os.getenv('DEBUG', 'False')
def send(log):
if isinstance(log, str):
log = log.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(log, (syslog_host, syslog_port))
if debug.lower() == 'true':
print(log)
# if __name__ == "__main__":
# send('this is a python test')
|
Fix debug flag to actually work
|
Fix debug flag to actually work
|
Python
|
apache-2.0
|
CanopyTax/logspit
|
__author__ = 'nhumrich'
import os
import socket
syslog_host = os.getenv('SYSLOG_HOST', 'localhost')
syslog_port = os.getenv('SYSLOG_PORT', 514)
debug = os.getenv('DEBUG', 'False')
def send(log):
if isinstance(log, str):
log = log.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(log, (syslog_host, syslog_port))
if bool(debug):
print(log)
# if __name__ == "__main__":
# send('this is a python test')
Fix debug flag to actually work
|
__author__ = 'nhumrich'
import os
import socket
syslog_host = os.getenv('SYSLOG_HOST', 'localhost')
syslog_port = os.getenv('SYSLOG_PORT', 514)
debug = os.getenv('DEBUG', 'False')
def send(log):
if isinstance(log, str):
log = log.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(log, (syslog_host, syslog_port))
if debug.lower() == 'true':
print(log)
# if __name__ == "__main__":
# send('this is a python test')
|
<commit_before>__author__ = 'nhumrich'
import os
import socket
syslog_host = os.getenv('SYSLOG_HOST', 'localhost')
syslog_port = os.getenv('SYSLOG_PORT', 514)
debug = os.getenv('DEBUG', 'False')
def send(log):
if isinstance(log, str):
log = log.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(log, (syslog_host, syslog_port))
if bool(debug):
print(log)
# if __name__ == "__main__":
# send('this is a python test')
<commit_msg>Fix debug flag to actually work<commit_after>
|
__author__ = 'nhumrich'
import os
import socket
syslog_host = os.getenv('SYSLOG_HOST', 'localhost')
syslog_port = os.getenv('SYSLOG_PORT', 514)
debug = os.getenv('DEBUG', 'False')
def send(log):
if isinstance(log, str):
log = log.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(log, (syslog_host, syslog_port))
if debug.lower() == 'true':
print(log)
# if __name__ == "__main__":
# send('this is a python test')
|
__author__ = 'nhumrich'
import os
import socket
syslog_host = os.getenv('SYSLOG_HOST', 'localhost')
syslog_port = os.getenv('SYSLOG_PORT', 514)
debug = os.getenv('DEBUG', 'False')
def send(log):
if isinstance(log, str):
log = log.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(log, (syslog_host, syslog_port))
if bool(debug):
print(log)
# if __name__ == "__main__":
# send('this is a python test')
Fix debug flag to actually work__author__ = 'nhumrich'
import os
import socket
syslog_host = os.getenv('SYSLOG_HOST', 'localhost')
syslog_port = os.getenv('SYSLOG_PORT', 514)
debug = os.getenv('DEBUG', 'False')
def send(log):
if isinstance(log, str):
log = log.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(log, (syslog_host, syslog_port))
if debug.lower() == 'true':
print(log)
# if __name__ == "__main__":
# send('this is a python test')
|
<commit_before>__author__ = 'nhumrich'
import os
import socket
syslog_host = os.getenv('SYSLOG_HOST', 'localhost')
syslog_port = os.getenv('SYSLOG_PORT', 514)
debug = os.getenv('DEBUG', 'False')
def send(log):
if isinstance(log, str):
log = log.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(log, (syslog_host, syslog_port))
if bool(debug):
print(log)
# if __name__ == "__main__":
# send('this is a python test')
<commit_msg>Fix debug flag to actually work<commit_after>__author__ = 'nhumrich'
import os
import socket
syslog_host = os.getenv('SYSLOG_HOST', 'localhost')
syslog_port = os.getenv('SYSLOG_PORT', 514)
debug = os.getenv('DEBUG', 'False')
def send(log):
if isinstance(log, str):
log = log.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(log, (syslog_host, syslog_port))
if debug.lower() == 'true':
print(log)
# if __name__ == "__main__":
# send('this is a python test')
|
081dcb1a6f3531249f8948b019d8fdc4175dbe61
|
makerscience_profile/api.py
|
makerscience_profile/api.py
|
from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
return bundle
|
from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
bundle.data["full_name"] = "%s %s" % (bundle.obj.parent.user.first_name, bundle.obj.parent.user.last_name)
return bundle
|
Add fullname in REST response
|
Add fullname in REST response
|
Python
|
agpl-3.0
|
atiberghien/makerscience-server,atiberghien/makerscience-server
|
from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
return bundle
Add fullname in REST response
|
from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
bundle.data["full_name"] = "%s %s" % (bundle.obj.parent.user.first_name, bundle.obj.parent.user.last_name)
return bundle
|
<commit_before>from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
return bundle
<commit_msg>Add fullname in REST response<commit_after>
|
from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
bundle.data["full_name"] = "%s %s" % (bundle.obj.parent.user.first_name, bundle.obj.parent.user.last_name)
return bundle
|
from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
return bundle
Add fullname in REST responsefrom .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
bundle.data["full_name"] = "%s %s" % (bundle.obj.parent.user.first_name, bundle.obj.parent.user.last_name)
return bundle
|
<commit_before>from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
return bundle
<commit_msg>Add fullname in REST response<commit_after>from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
bundle.data["full_name"] = "%s %s" % (bundle.obj.parent.user.first_name, bundle.obj.parent.user.last_name)
return bundle
|
3af9e49d36aedd08d075c4aae027b7d7565d4579
|
src/redisboard/views.py
|
src/redisboard/views.py
|
from django.shortcuts import render
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = [name[2:] for name in conn.info() if name.startswith('db')]
database_details = {}
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
|
from django.shortcuts import render
from django.utils.datastructures import SortedDict
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = sorted(name[2:] for name in conn.info() if name.startswith('db'))
database_details = SortedDict()
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
|
Sort the database order in the inspect page.
|
Sort the database order in the inspect page.
|
Python
|
bsd-2-clause
|
ionelmc/django-redisboard,jolks/django-redisboard,jolks/django-redisboard,artscoop/django-redisboard,artscoop/django-redisboard,ionelmc/django-redisboard,jolks/django-redisboard,artscoop/django-redisboard
|
from django.shortcuts import render
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = [name[2:] for name in conn.info() if name.startswith('db')]
database_details = {}
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
Sort the database order in the inspect page.
|
from django.shortcuts import render
from django.utils.datastructures import SortedDict
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = sorted(name[2:] for name in conn.info() if name.startswith('db'))
database_details = SortedDict()
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
|
<commit_before>from django.shortcuts import render
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = [name[2:] for name in conn.info() if name.startswith('db')]
database_details = {}
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
<commit_msg>Sort the database order in the inspect page.<commit_after>
|
from django.shortcuts import render
from django.utils.datastructures import SortedDict
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = sorted(name[2:] for name in conn.info() if name.startswith('db'))
database_details = SortedDict()
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
|
from django.shortcuts import render
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = [name[2:] for name in conn.info() if name.startswith('db')]
database_details = {}
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
Sort the database order in the inspect page.from django.shortcuts import render
from django.utils.datastructures import SortedDict
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = sorted(name[2:] for name in conn.info() if name.startswith('db'))
database_details = SortedDict()
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
|
<commit_before>from django.shortcuts import render
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = [name[2:] for name in conn.info() if name.startswith('db')]
database_details = {}
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
<commit_msg>Sort the database order in the inspect page.<commit_after>from django.shortcuts import render
from django.utils.datastructures import SortedDict
def _get_key_details(conn, db):
conn.execute_command('SELECT', db)
keys = conn.keys()
key_details = {}
for key in keys:
details = conn.execute_command('DEBUG', 'OBJECT', key)
key_details[key] = {
'type': conn.type(key),
'details': dict(
i.split(':') for i in details.split() if ':' in i
),
'ttl': conn.ttl(key),
}
return key_details
def inspect(request, server):
stats = server.stats
if stats['status'] == 'UP':
conn = server.connection
databases = sorted(name[2:] for name in conn.info() if name.startswith('db'))
database_details = SortedDict()
for db in databases:
database_details[db] = _get_key_details(conn, db)
else:
database_details = {}
return render(request, "redisboard/inspect.html", {
'databases': database_details,
'original': server,
'stats': stats,
'app_label': 'redisboard',
})
|
4b097d7d343523c99b50dc910b62bf29eb7c4081
|
vint/linting/policy/prohibit_implicit_scope_variable.py
|
vint/linting/policy/prohibit_implicit_scope_variable.py
|
from vint.ast.node_type import NodeType
from vint.linting.level import Level
from vint.linting.policy.abstract_policy import AbstractPolicy
from vint.linting.policy_registry import register_policy
from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility
@register_policy
class ProhibitImplicitScopeVariable(AbstractPolicy):
def __init__(self):
super(ProhibitImplicitScopeVariable, self).__init__()
self.reference = 'Anti-pattern of vimrc (Scope of identifier)'
self.level = Level.STYLE_PROBLEM
def listen_node_types(self):
return [NodeType.IDENTIFIER]
def is_valid(self, identifier, lint_context):
""" Whether the identifier has a scope prefix. """
linter_config = lint_context['config']
scope_plugin = lint_context['plugins']['scope']
explicity = scope_plugin.get_explicity_of_scope_visibility(identifier)
is_autoload = scope_plugin.is_autoload_identifier(identifier)
try:
suppress_autoload = linter_config['policies'][self.name]['suppress_autoload']
except KeyError:
suppress_autoload = False
is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or
is_autoload and suppress_autoload)
if not is_valid:
self._make_description(identifier, scope_plugin)
return is_valid
def _make_description(self, identifier, scope_plugin):
self.description = 'Make the scope explicit like `{good_example}`'.format(
good_example=scope_plugin.normalize_variable_name(identifier)
)
|
from vint.ast.node_type import NodeType
from vint.linting.level import Level
from vint.linting.policy.abstract_policy import AbstractPolicy
from vint.linting.policy_registry import register_policy
from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility
@register_policy
class ProhibitImplicitScopeVariable(AbstractPolicy):
def __init__(self):
super(ProhibitImplicitScopeVariable, self).__init__()
self.reference = 'Anti-pattern of vimrc (Scope of identifier)'
self.level = Level.STYLE_PROBLEM
def listen_node_types(self):
return [NodeType.IDENTIFIER]
def is_valid(self, identifier, lint_context):
""" Whether the identifier has a scope prefix. """
scope_plugin = lint_context['plugins']['scope']
explicity = scope_plugin.get_explicity_of_scope_visibility(identifier)
is_autoload = scope_plugin.is_autoload_identifier(identifier)
config_dict = lint_context['config']
suppress_autoload = self.get_policy_option(config_dict, 'suppress_autoload', False)
is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or
is_autoload and suppress_autoload)
if not is_valid:
self._make_description(identifier, scope_plugin)
return is_valid
def _make_description(self, identifier, scope_plugin):
self.description = 'Make the scope explicit like `{good_example}`'.format(
good_example=scope_plugin.normalize_variable_name(identifier)
)
|
Replace try..except with get_policy_option call
|
Replace try..except with get_policy_option call
|
Python
|
mit
|
RianFuro/vint,Kuniwak/vint,Kuniwak/vint,RianFuro/vint
|
from vint.ast.node_type import NodeType
from vint.linting.level import Level
from vint.linting.policy.abstract_policy import AbstractPolicy
from vint.linting.policy_registry import register_policy
from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility
@register_policy
class ProhibitImplicitScopeVariable(AbstractPolicy):
def __init__(self):
super(ProhibitImplicitScopeVariable, self).__init__()
self.reference = 'Anti-pattern of vimrc (Scope of identifier)'
self.level = Level.STYLE_PROBLEM
def listen_node_types(self):
return [NodeType.IDENTIFIER]
def is_valid(self, identifier, lint_context):
""" Whether the identifier has a scope prefix. """
linter_config = lint_context['config']
scope_plugin = lint_context['plugins']['scope']
explicity = scope_plugin.get_explicity_of_scope_visibility(identifier)
is_autoload = scope_plugin.is_autoload_identifier(identifier)
try:
suppress_autoload = linter_config['policies'][self.name]['suppress_autoload']
except KeyError:
suppress_autoload = False
is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or
is_autoload and suppress_autoload)
if not is_valid:
self._make_description(identifier, scope_plugin)
return is_valid
def _make_description(self, identifier, scope_plugin):
self.description = 'Make the scope explicit like `{good_example}`'.format(
good_example=scope_plugin.normalize_variable_name(identifier)
)
Replace try..except with get_policy_option call
|
from vint.ast.node_type import NodeType
from vint.linting.level import Level
from vint.linting.policy.abstract_policy import AbstractPolicy
from vint.linting.policy_registry import register_policy
from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility
@register_policy
class ProhibitImplicitScopeVariable(AbstractPolicy):
def __init__(self):
super(ProhibitImplicitScopeVariable, self).__init__()
self.reference = 'Anti-pattern of vimrc (Scope of identifier)'
self.level = Level.STYLE_PROBLEM
def listen_node_types(self):
return [NodeType.IDENTIFIER]
def is_valid(self, identifier, lint_context):
""" Whether the identifier has a scope prefix. """
scope_plugin = lint_context['plugins']['scope']
explicity = scope_plugin.get_explicity_of_scope_visibility(identifier)
is_autoload = scope_plugin.is_autoload_identifier(identifier)
config_dict = lint_context['config']
suppress_autoload = self.get_policy_option(config_dict, 'suppress_autoload', False)
is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or
is_autoload and suppress_autoload)
if not is_valid:
self._make_description(identifier, scope_plugin)
return is_valid
def _make_description(self, identifier, scope_plugin):
self.description = 'Make the scope explicit like `{good_example}`'.format(
good_example=scope_plugin.normalize_variable_name(identifier)
)
|
<commit_before>from vint.ast.node_type import NodeType
from vint.linting.level import Level
from vint.linting.policy.abstract_policy import AbstractPolicy
from vint.linting.policy_registry import register_policy
from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility
@register_policy
class ProhibitImplicitScopeVariable(AbstractPolicy):
def __init__(self):
super(ProhibitImplicitScopeVariable, self).__init__()
self.reference = 'Anti-pattern of vimrc (Scope of identifier)'
self.level = Level.STYLE_PROBLEM
def listen_node_types(self):
return [NodeType.IDENTIFIER]
def is_valid(self, identifier, lint_context):
""" Whether the identifier has a scope prefix. """
linter_config = lint_context['config']
scope_plugin = lint_context['plugins']['scope']
explicity = scope_plugin.get_explicity_of_scope_visibility(identifier)
is_autoload = scope_plugin.is_autoload_identifier(identifier)
try:
suppress_autoload = linter_config['policies'][self.name]['suppress_autoload']
except KeyError:
suppress_autoload = False
is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or
is_autoload and suppress_autoload)
if not is_valid:
self._make_description(identifier, scope_plugin)
return is_valid
def _make_description(self, identifier, scope_plugin):
self.description = 'Make the scope explicit like `{good_example}`'.format(
good_example=scope_plugin.normalize_variable_name(identifier)
)
<commit_msg>Replace try..except with get_policy_option call<commit_after>
|
from vint.ast.node_type import NodeType
from vint.linting.level import Level
from vint.linting.policy.abstract_policy import AbstractPolicy
from vint.linting.policy_registry import register_policy
from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility
@register_policy
class ProhibitImplicitScopeVariable(AbstractPolicy):
def __init__(self):
super(ProhibitImplicitScopeVariable, self).__init__()
self.reference = 'Anti-pattern of vimrc (Scope of identifier)'
self.level = Level.STYLE_PROBLEM
def listen_node_types(self):
return [NodeType.IDENTIFIER]
def is_valid(self, identifier, lint_context):
""" Whether the identifier has a scope prefix. """
scope_plugin = lint_context['plugins']['scope']
explicity = scope_plugin.get_explicity_of_scope_visibility(identifier)
is_autoload = scope_plugin.is_autoload_identifier(identifier)
config_dict = lint_context['config']
suppress_autoload = self.get_policy_option(config_dict, 'suppress_autoload', False)
is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or
is_autoload and suppress_autoload)
if not is_valid:
self._make_description(identifier, scope_plugin)
return is_valid
def _make_description(self, identifier, scope_plugin):
self.description = 'Make the scope explicit like `{good_example}`'.format(
good_example=scope_plugin.normalize_variable_name(identifier)
)
|
from vint.ast.node_type import NodeType
from vint.linting.level import Level
from vint.linting.policy.abstract_policy import AbstractPolicy
from vint.linting.policy_registry import register_policy
from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility
@register_policy
class ProhibitImplicitScopeVariable(AbstractPolicy):
def __init__(self):
super(ProhibitImplicitScopeVariable, self).__init__()
self.reference = 'Anti-pattern of vimrc (Scope of identifier)'
self.level = Level.STYLE_PROBLEM
def listen_node_types(self):
return [NodeType.IDENTIFIER]
def is_valid(self, identifier, lint_context):
""" Whether the identifier has a scope prefix. """
linter_config = lint_context['config']
scope_plugin = lint_context['plugins']['scope']
explicity = scope_plugin.get_explicity_of_scope_visibility(identifier)
is_autoload = scope_plugin.is_autoload_identifier(identifier)
try:
suppress_autoload = linter_config['policies'][self.name]['suppress_autoload']
except KeyError:
suppress_autoload = False
is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or
is_autoload and suppress_autoload)
if not is_valid:
self._make_description(identifier, scope_plugin)
return is_valid
def _make_description(self, identifier, scope_plugin):
self.description = 'Make the scope explicit like `{good_example}`'.format(
good_example=scope_plugin.normalize_variable_name(identifier)
)
Replace try..except with get_policy_option callfrom vint.ast.node_type import NodeType
from vint.linting.level import Level
from vint.linting.policy.abstract_policy import AbstractPolicy
from vint.linting.policy_registry import register_policy
from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility
@register_policy
class ProhibitImplicitScopeVariable(AbstractPolicy):
def __init__(self):
super(ProhibitImplicitScopeVariable, self).__init__()
self.reference = 'Anti-pattern of vimrc (Scope of identifier)'
self.level = Level.STYLE_PROBLEM
def listen_node_types(self):
return [NodeType.IDENTIFIER]
def is_valid(self, identifier, lint_context):
""" Whether the identifier has a scope prefix. """
scope_plugin = lint_context['plugins']['scope']
explicity = scope_plugin.get_explicity_of_scope_visibility(identifier)
is_autoload = scope_plugin.is_autoload_identifier(identifier)
config_dict = lint_context['config']
suppress_autoload = self.get_policy_option(config_dict, 'suppress_autoload', False)
is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or
is_autoload and suppress_autoload)
if not is_valid:
self._make_description(identifier, scope_plugin)
return is_valid
def _make_description(self, identifier, scope_plugin):
self.description = 'Make the scope explicit like `{good_example}`'.format(
good_example=scope_plugin.normalize_variable_name(identifier)
)
|
<commit_before>from vint.ast.node_type import NodeType
from vint.linting.level import Level
from vint.linting.policy.abstract_policy import AbstractPolicy
from vint.linting.policy_registry import register_policy
from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility
@register_policy
class ProhibitImplicitScopeVariable(AbstractPolicy):
def __init__(self):
super(ProhibitImplicitScopeVariable, self).__init__()
self.reference = 'Anti-pattern of vimrc (Scope of identifier)'
self.level = Level.STYLE_PROBLEM
def listen_node_types(self):
return [NodeType.IDENTIFIER]
def is_valid(self, identifier, lint_context):
""" Whether the identifier has a scope prefix. """
linter_config = lint_context['config']
scope_plugin = lint_context['plugins']['scope']
explicity = scope_plugin.get_explicity_of_scope_visibility(identifier)
is_autoload = scope_plugin.is_autoload_identifier(identifier)
try:
suppress_autoload = linter_config['policies'][self.name]['suppress_autoload']
except KeyError:
suppress_autoload = False
is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or
is_autoload and suppress_autoload)
if not is_valid:
self._make_description(identifier, scope_plugin)
return is_valid
def _make_description(self, identifier, scope_plugin):
self.description = 'Make the scope explicit like `{good_example}`'.format(
good_example=scope_plugin.normalize_variable_name(identifier)
)
<commit_msg>Replace try..except with get_policy_option call<commit_after>from vint.ast.node_type import NodeType
from vint.linting.level import Level
from vint.linting.policy.abstract_policy import AbstractPolicy
from vint.linting.policy_registry import register_policy
from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility
@register_policy
class ProhibitImplicitScopeVariable(AbstractPolicy):
def __init__(self):
super(ProhibitImplicitScopeVariable, self).__init__()
self.reference = 'Anti-pattern of vimrc (Scope of identifier)'
self.level = Level.STYLE_PROBLEM
def listen_node_types(self):
return [NodeType.IDENTIFIER]
def is_valid(self, identifier, lint_context):
""" Whether the identifier has a scope prefix. """
scope_plugin = lint_context['plugins']['scope']
explicity = scope_plugin.get_explicity_of_scope_visibility(identifier)
is_autoload = scope_plugin.is_autoload_identifier(identifier)
config_dict = lint_context['config']
suppress_autoload = self.get_policy_option(config_dict, 'suppress_autoload', False)
is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or
is_autoload and suppress_autoload)
if not is_valid:
self._make_description(identifier, scope_plugin)
return is_valid
def _make_description(self, identifier, scope_plugin):
self.description = 'Make the scope explicit like `{good_example}`'.format(
good_example=scope_plugin.normalize_variable_name(identifier)
)
|
ef102617e5d73b32c43e4e9422a19917a1d3d717
|
molo/polls/wagtail_hooks.py
|
molo/polls/wagtail_hooks.py
|
from django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
|
from django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists()\
and not User.objects.filter(
pk=request.user.pk, groups__name='M&E Expert').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
|
Add M&E Expert to polls entries permissions
|
Add M&E Expert to polls entries permissions
|
Python
|
bsd-2-clause
|
praekelt/molo.polls,praekelt/molo.polls
|
from django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
Add M&E Expert to polls entries permissions
|
from django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists()\
and not User.objects.filter(
pk=request.user.pk, groups__name='M&E Expert').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
|
<commit_before>from django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
<commit_msg>Add M&E Expert to polls entries permissions<commit_after>
|
from django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists()\
and not User.objects.filter(
pk=request.user.pk, groups__name='M&E Expert').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
|
from django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
Add M&E Expert to polls entries permissionsfrom django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists()\
and not User.objects.filter(
pk=request.user.pk, groups__name='M&E Expert').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
|
<commit_before>from django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
<commit_msg>Add M&E Expert to polls entries permissions<commit_after>from django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists()\
and not User.objects.filter(
pk=request.user.pk, groups__name='M&E Expert').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
|
932606e41fa5289551a026ae993ececbd117ca7d
|
openedx/core/djangoapps/appsembler/tpa_admin/serializers.py
|
openedx/core/djangoapps/appsembler/tpa_admin/serializers.py
|
import json
from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig
from rest_framework import serializers
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return json.dumps(data)
def to_representation(self, value):
return value
class SAMLConfigurationSerializer(serializers.ModelSerializer):
other_config_str = JSONSerializerField()
class Meta:
model = SAMLConfiguration
fields = (
'id', 'site', 'enabled','entity_id', 'private_key', 'public_key', 'org_info_str', 'other_config_str'
)
class SAMLProviderConfigSerializer(serializers.ModelSerializer):
class Meta:
model = SAMLProviderConfig
fields = (
'id', 'site', 'enabled', 'name', 'icon_class', 'icon_image', 'secondary', 'skip_registration_form',
'visible', 'skip_email_verification', 'idp_slug', 'entity_id', 'metadata_source', 'attr_user_permanent_id',
'attr_full_name', 'attr_first_name', 'attr_last_name', 'attr_username', 'attr_email', 'other_settings'
)
|
import json
from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig, SAMLProviderData
from rest_framework import serializers
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return json.dumps(data)
def to_representation(self, value):
return value
class SAMLConfigurationSerializer(serializers.ModelSerializer):
other_config_str = JSONSerializerField()
class Meta:
model = SAMLConfiguration
fields = (
'id', 'site', 'enabled','entity_id', 'private_key', 'public_key', 'org_info_str', 'other_config_str'
)
class SAMLProviderConfigSerializer(serializers.ModelSerializer):
metadata_ready = serializers.SerializerMethodField()
class Meta:
model = SAMLProviderConfig
fields = (
'id', 'site', 'enabled', 'name', 'icon_class', 'icon_image', 'secondary', 'skip_registration_form',
'visible', 'skip_email_verification', 'idp_slug', 'entity_id', 'metadata_source', 'attr_user_permanent_id',
'attr_full_name', 'attr_first_name', 'attr_last_name', 'attr_username', 'attr_email', 'other_settings',
'metadata_ready'
)
def get_metadata_ready(self, obj):
""" Do we have cached metadata for this SAML provider? """
if not obj.is_active:
return None # N/A
data = SAMLProviderData.current(obj.entity_id)
return bool(data and data.is_valid())
|
Add metadata ready field to IdP serializer
|
Add metadata ready field to IdP serializer
|
Python
|
agpl-3.0
|
appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform
|
import json
from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig
from rest_framework import serializers
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return json.dumps(data)
def to_representation(self, value):
return value
class SAMLConfigurationSerializer(serializers.ModelSerializer):
other_config_str = JSONSerializerField()
class Meta:
model = SAMLConfiguration
fields = (
'id', 'site', 'enabled','entity_id', 'private_key', 'public_key', 'org_info_str', 'other_config_str'
)
class SAMLProviderConfigSerializer(serializers.ModelSerializer):
class Meta:
model = SAMLProviderConfig
fields = (
'id', 'site', 'enabled', 'name', 'icon_class', 'icon_image', 'secondary', 'skip_registration_form',
'visible', 'skip_email_verification', 'idp_slug', 'entity_id', 'metadata_source', 'attr_user_permanent_id',
'attr_full_name', 'attr_first_name', 'attr_last_name', 'attr_username', 'attr_email', 'other_settings'
)
Add metadata ready field to IdP serializer
|
import json
from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig, SAMLProviderData
from rest_framework import serializers
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return json.dumps(data)
def to_representation(self, value):
return value
class SAMLConfigurationSerializer(serializers.ModelSerializer):
other_config_str = JSONSerializerField()
class Meta:
model = SAMLConfiguration
fields = (
'id', 'site', 'enabled','entity_id', 'private_key', 'public_key', 'org_info_str', 'other_config_str'
)
class SAMLProviderConfigSerializer(serializers.ModelSerializer):
metadata_ready = serializers.SerializerMethodField()
class Meta:
model = SAMLProviderConfig
fields = (
'id', 'site', 'enabled', 'name', 'icon_class', 'icon_image', 'secondary', 'skip_registration_form',
'visible', 'skip_email_verification', 'idp_slug', 'entity_id', 'metadata_source', 'attr_user_permanent_id',
'attr_full_name', 'attr_first_name', 'attr_last_name', 'attr_username', 'attr_email', 'other_settings',
'metadata_ready'
)
def get_metadata_ready(self, obj):
""" Do we have cached metadata for this SAML provider? """
if not obj.is_active:
return None # N/A
data = SAMLProviderData.current(obj.entity_id)
return bool(data and data.is_valid())
|
<commit_before>import json
from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig
from rest_framework import serializers
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return json.dumps(data)
def to_representation(self, value):
return value
class SAMLConfigurationSerializer(serializers.ModelSerializer):
other_config_str = JSONSerializerField()
class Meta:
model = SAMLConfiguration
fields = (
'id', 'site', 'enabled','entity_id', 'private_key', 'public_key', 'org_info_str', 'other_config_str'
)
class SAMLProviderConfigSerializer(serializers.ModelSerializer):
class Meta:
model = SAMLProviderConfig
fields = (
'id', 'site', 'enabled', 'name', 'icon_class', 'icon_image', 'secondary', 'skip_registration_form',
'visible', 'skip_email_verification', 'idp_slug', 'entity_id', 'metadata_source', 'attr_user_permanent_id',
'attr_full_name', 'attr_first_name', 'attr_last_name', 'attr_username', 'attr_email', 'other_settings'
)
<commit_msg>Add metadata ready field to IdP serializer<commit_after>
|
import json
from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig, SAMLProviderData
from rest_framework import serializers
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return json.dumps(data)
def to_representation(self, value):
return value
class SAMLConfigurationSerializer(serializers.ModelSerializer):
other_config_str = JSONSerializerField()
class Meta:
model = SAMLConfiguration
fields = (
'id', 'site', 'enabled','entity_id', 'private_key', 'public_key', 'org_info_str', 'other_config_str'
)
class SAMLProviderConfigSerializer(serializers.ModelSerializer):
metadata_ready = serializers.SerializerMethodField()
class Meta:
model = SAMLProviderConfig
fields = (
'id', 'site', 'enabled', 'name', 'icon_class', 'icon_image', 'secondary', 'skip_registration_form',
'visible', 'skip_email_verification', 'idp_slug', 'entity_id', 'metadata_source', 'attr_user_permanent_id',
'attr_full_name', 'attr_first_name', 'attr_last_name', 'attr_username', 'attr_email', 'other_settings',
'metadata_ready'
)
def get_metadata_ready(self, obj):
""" Do we have cached metadata for this SAML provider? """
if not obj.is_active:
return None # N/A
data = SAMLProviderData.current(obj.entity_id)
return bool(data and data.is_valid())
|
import json
from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig
from rest_framework import serializers
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return json.dumps(data)
def to_representation(self, value):
return value
class SAMLConfigurationSerializer(serializers.ModelSerializer):
other_config_str = JSONSerializerField()
class Meta:
model = SAMLConfiguration
fields = (
'id', 'site', 'enabled','entity_id', 'private_key', 'public_key', 'org_info_str', 'other_config_str'
)
class SAMLProviderConfigSerializer(serializers.ModelSerializer):
class Meta:
model = SAMLProviderConfig
fields = (
'id', 'site', 'enabled', 'name', 'icon_class', 'icon_image', 'secondary', 'skip_registration_form',
'visible', 'skip_email_verification', 'idp_slug', 'entity_id', 'metadata_source', 'attr_user_permanent_id',
'attr_full_name', 'attr_first_name', 'attr_last_name', 'attr_username', 'attr_email', 'other_settings'
)
Add metadata ready field to IdP serializerimport json
from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig, SAMLProviderData
from rest_framework import serializers
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return json.dumps(data)
def to_representation(self, value):
return value
class SAMLConfigurationSerializer(serializers.ModelSerializer):
other_config_str = JSONSerializerField()
class Meta:
model = SAMLConfiguration
fields = (
'id', 'site', 'enabled','entity_id', 'private_key', 'public_key', 'org_info_str', 'other_config_str'
)
class SAMLProviderConfigSerializer(serializers.ModelSerializer):
metadata_ready = serializers.SerializerMethodField()
class Meta:
model = SAMLProviderConfig
fields = (
'id', 'site', 'enabled', 'name', 'icon_class', 'icon_image', 'secondary', 'skip_registration_form',
'visible', 'skip_email_verification', 'idp_slug', 'entity_id', 'metadata_source', 'attr_user_permanent_id',
'attr_full_name', 'attr_first_name', 'attr_last_name', 'attr_username', 'attr_email', 'other_settings',
'metadata_ready'
)
def get_metadata_ready(self, obj):
""" Do we have cached metadata for this SAML provider? """
if not obj.is_active:
return None # N/A
data = SAMLProviderData.current(obj.entity_id)
return bool(data and data.is_valid())
|
<commit_before>import json
from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig
from rest_framework import serializers
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return json.dumps(data)
def to_representation(self, value):
return value
class SAMLConfigurationSerializer(serializers.ModelSerializer):
other_config_str = JSONSerializerField()
class Meta:
model = SAMLConfiguration
fields = (
'id', 'site', 'enabled','entity_id', 'private_key', 'public_key', 'org_info_str', 'other_config_str'
)
class SAMLProviderConfigSerializer(serializers.ModelSerializer):
class Meta:
model = SAMLProviderConfig
fields = (
'id', 'site', 'enabled', 'name', 'icon_class', 'icon_image', 'secondary', 'skip_registration_form',
'visible', 'skip_email_verification', 'idp_slug', 'entity_id', 'metadata_source', 'attr_user_permanent_id',
'attr_full_name', 'attr_first_name', 'attr_last_name', 'attr_username', 'attr_email', 'other_settings'
)
<commit_msg>Add metadata ready field to IdP serializer<commit_after>import json
from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig, SAMLProviderData
from rest_framework import serializers
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return json.dumps(data)
def to_representation(self, value):
return value
class SAMLConfigurationSerializer(serializers.ModelSerializer):
other_config_str = JSONSerializerField()
class Meta:
model = SAMLConfiguration
fields = (
'id', 'site', 'enabled','entity_id', 'private_key', 'public_key', 'org_info_str', 'other_config_str'
)
class SAMLProviderConfigSerializer(serializers.ModelSerializer):
metadata_ready = serializers.SerializerMethodField()
class Meta:
model = SAMLProviderConfig
fields = (
'id', 'site', 'enabled', 'name', 'icon_class', 'icon_image', 'secondary', 'skip_registration_form',
'visible', 'skip_email_verification', 'idp_slug', 'entity_id', 'metadata_source', 'attr_user_permanent_id',
'attr_full_name', 'attr_first_name', 'attr_last_name', 'attr_username', 'attr_email', 'other_settings',
'metadata_ready'
)
def get_metadata_ready(self, obj):
""" Do we have cached metadata for this SAML provider? """
if not obj.is_active:
return None # N/A
data = SAMLProviderData.current(obj.entity_id)
return bool(data and data.is_valid())
|
d1941980e48e738eaf6231a630595d85eeadf390
|
readthedocs/config/models.py
|
readthedocs/config/models.py
|
"""Models for the response of the configuration object."""
from __future__ import division, print_function, unicode_literals
from readthedocs.config.utils import to_dict
class Base(object):
"""
Base class for every configuration.
Each inherited class should define
its attibutes in the `__slots__` attribute.
"""
def __init__(self, **kwargs):
for name in self.__slots__:
setattr(self, name, kwargs[name])
def as_dict(self):
return {
name: to_dict(getattr(self, name))
for name in self.__slots__
}
class Build(Base):
__slots__ = ('image',)
class Python(Base):
__slots__ = ('version', 'install', 'use_system_site_packages')
class PythonInstallRequirements(Base):
__slots__ = ('requirements',)
class PythonInstall(Base):
__slots__ = ('path', 'method', 'extra_requirements',)
class Conda(Base):
__slots__ = ('environment',)
class Sphinx(Base):
__slots__ = ('builder', 'configuration', 'fail_on_warning')
class Mkdocs(Base):
__slots__ = ('configuration', 'fail_on_warning')
class Submodules(Base):
__slots__ = ('include', 'exclude', 'recursive')
|
"""Models for the response of the configuration object."""
from __future__ import division, print_function, unicode_literals
from readthedocs.config.utils import to_dict
class Base(object):
"""
Base class for every configuration.
Each inherited class should define
its attibutes in the `__slots__` attribute.
We are using `__slots__` so we can't add more attributes by mistake,
this is similar to a namedtuple.
"""
def __init__(self, **kwargs):
for name in self.__slots__:
setattr(self, name, kwargs[name])
def as_dict(self):
return {
name: to_dict(getattr(self, name))
for name in self.__slots__
}
class Build(Base):
__slots__ = ('image',)
class Python(Base):
__slots__ = ('version', 'install', 'use_system_site_packages')
class PythonInstallRequirements(Base):
__slots__ = ('requirements',)
class PythonInstall(Base):
__slots__ = ('path', 'method', 'extra_requirements',)
class Conda(Base):
__slots__ = ('environment',)
class Sphinx(Base):
__slots__ = ('builder', 'configuration', 'fail_on_warning')
class Mkdocs(Base):
__slots__ = ('configuration', 'fail_on_warning')
class Submodules(Base):
__slots__ = ('include', 'exclude', 'recursive')
|
Add explanation about using __slots__
|
Add explanation about using __slots__
|
Python
|
mit
|
rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org
|
"""Models for the response of the configuration object."""
from __future__ import division, print_function, unicode_literals
from readthedocs.config.utils import to_dict
class Base(object):
"""
Base class for every configuration.
Each inherited class should define
its attibutes in the `__slots__` attribute.
"""
def __init__(self, **kwargs):
for name in self.__slots__:
setattr(self, name, kwargs[name])
def as_dict(self):
return {
name: to_dict(getattr(self, name))
for name in self.__slots__
}
class Build(Base):
__slots__ = ('image',)
class Python(Base):
__slots__ = ('version', 'install', 'use_system_site_packages')
class PythonInstallRequirements(Base):
__slots__ = ('requirements',)
class PythonInstall(Base):
__slots__ = ('path', 'method', 'extra_requirements',)
class Conda(Base):
__slots__ = ('environment',)
class Sphinx(Base):
__slots__ = ('builder', 'configuration', 'fail_on_warning')
class Mkdocs(Base):
__slots__ = ('configuration', 'fail_on_warning')
class Submodules(Base):
__slots__ = ('include', 'exclude', 'recursive')
Add explanation about using __slots__
|
"""Models for the response of the configuration object."""
from __future__ import division, print_function, unicode_literals
from readthedocs.config.utils import to_dict
class Base(object):
"""
Base class for every configuration.
Each inherited class should define
its attibutes in the `__slots__` attribute.
We are using `__slots__` so we can't add more attributes by mistake,
this is similar to a namedtuple.
"""
def __init__(self, **kwargs):
for name in self.__slots__:
setattr(self, name, kwargs[name])
def as_dict(self):
return {
name: to_dict(getattr(self, name))
for name in self.__slots__
}
class Build(Base):
__slots__ = ('image',)
class Python(Base):
__slots__ = ('version', 'install', 'use_system_site_packages')
class PythonInstallRequirements(Base):
__slots__ = ('requirements',)
class PythonInstall(Base):
__slots__ = ('path', 'method', 'extra_requirements',)
class Conda(Base):
__slots__ = ('environment',)
class Sphinx(Base):
__slots__ = ('builder', 'configuration', 'fail_on_warning')
class Mkdocs(Base):
__slots__ = ('configuration', 'fail_on_warning')
class Submodules(Base):
__slots__ = ('include', 'exclude', 'recursive')
|
<commit_before>"""Models for the response of the configuration object."""
from __future__ import division, print_function, unicode_literals
from readthedocs.config.utils import to_dict
class Base(object):
"""
Base class for every configuration.
Each inherited class should define
its attibutes in the `__slots__` attribute.
"""
def __init__(self, **kwargs):
for name in self.__slots__:
setattr(self, name, kwargs[name])
def as_dict(self):
return {
name: to_dict(getattr(self, name))
for name in self.__slots__
}
class Build(Base):
__slots__ = ('image',)
class Python(Base):
__slots__ = ('version', 'install', 'use_system_site_packages')
class PythonInstallRequirements(Base):
__slots__ = ('requirements',)
class PythonInstall(Base):
__slots__ = ('path', 'method', 'extra_requirements',)
class Conda(Base):
__slots__ = ('environment',)
class Sphinx(Base):
__slots__ = ('builder', 'configuration', 'fail_on_warning')
class Mkdocs(Base):
__slots__ = ('configuration', 'fail_on_warning')
class Submodules(Base):
__slots__ = ('include', 'exclude', 'recursive')
<commit_msg>Add explanation about using __slots__<commit_after>
|
"""Models for the response of the configuration object."""
from __future__ import division, print_function, unicode_literals
from readthedocs.config.utils import to_dict
class Base(object):
"""
Base class for every configuration.
Each inherited class should define
its attibutes in the `__slots__` attribute.
We are using `__slots__` so we can't add more attributes by mistake,
this is similar to a namedtuple.
"""
def __init__(self, **kwargs):
for name in self.__slots__:
setattr(self, name, kwargs[name])
def as_dict(self):
return {
name: to_dict(getattr(self, name))
for name in self.__slots__
}
class Build(Base):
__slots__ = ('image',)
class Python(Base):
__slots__ = ('version', 'install', 'use_system_site_packages')
class PythonInstallRequirements(Base):
__slots__ = ('requirements',)
class PythonInstall(Base):
__slots__ = ('path', 'method', 'extra_requirements',)
class Conda(Base):
__slots__ = ('environment',)
class Sphinx(Base):
__slots__ = ('builder', 'configuration', 'fail_on_warning')
class Mkdocs(Base):
__slots__ = ('configuration', 'fail_on_warning')
class Submodules(Base):
__slots__ = ('include', 'exclude', 'recursive')
|
"""Models for the response of the configuration object."""
from __future__ import division, print_function, unicode_literals
from readthedocs.config.utils import to_dict
class Base(object):
"""
Base class for every configuration.
Each inherited class should define
its attibutes in the `__slots__` attribute.
"""
def __init__(self, **kwargs):
for name in self.__slots__:
setattr(self, name, kwargs[name])
def as_dict(self):
return {
name: to_dict(getattr(self, name))
for name in self.__slots__
}
class Build(Base):
__slots__ = ('image',)
class Python(Base):
__slots__ = ('version', 'install', 'use_system_site_packages')
class PythonInstallRequirements(Base):
__slots__ = ('requirements',)
class PythonInstall(Base):
__slots__ = ('path', 'method', 'extra_requirements',)
class Conda(Base):
__slots__ = ('environment',)
class Sphinx(Base):
__slots__ = ('builder', 'configuration', 'fail_on_warning')
class Mkdocs(Base):
__slots__ = ('configuration', 'fail_on_warning')
class Submodules(Base):
__slots__ = ('include', 'exclude', 'recursive')
Add explanation about using __slots__"""Models for the response of the configuration object."""
from __future__ import division, print_function, unicode_literals
from readthedocs.config.utils import to_dict
class Base(object):
"""
Base class for every configuration.
Each inherited class should define
its attibutes in the `__slots__` attribute.
We are using `__slots__` so we can't add more attributes by mistake,
this is similar to a namedtuple.
"""
def __init__(self, **kwargs):
for name in self.__slots__:
setattr(self, name, kwargs[name])
def as_dict(self):
return {
name: to_dict(getattr(self, name))
for name in self.__slots__
}
class Build(Base):
__slots__ = ('image',)
class Python(Base):
__slots__ = ('version', 'install', 'use_system_site_packages')
class PythonInstallRequirements(Base):
__slots__ = ('requirements',)
class PythonInstall(Base):
__slots__ = ('path', 'method', 'extra_requirements',)
class Conda(Base):
__slots__ = ('environment',)
class Sphinx(Base):
__slots__ = ('builder', 'configuration', 'fail_on_warning')
class Mkdocs(Base):
__slots__ = ('configuration', 'fail_on_warning')
class Submodules(Base):
__slots__ = ('include', 'exclude', 'recursive')
|
<commit_before>"""Models for the response of the configuration object."""
from __future__ import division, print_function, unicode_literals
from readthedocs.config.utils import to_dict
class Base(object):
"""
Base class for every configuration.
Each inherited class should define
its attibutes in the `__slots__` attribute.
"""
def __init__(self, **kwargs):
for name in self.__slots__:
setattr(self, name, kwargs[name])
def as_dict(self):
return {
name: to_dict(getattr(self, name))
for name in self.__slots__
}
class Build(Base):
__slots__ = ('image',)
class Python(Base):
__slots__ = ('version', 'install', 'use_system_site_packages')
class PythonInstallRequirements(Base):
__slots__ = ('requirements',)
class PythonInstall(Base):
__slots__ = ('path', 'method', 'extra_requirements',)
class Conda(Base):
__slots__ = ('environment',)
class Sphinx(Base):
__slots__ = ('builder', 'configuration', 'fail_on_warning')
class Mkdocs(Base):
__slots__ = ('configuration', 'fail_on_warning')
class Submodules(Base):
__slots__ = ('include', 'exclude', 'recursive')
<commit_msg>Add explanation about using __slots__<commit_after>"""Models for the response of the configuration object."""
from __future__ import division, print_function, unicode_literals
from readthedocs.config.utils import to_dict
class Base(object):
"""
Base class for every configuration.
Each inherited class should define
its attibutes in the `__slots__` attribute.
We are using `__slots__` so we can't add more attributes by mistake,
this is similar to a namedtuple.
"""
def __init__(self, **kwargs):
for name in self.__slots__:
setattr(self, name, kwargs[name])
def as_dict(self):
return {
name: to_dict(getattr(self, name))
for name in self.__slots__
}
class Build(Base):
__slots__ = ('image',)
class Python(Base):
__slots__ = ('version', 'install', 'use_system_site_packages')
class PythonInstallRequirements(Base):
__slots__ = ('requirements',)
class PythonInstall(Base):
__slots__ = ('path', 'method', 'extra_requirements',)
class Conda(Base):
__slots__ = ('environment',)
class Sphinx(Base):
__slots__ = ('builder', 'configuration', 'fail_on_warning')
class Mkdocs(Base):
__slots__ = ('configuration', 'fail_on_warning')
class Submodules(Base):
__slots__ = ('include', 'exclude', 'recursive')
|
9a94e9e61a7bb1680265692eb7cdf926842aa766
|
streamline/__init__.py
|
streamline/__init__.py
|
from .base import RouteBase, NonIterableRouteBase
from .template import TemplateRoute, XHRPartialRoute, ROCARoute
from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute
__version__ = '1.0'
__author__ = 'Outernet Inc'
__all__ = (
RouteBase,
NonIterableRouteBase,
TemplateRoute,
XHRPartialRoute,
ROCARoute,
FormRoute,
TemplateFormRoute,
XHRPartialFormRoute,
)
|
from .base import RouteBase, NonIterableRouteBase
from .template import TemplateRoute, XHRPartialRoute, ROCARoute
from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute
__version__ = '1.0'
__author__ = 'Outernet Inc'
__all__ = (
'RouteBase',
'NonIterableRouteBase',
'TemplateRoute',
'XHRPartialRoute',
'ROCARoute',
'FormRoute',
'TemplateFormRoute',
'XHRPartialFormRoute',
)
|
Fix __all__ using objects instead of strings
|
Fix __all__ using objects instead of strings
Signed-off-by: Branko Vukelic <26059cc39872530f89fec69552bb1050e1cc2caa@outernet.is>
|
Python
|
bsd-2-clause
|
Outernet-Project/bottle-streamline
|
from .base import RouteBase, NonIterableRouteBase
from .template import TemplateRoute, XHRPartialRoute, ROCARoute
from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute
__version__ = '1.0'
__author__ = 'Outernet Inc'
__all__ = (
RouteBase,
NonIterableRouteBase,
TemplateRoute,
XHRPartialRoute,
ROCARoute,
FormRoute,
TemplateFormRoute,
XHRPartialFormRoute,
)
Fix __all__ using objects instead of strings
Signed-off-by: Branko Vukelic <26059cc39872530f89fec69552bb1050e1cc2caa@outernet.is>
|
from .base import RouteBase, NonIterableRouteBase
from .template import TemplateRoute, XHRPartialRoute, ROCARoute
from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute
__version__ = '1.0'
__author__ = 'Outernet Inc'
__all__ = (
'RouteBase',
'NonIterableRouteBase',
'TemplateRoute',
'XHRPartialRoute',
'ROCARoute',
'FormRoute',
'TemplateFormRoute',
'XHRPartialFormRoute',
)
|
<commit_before>from .base import RouteBase, NonIterableRouteBase
from .template import TemplateRoute, XHRPartialRoute, ROCARoute
from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute
__version__ = '1.0'
__author__ = 'Outernet Inc'
__all__ = (
RouteBase,
NonIterableRouteBase,
TemplateRoute,
XHRPartialRoute,
ROCARoute,
FormRoute,
TemplateFormRoute,
XHRPartialFormRoute,
)
<commit_msg>Fix __all__ using objects instead of strings
Signed-off-by: Branko Vukelic <26059cc39872530f89fec69552bb1050e1cc2caa@outernet.is><commit_after>
|
from .base import RouteBase, NonIterableRouteBase
from .template import TemplateRoute, XHRPartialRoute, ROCARoute
from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute
__version__ = '1.0'
__author__ = 'Outernet Inc'
__all__ = (
'RouteBase',
'NonIterableRouteBase',
'TemplateRoute',
'XHRPartialRoute',
'ROCARoute',
'FormRoute',
'TemplateFormRoute',
'XHRPartialFormRoute',
)
|
from .base import RouteBase, NonIterableRouteBase
from .template import TemplateRoute, XHRPartialRoute, ROCARoute
from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute
__version__ = '1.0'
__author__ = 'Outernet Inc'
__all__ = (
RouteBase,
NonIterableRouteBase,
TemplateRoute,
XHRPartialRoute,
ROCARoute,
FormRoute,
TemplateFormRoute,
XHRPartialFormRoute,
)
Fix __all__ using objects instead of strings
Signed-off-by: Branko Vukelic <26059cc39872530f89fec69552bb1050e1cc2caa@outernet.is>from .base import RouteBase, NonIterableRouteBase
from .template import TemplateRoute, XHRPartialRoute, ROCARoute
from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute
__version__ = '1.0'
__author__ = 'Outernet Inc'
__all__ = (
'RouteBase',
'NonIterableRouteBase',
'TemplateRoute',
'XHRPartialRoute',
'ROCARoute',
'FormRoute',
'TemplateFormRoute',
'XHRPartialFormRoute',
)
|
<commit_before>from .base import RouteBase, NonIterableRouteBase
from .template import TemplateRoute, XHRPartialRoute, ROCARoute
from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute
__version__ = '1.0'
__author__ = 'Outernet Inc'
__all__ = (
RouteBase,
NonIterableRouteBase,
TemplateRoute,
XHRPartialRoute,
ROCARoute,
FormRoute,
TemplateFormRoute,
XHRPartialFormRoute,
)
<commit_msg>Fix __all__ using objects instead of strings
Signed-off-by: Branko Vukelic <26059cc39872530f89fec69552bb1050e1cc2caa@outernet.is><commit_after>from .base import RouteBase, NonIterableRouteBase
from .template import TemplateRoute, XHRPartialRoute, ROCARoute
from .forms import FormRoute, TemplateFormRoute, XHRPartialFormRoute
__version__ = '1.0'
__author__ = 'Outernet Inc'
__all__ = (
'RouteBase',
'NonIterableRouteBase',
'TemplateRoute',
'XHRPartialRoute',
'ROCARoute',
'FormRoute',
'TemplateFormRoute',
'XHRPartialFormRoute',
)
|
1da0edc9a3d6c8ea72b3d41c136907e035dff3c8
|
tba_config.py
|
tba_config.py
|
import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = BUILDSEASON
CONFIG["static_resource_version"] = 2
|
import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = KICKOFF
CONFIG["static_resource_version"] = 2
|
Revert back to kickoff for landing page
|
Revert back to kickoff for landing page
|
Python
|
mit
|
tsteward/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,phil-lopreiato/the-blue-alliance,bvisness/the-blue-alliance,1fish2/the-blue-alliance,nwalters512/the-blue-alliance,bvisness/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,1fish2/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,1fish2/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,1fish2/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,jaredhasenklein/the-blue-alliance,phil-lopreiato/the-blue-alliance,verycumbersome/the-blue-alliance,phil-lopreiato/the-blue-alliance,josephbisch/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,phil-lopreiato/the-blue-alliance,bvisness/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,bvisness/the-blue-alliance,synth3tk/the-blue-alliance,the-blue-alliance/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,1fish2/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,josephbisch/the-blue-alliance,bvisness/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance
|
import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = BUILDSEASON
CONFIG["static_resource_version"] = 2
Revert back to kickoff for landing page
|
import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = KICKOFF
CONFIG["static_resource_version"] = 2
|
<commit_before>import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = BUILDSEASON
CONFIG["static_resource_version"] = 2
<commit_msg>Revert back to kickoff for landing page<commit_after>
|
import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = KICKOFF
CONFIG["static_resource_version"] = 2
|
import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = BUILDSEASON
CONFIG["static_resource_version"] = 2
Revert back to kickoff for landing pageimport json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = KICKOFF
CONFIG["static_resource_version"] = 2
|
<commit_before>import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = BUILDSEASON
CONFIG["static_resource_version"] = 2
<commit_msg>Revert back to kickoff for landing page<commit_after>import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = KICKOFF
CONFIG["static_resource_version"] = 2
|
325ca5357af3b3c769b9d80d5452aae41cc2ba4f
|
src/utils/versioning.py
|
src/utils/versioning.py
|
'''
Backup es index to S3 and refresh
'''
from tornado.ioloop import IOLoop
from web.api.es import ESQuery
async def backup_and_refresh():
'''
Run periodically in the main event loop
'''
def sync_func():
esq = ESQuery()
esq.backup_all(aws_s3_bucket='smartapi')
esq.refresh_all(dryrun=False)
await IOLoop.current().run_in_executor(None, sync_func)
|
'''
Backup es index to S3 and refresh
'''
import logging
from tornado.ioloop import IOLoop
from web.api.es import ESQuery
async def backup_and_refresh():
'''
Run periodically in the main event loop
'''
def sync_func():
esq = ESQuery()
try:
esq.backup_all(aws_s3_bucket='smartapi')
except:
logging.exception("Backup failed.")
esq.refresh_all(dryrun=False)
await IOLoop.current().run_in_executor(None, sync_func)
|
Make backup failures not disruptive
|
Make backup failures not disruptive
|
Python
|
mit
|
Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI,Network-of-BioThings/smartAPI
|
'''
Backup es index to S3 and refresh
'''
from tornado.ioloop import IOLoop
from web.api.es import ESQuery
async def backup_and_refresh():
'''
Run periodically in the main event loop
'''
def sync_func():
esq = ESQuery()
esq.backup_all(aws_s3_bucket='smartapi')
esq.refresh_all(dryrun=False)
await IOLoop.current().run_in_executor(None, sync_func)
Make backup failures not disruptive
|
'''
Backup es index to S3 and refresh
'''
import logging
from tornado.ioloop import IOLoop
from web.api.es import ESQuery
async def backup_and_refresh():
'''
Run periodically in the main event loop
'''
def sync_func():
esq = ESQuery()
try:
esq.backup_all(aws_s3_bucket='smartapi')
except:
logging.exception("Backup failed.")
esq.refresh_all(dryrun=False)
await IOLoop.current().run_in_executor(None, sync_func)
|
<commit_before>'''
Backup es index to S3 and refresh
'''
from tornado.ioloop import IOLoop
from web.api.es import ESQuery
async def backup_and_refresh():
'''
Run periodically in the main event loop
'''
def sync_func():
esq = ESQuery()
esq.backup_all(aws_s3_bucket='smartapi')
esq.refresh_all(dryrun=False)
await IOLoop.current().run_in_executor(None, sync_func)
<commit_msg>Make backup failures not disruptive<commit_after>
|
'''
Backup es index to S3 and refresh
'''
import logging
from tornado.ioloop import IOLoop
from web.api.es import ESQuery
async def backup_and_refresh():
'''
Run periodically in the main event loop
'''
def sync_func():
esq = ESQuery()
try:
esq.backup_all(aws_s3_bucket='smartapi')
except:
logging.exception("Backup failed.")
esq.refresh_all(dryrun=False)
await IOLoop.current().run_in_executor(None, sync_func)
|
'''
Backup es index to S3 and refresh
'''
from tornado.ioloop import IOLoop
from web.api.es import ESQuery
async def backup_and_refresh():
'''
Run periodically in the main event loop
'''
def sync_func():
esq = ESQuery()
esq.backup_all(aws_s3_bucket='smartapi')
esq.refresh_all(dryrun=False)
await IOLoop.current().run_in_executor(None, sync_func)
Make backup failures not disruptive'''
Backup es index to S3 and refresh
'''
import logging
from tornado.ioloop import IOLoop
from web.api.es import ESQuery
async def backup_and_refresh():
'''
Run periodically in the main event loop
'''
def sync_func():
esq = ESQuery()
try:
esq.backup_all(aws_s3_bucket='smartapi')
except:
logging.exception("Backup failed.")
esq.refresh_all(dryrun=False)
await IOLoop.current().run_in_executor(None, sync_func)
|
<commit_before>'''
Backup es index to S3 and refresh
'''
from tornado.ioloop import IOLoop
from web.api.es import ESQuery
async def backup_and_refresh():
'''
Run periodically in the main event loop
'''
def sync_func():
esq = ESQuery()
esq.backup_all(aws_s3_bucket='smartapi')
esq.refresh_all(dryrun=False)
await IOLoop.current().run_in_executor(None, sync_func)
<commit_msg>Make backup failures not disruptive<commit_after>'''
Backup es index to S3 and refresh
'''
import logging
from tornado.ioloop import IOLoop
from web.api.es import ESQuery
async def backup_and_refresh():
'''
Run periodically in the main event loop
'''
def sync_func():
esq = ESQuery()
try:
esq.backup_all(aws_s3_bucket='smartapi')
except:
logging.exception("Backup failed.")
esq.refresh_all(dryrun=False)
await IOLoop.current().run_in_executor(None, sync_func)
|
3d242b5191e752c5686bd45b5b64c1b55d25778e
|
teknologr/members/tests.py
|
teknologr/members/tests.py
|
from django.test import TestCase
# Create your tests here.
class SanityTest(TestCase):
def test_one_plus_one_equals_two(self):
self.assertEqual(1+1, 2)
|
from django.test import TestCase
# Create your tests here.
class SanityTest(TestCase):
def test_one_plus_one_equals_two(self):
self.assertEqual(1 + 1, 2)
|
Add whitespace around + (pep8 E225/E226)
|
Add whitespace around + (pep8 E225/E226)
|
Python
|
mit
|
Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io
|
from django.test import TestCase
# Create your tests here.
class SanityTest(TestCase):
def test_one_plus_one_equals_two(self):
self.assertEqual(1+1, 2)
Add whitespace around + (pep8 E225/E226)
|
from django.test import TestCase
# Create your tests here.
class SanityTest(TestCase):
def test_one_plus_one_equals_two(self):
self.assertEqual(1 + 1, 2)
|
<commit_before>from django.test import TestCase
# Create your tests here.
class SanityTest(TestCase):
def test_one_plus_one_equals_two(self):
self.assertEqual(1+1, 2)
<commit_msg>Add whitespace around + (pep8 E225/E226)<commit_after>
|
from django.test import TestCase
# Create your tests here.
class SanityTest(TestCase):
def test_one_plus_one_equals_two(self):
self.assertEqual(1 + 1, 2)
|
from django.test import TestCase
# Create your tests here.
class SanityTest(TestCase):
def test_one_plus_one_equals_two(self):
self.assertEqual(1+1, 2)
Add whitespace around + (pep8 E225/E226)from django.test import TestCase
# Create your tests here.
class SanityTest(TestCase):
def test_one_plus_one_equals_two(self):
self.assertEqual(1 + 1, 2)
|
<commit_before>from django.test import TestCase
# Create your tests here.
class SanityTest(TestCase):
def test_one_plus_one_equals_two(self):
self.assertEqual(1+1, 2)
<commit_msg>Add whitespace around + (pep8 E225/E226)<commit_after>from django.test import TestCase
# Create your tests here.
class SanityTest(TestCase):
def test_one_plus_one_equals_two(self):
self.assertEqual(1 + 1, 2)
|
76e048b581de16fbcbd270f6e6faa4ba11b27f19
|
s3img_magic.py
|
s3img_magic.py
|
from IPython.display import Image
import boto
def s3img(uri):
if uri.startswith('s3://'):
uri = uri[5:]
bucket_name, key_name = uri.split('/', 1)
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
key = bucket.get_key(key_name)
data = key.get_contents_as_string()
return Image(data=data)
def load_ipython_extension(ipython):
ipython.register_magic_function(s3img, 'line')
|
from IPython.display import Image
import boto
def parse_s3_uri(uri):
if uri.startswith('s3://'):
uri = uri[5:]
return uri.split('/', 1)
def get_s3_key(uri):
bucket_name, key_name = parse_s3_uri(uri)
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
return bucket.get_key(key_name)
def s3img(uri):
key = get_s3_key(uri)
data = key.get_contents_as_string()
return Image(data=data)
def load_ipython_extension(ipython):
ipython.register_magic_function(s3img, 'line')
|
Refactor S3 interactions for reusability
|
Refactor S3 interactions for reusability
|
Python
|
mit
|
AustinRochford/s3img-ipython-magic,AustinRochford/s3img-ipython-magic
|
from IPython.display import Image
import boto
def s3img(uri):
if uri.startswith('s3://'):
uri = uri[5:]
bucket_name, key_name = uri.split('/', 1)
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
key = bucket.get_key(key_name)
data = key.get_contents_as_string()
return Image(data=data)
def load_ipython_extension(ipython):
ipython.register_magic_function(s3img, 'line')
Refactor S3 interactions for reusability
|
from IPython.display import Image
import boto
def parse_s3_uri(uri):
if uri.startswith('s3://'):
uri = uri[5:]
return uri.split('/', 1)
def get_s3_key(uri):
bucket_name, key_name = parse_s3_uri(uri)
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
return bucket.get_key(key_name)
def s3img(uri):
key = get_s3_key(uri)
data = key.get_contents_as_string()
return Image(data=data)
def load_ipython_extension(ipython):
ipython.register_magic_function(s3img, 'line')
|
<commit_before>from IPython.display import Image
import boto
def s3img(uri):
if uri.startswith('s3://'):
uri = uri[5:]
bucket_name, key_name = uri.split('/', 1)
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
key = bucket.get_key(key_name)
data = key.get_contents_as_string()
return Image(data=data)
def load_ipython_extension(ipython):
ipython.register_magic_function(s3img, 'line')
<commit_msg>Refactor S3 interactions for reusability<commit_after>
|
from IPython.display import Image
import boto
def parse_s3_uri(uri):
if uri.startswith('s3://'):
uri = uri[5:]
return uri.split('/', 1)
def get_s3_key(uri):
bucket_name, key_name = parse_s3_uri(uri)
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
return bucket.get_key(key_name)
def s3img(uri):
key = get_s3_key(uri)
data = key.get_contents_as_string()
return Image(data=data)
def load_ipython_extension(ipython):
ipython.register_magic_function(s3img, 'line')
|
from IPython.display import Image
import boto
def s3img(uri):
if uri.startswith('s3://'):
uri = uri[5:]
bucket_name, key_name = uri.split('/', 1)
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
key = bucket.get_key(key_name)
data = key.get_contents_as_string()
return Image(data=data)
def load_ipython_extension(ipython):
ipython.register_magic_function(s3img, 'line')
Refactor S3 interactions for reusabilityfrom IPython.display import Image
import boto
def parse_s3_uri(uri):
if uri.startswith('s3://'):
uri = uri[5:]
return uri.split('/', 1)
def get_s3_key(uri):
bucket_name, key_name = parse_s3_uri(uri)
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
return bucket.get_key(key_name)
def s3img(uri):
key = get_s3_key(uri)
data = key.get_contents_as_string()
return Image(data=data)
def load_ipython_extension(ipython):
ipython.register_magic_function(s3img, 'line')
|
<commit_before>from IPython.display import Image
import boto
def s3img(uri):
if uri.startswith('s3://'):
uri = uri[5:]
bucket_name, key_name = uri.split('/', 1)
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
key = bucket.get_key(key_name)
data = key.get_contents_as_string()
return Image(data=data)
def load_ipython_extension(ipython):
ipython.register_magic_function(s3img, 'line')
<commit_msg>Refactor S3 interactions for reusability<commit_after>from IPython.display import Image
import boto
def parse_s3_uri(uri):
if uri.startswith('s3://'):
uri = uri[5:]
return uri.split('/', 1)
def get_s3_key(uri):
bucket_name, key_name = parse_s3_uri(uri)
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name)
return bucket.get_key(key_name)
def s3img(uri):
key = get_s3_key(uri)
data = key.get_contents_as_string()
return Image(data=data)
def load_ipython_extension(ipython):
ipython.register_magic_function(s3img, 'line')
|
185e6490eef10f5e0c5e9d08ad0fd4b976a73c9c
|
test/sanity_run_vpp.py
|
test/sanity_run_vpp.py
|
#!/usr/bin/env python
from __future__ import print_function
from multiprocessing import Pipe
from sys import exit
from hook import VppDiedError
from framework import VppTestCase, KeepAliveReporter
class SanityTestCase(VppTestCase):
""" Sanity test case - verify thether VPP is able to start """
pass
if __name__ == '__main__':
rc = 0
tc = SanityTestCase
x, y = Pipe()
reporter = KeepAliveReporter()
reporter.pipe = y
try:
tc.setUpClass()
except VppDiedError:
rc = -1
else:
try:
tc.tearDownClass()
except:
pass
x.close()
y.close()
if rc == 0:
print('Sanity test case passed\n')
else:
print('Sanity test case failed\n')
exit(rc)
|
#!/usr/bin/env python
from __future__ import print_function
from multiprocessing import Pipe
from sys import exit
from hook import VppDiedError
from framework import VppTestCase, KeepAliveReporter
class SanityTestCase(VppTestCase):
""" Sanity test case - verify whether VPP is able to start """
pass
if __name__ == '__main__':
rc = 0
tc = SanityTestCase
x, y = Pipe()
reporter = KeepAliveReporter()
reporter.pipe = y
try:
tc.setUpClass()
except VppDiedError:
rc = -1
else:
try:
tc.tearDownClass()
except:
pass
x.close()
y.close()
if rc == 0:
print('Sanity test case passed\n')
else:
print('Sanity test case failed\n')
exit(rc)
|
Fix typo in sanity test description
|
Fix typo in sanity test description
Change-Id: Icd575b8ed62c340c57857ff6576f65557434f3e0
Signed-off-by: juraj.linkes <cc98fdfd74a97bdc42df592c19d962e48c451a95@pantheon.tech>
|
Python
|
apache-2.0
|
chrisy/vpp,vpp-dev/vpp,FDio/vpp,chrisy/vpp,FDio/vpp,chrisy/vpp,vpp-dev/vpp,vpp-dev/vpp,FDio/vpp,vpp-dev/vpp,chrisy/vpp,FDio/vpp,chrisy/vpp,chrisy/vpp,vpp-dev/vpp,FDio/vpp,chrisy/vpp,FDio/vpp,FDio/vpp,vpp-dev/vpp,FDio/vpp,vpp-dev/vpp,chrisy/vpp
|
#!/usr/bin/env python
from __future__ import print_function
from multiprocessing import Pipe
from sys import exit
from hook import VppDiedError
from framework import VppTestCase, KeepAliveReporter
class SanityTestCase(VppTestCase):
""" Sanity test case - verify thether VPP is able to start """
pass
if __name__ == '__main__':
rc = 0
tc = SanityTestCase
x, y = Pipe()
reporter = KeepAliveReporter()
reporter.pipe = y
try:
tc.setUpClass()
except VppDiedError:
rc = -1
else:
try:
tc.tearDownClass()
except:
pass
x.close()
y.close()
if rc == 0:
print('Sanity test case passed\n')
else:
print('Sanity test case failed\n')
exit(rc)
Fix typo in sanity test description
Change-Id: Icd575b8ed62c340c57857ff6576f65557434f3e0
Signed-off-by: juraj.linkes <cc98fdfd74a97bdc42df592c19d962e48c451a95@pantheon.tech>
|
#!/usr/bin/env python
from __future__ import print_function
from multiprocessing import Pipe
from sys import exit
from hook import VppDiedError
from framework import VppTestCase, KeepAliveReporter
class SanityTestCase(VppTestCase):
""" Sanity test case - verify whether VPP is able to start """
pass
if __name__ == '__main__':
rc = 0
tc = SanityTestCase
x, y = Pipe()
reporter = KeepAliveReporter()
reporter.pipe = y
try:
tc.setUpClass()
except VppDiedError:
rc = -1
else:
try:
tc.tearDownClass()
except:
pass
x.close()
y.close()
if rc == 0:
print('Sanity test case passed\n')
else:
print('Sanity test case failed\n')
exit(rc)
|
<commit_before>#!/usr/bin/env python
from __future__ import print_function
from multiprocessing import Pipe
from sys import exit
from hook import VppDiedError
from framework import VppTestCase, KeepAliveReporter
class SanityTestCase(VppTestCase):
""" Sanity test case - verify thether VPP is able to start """
pass
if __name__ == '__main__':
rc = 0
tc = SanityTestCase
x, y = Pipe()
reporter = KeepAliveReporter()
reporter.pipe = y
try:
tc.setUpClass()
except VppDiedError:
rc = -1
else:
try:
tc.tearDownClass()
except:
pass
x.close()
y.close()
if rc == 0:
print('Sanity test case passed\n')
else:
print('Sanity test case failed\n')
exit(rc)
<commit_msg>Fix typo in sanity test description
Change-Id: Icd575b8ed62c340c57857ff6576f65557434f3e0
Signed-off-by: juraj.linkes <cc98fdfd74a97bdc42df592c19d962e48c451a95@pantheon.tech><commit_after>
|
#!/usr/bin/env python
from __future__ import print_function
from multiprocessing import Pipe
from sys import exit
from hook import VppDiedError
from framework import VppTestCase, KeepAliveReporter
class SanityTestCase(VppTestCase):
""" Sanity test case - verify whether VPP is able to start """
pass
if __name__ == '__main__':
rc = 0
tc = SanityTestCase
x, y = Pipe()
reporter = KeepAliveReporter()
reporter.pipe = y
try:
tc.setUpClass()
except VppDiedError:
rc = -1
else:
try:
tc.tearDownClass()
except:
pass
x.close()
y.close()
if rc == 0:
print('Sanity test case passed\n')
else:
print('Sanity test case failed\n')
exit(rc)
|
#!/usr/bin/env python
from __future__ import print_function
from multiprocessing import Pipe
from sys import exit
from hook import VppDiedError
from framework import VppTestCase, KeepAliveReporter
class SanityTestCase(VppTestCase):
""" Sanity test case - verify thether VPP is able to start """
pass
if __name__ == '__main__':
rc = 0
tc = SanityTestCase
x, y = Pipe()
reporter = KeepAliveReporter()
reporter.pipe = y
try:
tc.setUpClass()
except VppDiedError:
rc = -1
else:
try:
tc.tearDownClass()
except:
pass
x.close()
y.close()
if rc == 0:
print('Sanity test case passed\n')
else:
print('Sanity test case failed\n')
exit(rc)
Fix typo in sanity test description
Change-Id: Icd575b8ed62c340c57857ff6576f65557434f3e0
Signed-off-by: juraj.linkes <cc98fdfd74a97bdc42df592c19d962e48c451a95@pantheon.tech>#!/usr/bin/env python
from __future__ import print_function
from multiprocessing import Pipe
from sys import exit
from hook import VppDiedError
from framework import VppTestCase, KeepAliveReporter
class SanityTestCase(VppTestCase):
""" Sanity test case - verify whether VPP is able to start """
pass
if __name__ == '__main__':
rc = 0
tc = SanityTestCase
x, y = Pipe()
reporter = KeepAliveReporter()
reporter.pipe = y
try:
tc.setUpClass()
except VppDiedError:
rc = -1
else:
try:
tc.tearDownClass()
except:
pass
x.close()
y.close()
if rc == 0:
print('Sanity test case passed\n')
else:
print('Sanity test case failed\n')
exit(rc)
|
<commit_before>#!/usr/bin/env python
from __future__ import print_function
from multiprocessing import Pipe
from sys import exit
from hook import VppDiedError
from framework import VppTestCase, KeepAliveReporter
class SanityTestCase(VppTestCase):
""" Sanity test case - verify thether VPP is able to start """
pass
if __name__ == '__main__':
rc = 0
tc = SanityTestCase
x, y = Pipe()
reporter = KeepAliveReporter()
reporter.pipe = y
try:
tc.setUpClass()
except VppDiedError:
rc = -1
else:
try:
tc.tearDownClass()
except:
pass
x.close()
y.close()
if rc == 0:
print('Sanity test case passed\n')
else:
print('Sanity test case failed\n')
exit(rc)
<commit_msg>Fix typo in sanity test description
Change-Id: Icd575b8ed62c340c57857ff6576f65557434f3e0
Signed-off-by: juraj.linkes <cc98fdfd74a97bdc42df592c19d962e48c451a95@pantheon.tech><commit_after>#!/usr/bin/env python
from __future__ import print_function
from multiprocessing import Pipe
from sys import exit
from hook import VppDiedError
from framework import VppTestCase, KeepAliveReporter
class SanityTestCase(VppTestCase):
""" Sanity test case - verify whether VPP is able to start """
pass
if __name__ == '__main__':
rc = 0
tc = SanityTestCase
x, y = Pipe()
reporter = KeepAliveReporter()
reporter.pipe = y
try:
tc.setUpClass()
except VppDiedError:
rc = -1
else:
try:
tc.tearDownClass()
except:
pass
x.close()
y.close()
if rc == 0:
print('Sanity test case passed\n')
else:
print('Sanity test case failed\n')
exit(rc)
|
d301a0635578550ededd1bca7ac34e841366b0ef
|
devito/foreign/__init__.py
|
devito/foreign/__init__.py
|
"""
The ``foreign`` Devito backend is meant to be used by codes that don't
run Python natively. This backend is only capable of generating and compiling
kernels; however, kernels must be executed explicitly from outside Devito.
Further, with the ``foreign`` backed, Devito doesn't allocate any data.
"""
# The following used by backends.backendSelector
from devito.function import Constant, Function, TimeFunction, SparseFunction # noqa
from devito.foreign.operator import Operator # noqa
|
"""
The ``foreign`` Devito backend is meant to be used by codes that don't
run Python natively. This backend is only capable of generating and compiling
kernels; however, kernels must be executed explicitly from outside Devito.
Further, with the ``foreign`` backed, Devito doesn't allocate any data.
"""
# The following used by backends.backendSelector
from devito.function import Constant, Function, TimeFunction, SparseFunction # noqa
from devito.foreign.operator import Operator # noqa
from devito.types import CacheManager # noqa
|
Add leftover import due to disfunctional testing
|
Add leftover import due to disfunctional testing
|
Python
|
mit
|
opesci/devito,opesci/devito
|
"""
The ``foreign`` Devito backend is meant to be used by codes that don't
run Python natively. This backend is only capable of generating and compiling
kernels; however, kernels must be executed explicitly from outside Devito.
Further, with the ``foreign`` backed, Devito doesn't allocate any data.
"""
# The following used by backends.backendSelector
from devito.function import Constant, Function, TimeFunction, SparseFunction # noqa
from devito.foreign.operator import Operator # noqa
Add leftover import due to disfunctional testing
|
"""
The ``foreign`` Devito backend is meant to be used by codes that don't
run Python natively. This backend is only capable of generating and compiling
kernels; however, kernels must be executed explicitly from outside Devito.
Further, with the ``foreign`` backed, Devito doesn't allocate any data.
"""
# The following used by backends.backendSelector
from devito.function import Constant, Function, TimeFunction, SparseFunction # noqa
from devito.foreign.operator import Operator # noqa
from devito.types import CacheManager # noqa
|
<commit_before>"""
The ``foreign`` Devito backend is meant to be used by codes that don't
run Python natively. This backend is only capable of generating and compiling
kernels; however, kernels must be executed explicitly from outside Devito.
Further, with the ``foreign`` backed, Devito doesn't allocate any data.
"""
# The following used by backends.backendSelector
from devito.function import Constant, Function, TimeFunction, SparseFunction # noqa
from devito.foreign.operator import Operator # noqa
<commit_msg>Add leftover import due to disfunctional testing<commit_after>
|
"""
The ``foreign`` Devito backend is meant to be used by codes that don't
run Python natively. This backend is only capable of generating and compiling
kernels; however, kernels must be executed explicitly from outside Devito.
Further, with the ``foreign`` backed, Devito doesn't allocate any data.
"""
# The following used by backends.backendSelector
from devito.function import Constant, Function, TimeFunction, SparseFunction # noqa
from devito.foreign.operator import Operator # noqa
from devito.types import CacheManager # noqa
|
"""
The ``foreign`` Devito backend is meant to be used by codes that don't
run Python natively. This backend is only capable of generating and compiling
kernels; however, kernels must be executed explicitly from outside Devito.
Further, with the ``foreign`` backed, Devito doesn't allocate any data.
"""
# The following used by backends.backendSelector
from devito.function import Constant, Function, TimeFunction, SparseFunction # noqa
from devito.foreign.operator import Operator # noqa
Add leftover import due to disfunctional testing"""
The ``foreign`` Devito backend is meant to be used by codes that don't
run Python natively. This backend is only capable of generating and compiling
kernels; however, kernels must be executed explicitly from outside Devito.
Further, with the ``foreign`` backed, Devito doesn't allocate any data.
"""
# The following used by backends.backendSelector
from devito.function import Constant, Function, TimeFunction, SparseFunction # noqa
from devito.foreign.operator import Operator # noqa
from devito.types import CacheManager # noqa
|
<commit_before>"""
The ``foreign`` Devito backend is meant to be used by codes that don't
run Python natively. This backend is only capable of generating and compiling
kernels; however, kernels must be executed explicitly from outside Devito.
Further, with the ``foreign`` backed, Devito doesn't allocate any data.
"""
# The following used by backends.backendSelector
from devito.function import Constant, Function, TimeFunction, SparseFunction # noqa
from devito.foreign.operator import Operator # noqa
<commit_msg>Add leftover import due to disfunctional testing<commit_after>"""
The ``foreign`` Devito backend is meant to be used by codes that don't
run Python natively. This backend is only capable of generating and compiling
kernels; however, kernels must be executed explicitly from outside Devito.
Further, with the ``foreign`` backed, Devito doesn't allocate any data.
"""
# The following used by backends.backendSelector
from devito.function import Constant, Function, TimeFunction, SparseFunction # noqa
from devito.foreign.operator import Operator # noqa
from devito.types import CacheManager # noqa
|
18aafd9218efe636c6efb75980b2014d43b6736e
|
tests/test_conditionals.py
|
tests/test_conditionals.py
|
import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
|
import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
def test_unconditional_else():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
otherwise
Output.write("dog is not dog")
if "dog" eq "cat"
Output.write("dog is cat")
otherwise
Output.write("dog is not cat")
""").output == """dog is dog\ndog is not cat""".strip()
|
Test for unconditional else branches
|
Test for unconditional else branches
|
Python
|
mit
|
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
|
import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
Test for unconditional else branches
|
import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
def test_unconditional_else():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
otherwise
Output.write("dog is not dog")
if "dog" eq "cat"
Output.write("dog is cat")
otherwise
Output.write("dog is not cat")
""").output == """dog is dog\ndog is not cat""".strip()
|
<commit_before>import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
<commit_msg>Test for unconditional else branches<commit_after>
|
import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
def test_unconditional_else():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
otherwise
Output.write("dog is not dog")
if "dog" eq "cat"
Output.write("dog is cat")
otherwise
Output.write("dog is not cat")
""").output == """dog is dog\ndog is not cat""".strip()
|
import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
Test for unconditional else branchesimport pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
def test_unconditional_else():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
otherwise
Output.write("dog is not dog")
if "dog" eq "cat"
Output.write("dog is cat")
otherwise
Output.write("dog is not cat")
""").output == """dog is dog\ndog is not cat""".strip()
|
<commit_before>import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
<commit_msg>Test for unconditional else branches<commit_after>import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
def test_unconditional_else():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
otherwise
Output.write("dog is not dog")
if "dog" eq "cat"
Output.write("dog is cat")
otherwise
Output.write("dog is not cat")
""").output == """dog is dog\ndog is not cat""".strip()
|
47612ac76be1f0d2929d470f34298117fa843d6f
|
tests/test_py3/__init__.py
|
tests/test_py3/__init__.py
|
"""
For tests that require python 3 only syntax.
"""
import six
if six.PY2:
# don't import this package on python2
def load_tests(loader, standard_tests, pattern):
return standard_tests
|
"""
For tests that require python 3 only syntax.
"""
import sys
if sys.version_info < (3, 6):
# These tests require annotations
def load_tests(loader, standard_tests, pattern):
return standard_tests
|
Fix python 3.5 test switching.
|
Fix python 3.5 test switching.
|
Python
|
mit
|
tim-mitchell/pure_interface
|
"""
For tests that require python 3 only syntax.
"""
import six
if six.PY2:
# don't import this package on python2
def load_tests(loader, standard_tests, pattern):
return standard_tests
Fix python 3.5 test switching.
|
"""
For tests that require python 3 only syntax.
"""
import sys
if sys.version_info < (3, 6):
# These tests require annotations
def load_tests(loader, standard_tests, pattern):
return standard_tests
|
<commit_before>"""
For tests that require python 3 only syntax.
"""
import six
if six.PY2:
# don't import this package on python2
def load_tests(loader, standard_tests, pattern):
return standard_tests
<commit_msg>Fix python 3.5 test switching.<commit_after>
|
"""
For tests that require python 3 only syntax.
"""
import sys
if sys.version_info < (3, 6):
# These tests require annotations
def load_tests(loader, standard_tests, pattern):
return standard_tests
|
"""
For tests that require python 3 only syntax.
"""
import six
if six.PY2:
# don't import this package on python2
def load_tests(loader, standard_tests, pattern):
return standard_tests
Fix python 3.5 test switching."""
For tests that require python 3 only syntax.
"""
import sys
if sys.version_info < (3, 6):
# These tests require annotations
def load_tests(loader, standard_tests, pattern):
return standard_tests
|
<commit_before>"""
For tests that require python 3 only syntax.
"""
import six
if six.PY2:
# don't import this package on python2
def load_tests(loader, standard_tests, pattern):
return standard_tests
<commit_msg>Fix python 3.5 test switching.<commit_after>"""
For tests that require python 3 only syntax.
"""
import sys
if sys.version_info < (3, 6):
# These tests require annotations
def load_tests(loader, standard_tests, pattern):
return standard_tests
|
da8efb34fe00f4c625c6ab7d3cf5651193d972d0
|
mopidy/backends/__init__.py
|
mopidy/backends/__init__.py
|
import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentPlaylistController(object):
def __init__(self, backend):
self.backend = backend
class BasePlaybackController(object):
PAUSED = 'paused'
PLAYING = 'playing'
STOPPED = 'stopped'
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
|
import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentPlaylistController(object):
def __init__(self, backend):
self.backend = backend
def add(self, track, at_position=None):
raise NotImplementedError
class BasePlaybackController(object):
PAUSED = 'paused'
PLAYING = 'playing'
STOPPED = 'stopped'
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
|
Add add method to BaseCurrentPlaylistController
|
Add add method to BaseCurrentPlaylistController
|
Python
|
apache-2.0
|
priestd09/mopidy,jcass77/mopidy,mokieyue/mopidy,ZenithDK/mopidy,SuperStarPL/mopidy,mopidy/mopidy,bencevans/mopidy,tkem/mopidy,quartz55/mopidy,rawdlite/mopidy,tkem/mopidy,quartz55/mopidy,glogiotatidis/mopidy,SuperStarPL/mopidy,adamcik/mopidy,woutervanwijk/mopidy,bencevans/mopidy,pacificIT/mopidy,hkariti/mopidy,bacontext/mopidy,abarisain/mopidy,SuperStarPL/mopidy,adamcik/mopidy,vrs01/mopidy,jcass77/mopidy,priestd09/mopidy,diandiankan/mopidy,jmarsik/mopidy,ZenithDK/mopidy,swak/mopidy,hkariti/mopidy,ZenithDK/mopidy,jmarsik/mopidy,ali/mopidy,quartz55/mopidy,SuperStarPL/mopidy,jodal/mopidy,ali/mopidy,rawdlite/mopidy,diandiankan/mopidy,rawdlite/mopidy,dbrgn/mopidy,quartz55/mopidy,tkem/mopidy,mopidy/mopidy,mokieyue/mopidy,swak/mopidy,tkem/mopidy,mokieyue/mopidy,liamw9534/mopidy,glogiotatidis/mopidy,jmarsik/mopidy,kingosticks/mopidy,hkariti/mopidy,jodal/mopidy,swak/mopidy,bencevans/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,diandiankan/mopidy,pacificIT/mopidy,bacontext/mopidy,dbrgn/mopidy,rawdlite/mopidy,priestd09/mopidy,ali/mopidy,hkariti/mopidy,liamw9534/mopidy,woutervanwijk/mopidy,mokieyue/mopidy,dbrgn/mopidy,adamcik/mopidy,glogiotatidis/mopidy,abarisain/mopidy,diandiankan/mopidy,dbrgn/mopidy,pacificIT/mopidy,ali/mopidy,bacontext/mopidy,mopidy/mopidy,pacificIT/mopidy,bacontext/mopidy,swak/mopidy,vrs01/mopidy,vrs01/mopidy,bencevans/mopidy,ZenithDK/mopidy,vrs01/mopidy,jcass77/mopidy,kingosticks/mopidy,jodal/mopidy,kingosticks/mopidy
|
import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentPlaylistController(object):
def __init__(self, backend):
self.backend = backend
class BasePlaybackController(object):
PAUSED = 'paused'
PLAYING = 'playing'
STOPPED = 'stopped'
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
Add add method to BaseCurrentPlaylistController
|
import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentPlaylistController(object):
def __init__(self, backend):
self.backend = backend
def add(self, track, at_position=None):
raise NotImplementedError
class BasePlaybackController(object):
PAUSED = 'paused'
PLAYING = 'playing'
STOPPED = 'stopped'
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
|
<commit_before>import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentPlaylistController(object):
def __init__(self, backend):
self.backend = backend
class BasePlaybackController(object):
PAUSED = 'paused'
PLAYING = 'playing'
STOPPED = 'stopped'
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
<commit_msg>Add add method to BaseCurrentPlaylistController<commit_after>
|
import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentPlaylistController(object):
def __init__(self, backend):
self.backend = backend
def add(self, track, at_position=None):
raise NotImplementedError
class BasePlaybackController(object):
PAUSED = 'paused'
PLAYING = 'playing'
STOPPED = 'stopped'
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
|
import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentPlaylistController(object):
def __init__(self, backend):
self.backend = backend
class BasePlaybackController(object):
PAUSED = 'paused'
PLAYING = 'playing'
STOPPED = 'stopped'
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
Add add method to BaseCurrentPlaylistControllerimport logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentPlaylistController(object):
def __init__(self, backend):
self.backend = backend
def add(self, track, at_position=None):
raise NotImplementedError
class BasePlaybackController(object):
PAUSED = 'paused'
PLAYING = 'playing'
STOPPED = 'stopped'
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
|
<commit_before>import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentPlaylistController(object):
def __init__(self, backend):
self.backend = backend
class BasePlaybackController(object):
PAUSED = 'paused'
PLAYING = 'playing'
STOPPED = 'stopped'
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
<commit_msg>Add add method to BaseCurrentPlaylistController<commit_after>import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentPlaylistController(object):
def __init__(self, backend):
self.backend = backend
def add(self, track, at_position=None):
raise NotImplementedError
class BasePlaybackController(object):
PAUSED = 'paused'
PLAYING = 'playing'
STOPPED = 'stopped'
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
|
4a07beaf945ce26186fa80f3114cb4c7dc0dd697
|
tests/app/test_rest.py
|
tests/app/test_rest.py
|
import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
|
import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
def it_shows_db_error(self, mocker, client, db):
mocker.patch('app.rest.db.session.execute', side_effect=Exception('db error'))
response = client.get(
url_for('.get_info')
)
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == 'Database error, check logs'
|
Add test for info when db error
|
Add test for info when db error
|
Python
|
mit
|
NewAcropolis/api,NewAcropolis/api,NewAcropolis/api
|
import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
Add test for info when db error
|
import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
def it_shows_db_error(self, mocker, client, db):
mocker.patch('app.rest.db.session.execute', side_effect=Exception('db error'))
response = client.get(
url_for('.get_info')
)
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == 'Database error, check logs'
|
<commit_before>import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
<commit_msg>Add test for info when db error<commit_after>
|
import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
def it_shows_db_error(self, mocker, client, db):
mocker.patch('app.rest.db.session.execute', side_effect=Exception('db error'))
response = client.get(
url_for('.get_info')
)
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == 'Database error, check logs'
|
import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
Add test for info when db errorimport pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
def it_shows_db_error(self, mocker, client, db):
mocker.patch('app.rest.db.session.execute', side_effect=Exception('db error'))
response = client.get(
url_for('.get_info')
)
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == 'Database error, check logs'
|
<commit_before>import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
<commit_msg>Add test for info when db error<commit_after>import pytest
from flask import json, url_for
class WhenAccessingSiteInfo(object):
def it_shows_info(self, client, db):
response = client.get(
url_for('.get_info')
)
query = 'SELECT version_num FROM alembic_version'
version_from_db = db.session.execute(query).fetchone()[0]
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == version_from_db
def it_shows_db_error(self, mocker, client, db):
mocker.patch('app.rest.db.session.execute', side_effect=Exception('db error'))
response = client.get(
url_for('.get_info')
)
json_resp = json.loads(response.get_data(as_text=True))['info']
assert response.status_code == 200
assert json_resp == 'Database error, check logs'
|
149ca57fabad4430b22af08c88d8df6fbcc6dfc2
|
statictemplate/tests.py
|
statictemplate/tests.py
|
# -*- coding: utf-8 -*-
from StringIO import StringIO
from django.conf import settings
from django.core.management import call_command
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from statictemplate.management.commands.statictemplate import make_static
import unittest
class TestLoader(BaseLoader):
is_usable = True
templates = {
'simple': '{% extends "base" %}{% block content %}simple{% endblock %}',
'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}',
}
def load_template_source(self, template_name, template_dirs=None):
found = self.templates.get(template_name, None)
if not found: # pragma: no cover
raise TemplateDoesNotExist(template_name)
return found, template_name
class StaticTemplateTests(unittest.TestCase):
def setUp(self):
settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader']
def test_python_api(self):
output = make_static('simple')
self.assertEqual(output, 'headsimple')
def test_call_command(self):
sio = StringIO()
call_command('statictemplate', 'simple', stdout=sio)
self.assertEqual(sio.getvalue().strip(), 'headsimple')
|
# -*- coding: utf-8 -*-
from StringIO import StringIO
from django.conf import settings
from django.http import HttpResponseRedirect
from django.core.management import call_command
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from statictemplate.management.commands.statictemplate import make_static
import unittest
class TestLoader(BaseLoader):
is_usable = True
templates = {
'simple': '{% extends "base" %}{% block content %}simple{% endblock %}',
'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}',
}
def load_template_source(self, template_name, template_dirs=None):
found = self.templates.get(template_name, None)
if not found: # pragma: no cover
raise TemplateDoesNotExist(template_name)
return found, template_name
class MeddlingMiddleware(object):
def process_request(self, request):
return HttpResponseRedirect('/foobarbaz')
class StaticTemplateTests(unittest.TestCase):
def setUp(self):
settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader']
def test_python_api(self):
output = make_static('simple')
self.assertEqual(output, 'headsimple')
def test_call_command(self):
sio = StringIO()
call_command('statictemplate', 'simple', stdout=sio)
self.assertEqual(sio.getvalue().strip(), 'headsimple')
def test_meddling_middleware(self):
middleware = (
'statictemplate.tests.MeddlingMiddleware',
)
settings.MIDDLEWARE_CLASSES = middleware
output = make_static('simple')
self.assertEqual(output, 'headsimple')
self.assertEqual(settings.MIDDLEWARE_CLASSES, middleware)
|
Add test for meddling middleware
|
Add test for meddling middleware
|
Python
|
bsd-3-clause
|
bdon/django-statictemplate,ojii/django-statictemplate,yakky/django-statictemplate
|
# -*- coding: utf-8 -*-
from StringIO import StringIO
from django.conf import settings
from django.core.management import call_command
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from statictemplate.management.commands.statictemplate import make_static
import unittest
class TestLoader(BaseLoader):
is_usable = True
templates = {
'simple': '{% extends "base" %}{% block content %}simple{% endblock %}',
'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}',
}
def load_template_source(self, template_name, template_dirs=None):
found = self.templates.get(template_name, None)
if not found: # pragma: no cover
raise TemplateDoesNotExist(template_name)
return found, template_name
class StaticTemplateTests(unittest.TestCase):
def setUp(self):
settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader']
def test_python_api(self):
output = make_static('simple')
self.assertEqual(output, 'headsimple')
def test_call_command(self):
sio = StringIO()
call_command('statictemplate', 'simple', stdout=sio)
self.assertEqual(sio.getvalue().strip(), 'headsimple')
Add test for meddling middleware
|
# -*- coding: utf-8 -*-
from StringIO import StringIO
from django.conf import settings
from django.http import HttpResponseRedirect
from django.core.management import call_command
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from statictemplate.management.commands.statictemplate import make_static
import unittest
class TestLoader(BaseLoader):
is_usable = True
templates = {
'simple': '{% extends "base" %}{% block content %}simple{% endblock %}',
'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}',
}
def load_template_source(self, template_name, template_dirs=None):
found = self.templates.get(template_name, None)
if not found: # pragma: no cover
raise TemplateDoesNotExist(template_name)
return found, template_name
class MeddlingMiddleware(object):
def process_request(self, request):
return HttpResponseRedirect('/foobarbaz')
class StaticTemplateTests(unittest.TestCase):
def setUp(self):
settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader']
def test_python_api(self):
output = make_static('simple')
self.assertEqual(output, 'headsimple')
def test_call_command(self):
sio = StringIO()
call_command('statictemplate', 'simple', stdout=sio)
self.assertEqual(sio.getvalue().strip(), 'headsimple')
def test_meddling_middleware(self):
middleware = (
'statictemplate.tests.MeddlingMiddleware',
)
settings.MIDDLEWARE_CLASSES = middleware
output = make_static('simple')
self.assertEqual(output, 'headsimple')
self.assertEqual(settings.MIDDLEWARE_CLASSES, middleware)
|
<commit_before># -*- coding: utf-8 -*-
from StringIO import StringIO
from django.conf import settings
from django.core.management import call_command
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from statictemplate.management.commands.statictemplate import make_static
import unittest
class TestLoader(BaseLoader):
is_usable = True
templates = {
'simple': '{% extends "base" %}{% block content %}simple{% endblock %}',
'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}',
}
def load_template_source(self, template_name, template_dirs=None):
found = self.templates.get(template_name, None)
if not found: # pragma: no cover
raise TemplateDoesNotExist(template_name)
return found, template_name
class StaticTemplateTests(unittest.TestCase):
def setUp(self):
settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader']
def test_python_api(self):
output = make_static('simple')
self.assertEqual(output, 'headsimple')
def test_call_command(self):
sio = StringIO()
call_command('statictemplate', 'simple', stdout=sio)
self.assertEqual(sio.getvalue().strip(), 'headsimple')
<commit_msg>Add test for meddling middleware<commit_after>
|
# -*- coding: utf-8 -*-
from StringIO import StringIO
from django.conf import settings
from django.http import HttpResponseRedirect
from django.core.management import call_command
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from statictemplate.management.commands.statictemplate import make_static
import unittest
class TestLoader(BaseLoader):
is_usable = True
templates = {
'simple': '{% extends "base" %}{% block content %}simple{% endblock %}',
'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}',
}
def load_template_source(self, template_name, template_dirs=None):
found = self.templates.get(template_name, None)
if not found: # pragma: no cover
raise TemplateDoesNotExist(template_name)
return found, template_name
class MeddlingMiddleware(object):
def process_request(self, request):
return HttpResponseRedirect('/foobarbaz')
class StaticTemplateTests(unittest.TestCase):
def setUp(self):
settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader']
def test_python_api(self):
output = make_static('simple')
self.assertEqual(output, 'headsimple')
def test_call_command(self):
sio = StringIO()
call_command('statictemplate', 'simple', stdout=sio)
self.assertEqual(sio.getvalue().strip(), 'headsimple')
def test_meddling_middleware(self):
middleware = (
'statictemplate.tests.MeddlingMiddleware',
)
settings.MIDDLEWARE_CLASSES = middleware
output = make_static('simple')
self.assertEqual(output, 'headsimple')
self.assertEqual(settings.MIDDLEWARE_CLASSES, middleware)
|
# -*- coding: utf-8 -*-
from StringIO import StringIO
from django.conf import settings
from django.core.management import call_command
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from statictemplate.management.commands.statictemplate import make_static
import unittest
class TestLoader(BaseLoader):
is_usable = True
templates = {
'simple': '{% extends "base" %}{% block content %}simple{% endblock %}',
'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}',
}
def load_template_source(self, template_name, template_dirs=None):
found = self.templates.get(template_name, None)
if not found: # pragma: no cover
raise TemplateDoesNotExist(template_name)
return found, template_name
class StaticTemplateTests(unittest.TestCase):
def setUp(self):
settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader']
def test_python_api(self):
output = make_static('simple')
self.assertEqual(output, 'headsimple')
def test_call_command(self):
sio = StringIO()
call_command('statictemplate', 'simple', stdout=sio)
self.assertEqual(sio.getvalue().strip(), 'headsimple')
Add test for meddling middleware# -*- coding: utf-8 -*-
from StringIO import StringIO
from django.conf import settings
from django.http import HttpResponseRedirect
from django.core.management import call_command
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from statictemplate.management.commands.statictemplate import make_static
import unittest
class TestLoader(BaseLoader):
is_usable = True
templates = {
'simple': '{% extends "base" %}{% block content %}simple{% endblock %}',
'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}',
}
def load_template_source(self, template_name, template_dirs=None):
found = self.templates.get(template_name, None)
if not found: # pragma: no cover
raise TemplateDoesNotExist(template_name)
return found, template_name
class MeddlingMiddleware(object):
def process_request(self, request):
return HttpResponseRedirect('/foobarbaz')
class StaticTemplateTests(unittest.TestCase):
def setUp(self):
settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader']
def test_python_api(self):
output = make_static('simple')
self.assertEqual(output, 'headsimple')
def test_call_command(self):
sio = StringIO()
call_command('statictemplate', 'simple', stdout=sio)
self.assertEqual(sio.getvalue().strip(), 'headsimple')
def test_meddling_middleware(self):
middleware = (
'statictemplate.tests.MeddlingMiddleware',
)
settings.MIDDLEWARE_CLASSES = middleware
output = make_static('simple')
self.assertEqual(output, 'headsimple')
self.assertEqual(settings.MIDDLEWARE_CLASSES, middleware)
|
<commit_before># -*- coding: utf-8 -*-
from StringIO import StringIO
from django.conf import settings
from django.core.management import call_command
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from statictemplate.management.commands.statictemplate import make_static
import unittest
class TestLoader(BaseLoader):
is_usable = True
templates = {
'simple': '{% extends "base" %}{% block content %}simple{% endblock %}',
'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}',
}
def load_template_source(self, template_name, template_dirs=None):
found = self.templates.get(template_name, None)
if not found: # pragma: no cover
raise TemplateDoesNotExist(template_name)
return found, template_name
class StaticTemplateTests(unittest.TestCase):
def setUp(self):
settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader']
def test_python_api(self):
output = make_static('simple')
self.assertEqual(output, 'headsimple')
def test_call_command(self):
sio = StringIO()
call_command('statictemplate', 'simple', stdout=sio)
self.assertEqual(sio.getvalue().strip(), 'headsimple')
<commit_msg>Add test for meddling middleware<commit_after># -*- coding: utf-8 -*-
from StringIO import StringIO
from django.conf import settings
from django.http import HttpResponseRedirect
from django.core.management import call_command
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from statictemplate.management.commands.statictemplate import make_static
import unittest
class TestLoader(BaseLoader):
is_usable = True
templates = {
'simple': '{% extends "base" %}{% block content %}simple{% endblock %}',
'base': '{% block head %}head{% endblock %}{% block content %}content{% endblock %}',
}
def load_template_source(self, template_name, template_dirs=None):
found = self.templates.get(template_name, None)
if not found: # pragma: no cover
raise TemplateDoesNotExist(template_name)
return found, template_name
class MeddlingMiddleware(object):
def process_request(self, request):
return HttpResponseRedirect('/foobarbaz')
class StaticTemplateTests(unittest.TestCase):
def setUp(self):
settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader']
def test_python_api(self):
output = make_static('simple')
self.assertEqual(output, 'headsimple')
def test_call_command(self):
sio = StringIO()
call_command('statictemplate', 'simple', stdout=sio)
self.assertEqual(sio.getvalue().strip(), 'headsimple')
def test_meddling_middleware(self):
middleware = (
'statictemplate.tests.MeddlingMiddleware',
)
settings.MIDDLEWARE_CLASSES = middleware
output = make_static('simple')
self.assertEqual(output, 'headsimple')
self.assertEqual(settings.MIDDLEWARE_CLASSES, middleware)
|
cd00388bdc4c1963ac8ff81f9b7132ba32272fc8
|
adwords_client/__init__.py
|
adwords_client/__init__.py
|
__version__ = '17.07' # Date based versioning
# See: https://packaging.python.org/tutorials/distributing-packages/#date-based-versioning
|
"""
Copyright 2017 GetNinjas
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.
"""
__version__ = '17.07' # Date based versioning
# See: https://packaging.python.org/tutorials/distributing-packages/#date-based-versioning
import sys
print(__doc__, file=sys.stderr, flush=True)
|
Print license on each import
|
Print license on each import
|
Python
|
apache-2.0
|
getninjas/adwords-client
|
__version__ = '17.07' # Date based versioning
# See: https://packaging.python.org/tutorials/distributing-packages/#date-based-versioning
Print license on each import
|
"""
Copyright 2017 GetNinjas
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.
"""
__version__ = '17.07' # Date based versioning
# See: https://packaging.python.org/tutorials/distributing-packages/#date-based-versioning
import sys
print(__doc__, file=sys.stderr, flush=True)
|
<commit_before>__version__ = '17.07' # Date based versioning
# See: https://packaging.python.org/tutorials/distributing-packages/#date-based-versioning
<commit_msg>Print license on each import<commit_after>
|
"""
Copyright 2017 GetNinjas
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.
"""
__version__ = '17.07' # Date based versioning
# See: https://packaging.python.org/tutorials/distributing-packages/#date-based-versioning
import sys
print(__doc__, file=sys.stderr, flush=True)
|
__version__ = '17.07' # Date based versioning
# See: https://packaging.python.org/tutorials/distributing-packages/#date-based-versioning
Print license on each import"""
Copyright 2017 GetNinjas
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.
"""
__version__ = '17.07' # Date based versioning
# See: https://packaging.python.org/tutorials/distributing-packages/#date-based-versioning
import sys
print(__doc__, file=sys.stderr, flush=True)
|
<commit_before>__version__ = '17.07' # Date based versioning
# See: https://packaging.python.org/tutorials/distributing-packages/#date-based-versioning
<commit_msg>Print license on each import<commit_after>"""
Copyright 2017 GetNinjas
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.
"""
__version__ = '17.07' # Date based versioning
# See: https://packaging.python.org/tutorials/distributing-packages/#date-based-versioning
import sys
print(__doc__, file=sys.stderr, flush=True)
|
f692ca5449941a14e1356d089f63e9b4ac261545
|
turbustat/tests/test_stat_moments.py
|
turbustat/tests/test_stat_moments.py
|
# Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class TestMoments(TestCase):
def test_moments(self):
self.tester = StatMoments(dataset1["moment0"])
self.tester.run()
# This simply ensures the data set will run.
# There are subtle differences due to matching the bins
# between the sets. So all tests are completed below
def test_moment_distance(self):
self.tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
self.tester_dist.distance_metric()
assert np.allclose(self.tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(self.tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(self.tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(self.tester_dist.skewness_distance,
computed_distances['skewness_distance'])
|
# Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
import pytest
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
def test_moments():
tester = StatMoments(dataset1["moment0"])
tester.run()
# TODO: Add more test comparisons. Save the total moments over the whole
# arrays, portions of the local arrays, and the histogram values.
def test_moments_units():
pass
def test_moments_nonperiodic():
pass
def test_moments_custombins():
pass
def test_moment_distance():
tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
tester_dist.distance_metric()
assert np.allclose(tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(tester_dist.skewness_distance,
computed_distances['skewness_distance'])
|
Update StatMoments tests (passing); empty tests to be filled in when the testing data is updated
|
Update StatMoments tests (passing); empty tests to be filled in when the testing data is updated
|
Python
|
mit
|
e-koch/TurbuStat,Astroua/TurbuStat
|
# Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class TestMoments(TestCase):
def test_moments(self):
self.tester = StatMoments(dataset1["moment0"])
self.tester.run()
# This simply ensures the data set will run.
# There are subtle differences due to matching the bins
# between the sets. So all tests are completed below
def test_moment_distance(self):
self.tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
self.tester_dist.distance_metric()
assert np.allclose(self.tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(self.tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(self.tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(self.tester_dist.skewness_distance,
computed_distances['skewness_distance'])
Update StatMoments tests (passing); empty tests to be filled in when the testing data is updated
|
# Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
import pytest
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
def test_moments():
tester = StatMoments(dataset1["moment0"])
tester.run()
# TODO: Add more test comparisons. Save the total moments over the whole
# arrays, portions of the local arrays, and the histogram values.
def test_moments_units():
pass
def test_moments_nonperiodic():
pass
def test_moments_custombins():
pass
def test_moment_distance():
tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
tester_dist.distance_metric()
assert np.allclose(tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(tester_dist.skewness_distance,
computed_distances['skewness_distance'])
|
<commit_before># Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class TestMoments(TestCase):
def test_moments(self):
self.tester = StatMoments(dataset1["moment0"])
self.tester.run()
# This simply ensures the data set will run.
# There are subtle differences due to matching the bins
# between the sets. So all tests are completed below
def test_moment_distance(self):
self.tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
self.tester_dist.distance_metric()
assert np.allclose(self.tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(self.tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(self.tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(self.tester_dist.skewness_distance,
computed_distances['skewness_distance'])
<commit_msg>Update StatMoments tests (passing); empty tests to be filled in when the testing data is updated<commit_after>
|
# Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
import pytest
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
def test_moments():
tester = StatMoments(dataset1["moment0"])
tester.run()
# TODO: Add more test comparisons. Save the total moments over the whole
# arrays, portions of the local arrays, and the histogram values.
def test_moments_units():
pass
def test_moments_nonperiodic():
pass
def test_moments_custombins():
pass
def test_moment_distance():
tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
tester_dist.distance_metric()
assert np.allclose(tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(tester_dist.skewness_distance,
computed_distances['skewness_distance'])
|
# Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class TestMoments(TestCase):
def test_moments(self):
self.tester = StatMoments(dataset1["moment0"])
self.tester.run()
# This simply ensures the data set will run.
# There are subtle differences due to matching the bins
# between the sets. So all tests are completed below
def test_moment_distance(self):
self.tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
self.tester_dist.distance_metric()
assert np.allclose(self.tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(self.tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(self.tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(self.tester_dist.skewness_distance,
computed_distances['skewness_distance'])
Update StatMoments tests (passing); empty tests to be filled in when the testing data is updated# Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
import pytest
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
def test_moments():
tester = StatMoments(dataset1["moment0"])
tester.run()
# TODO: Add more test comparisons. Save the total moments over the whole
# arrays, portions of the local arrays, and the histogram values.
def test_moments_units():
pass
def test_moments_nonperiodic():
pass
def test_moments_custombins():
pass
def test_moment_distance():
tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
tester_dist.distance_metric()
assert np.allclose(tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(tester_dist.skewness_distance,
computed_distances['skewness_distance'])
|
<commit_before># Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class TestMoments(TestCase):
def test_moments(self):
self.tester = StatMoments(dataset1["moment0"])
self.tester.run()
# This simply ensures the data set will run.
# There are subtle differences due to matching the bins
# between the sets. So all tests are completed below
def test_moment_distance(self):
self.tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
self.tester_dist.distance_metric()
assert np.allclose(self.tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(self.tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(self.tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(self.tester_dist.skewness_distance,
computed_distances['skewness_distance'])
<commit_msg>Update StatMoments tests (passing); empty tests to be filled in when the testing data is updated<commit_after># Licensed under an MIT open source license - see LICENSE
'''
Test functions for Kurtosis
'''
import pytest
import numpy as np
import numpy.testing as npt
from ..statistics import StatMoments, StatMoments_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
def test_moments():
tester = StatMoments(dataset1["moment0"])
tester.run()
# TODO: Add more test comparisons. Save the total moments over the whole
# arrays, portions of the local arrays, and the histogram values.
def test_moments_units():
pass
def test_moments_nonperiodic():
pass
def test_moments_custombins():
pass
def test_moment_distance():
tester_dist = \
StatMoments_Distance(dataset1["moment0"],
dataset2["moment0"])
tester_dist.distance_metric()
assert np.allclose(tester_dist.moments1.kurtosis_hist[1],
computed_data['kurtosis_val'])
assert np.allclose(tester_dist.moments1.skewness_hist[1],
computed_data['skewness_val'])
npt.assert_almost_equal(tester_dist.kurtosis_distance,
computed_distances['kurtosis_distance'])
npt.assert_almost_equal(tester_dist.skewness_distance,
computed_distances['skewness_distance'])
|
3188e993ccbd8ae49c43f21ccb35947364030bcd
|
seabird/test/test_rules.py
|
seabird/test/test_rules.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check the rules
"""
import os
import pkg_resources
import json
import re
import seabird
def test_load_available_rules():
""" Try to read all available rules
https://github.com/castelao/seabird/issues/7
"""
rules_dir = 'rules'
rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir)
rule_files = [f for f in rule_files if re.match('^cnv.*json$', f)]
for rule_file in rule_files:
print("loading rule: %s", (rule_file))
text = pkg_resources.resource_string(
seabird.__name__,
os.path.join(rules_dir, rule_file))
rule = json.loads(text.decode('utf-8'), encoding="utf-8")
assert type(rule) == dict
assert len(rule.keys()) > 0
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check the rules
"""
import os
import pkg_resources
import json
import re
import seabird
def test_load_available_rules():
""" Try to read all available rules
https://github.com/castelao/seabird/issues/7
"""
rules_dir = 'rules'
rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir)
rule_files = [f for f in rule_files if re.match('^(?!refnames).*json$', f)]
for rule_file in rule_files:
print("loading rule: %s", (rule_file))
text = pkg_resources.resource_string(
seabird.__name__,
os.path.join(rules_dir, rule_file))
rule = json.loads(text.decode('utf-8'), encoding="utf-8")
assert type(rule) == dict
assert len(rule.keys()) > 0
|
Test all rules but refnames.
|
Test all rules but refnames.
|
Python
|
bsd-3-clause
|
castelao/seabird
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check the rules
"""
import os
import pkg_resources
import json
import re
import seabird
def test_load_available_rules():
""" Try to read all available rules
https://github.com/castelao/seabird/issues/7
"""
rules_dir = 'rules'
rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir)
rule_files = [f for f in rule_files if re.match('^cnv.*json$', f)]
for rule_file in rule_files:
print("loading rule: %s", (rule_file))
text = pkg_resources.resource_string(
seabird.__name__,
os.path.join(rules_dir, rule_file))
rule = json.loads(text.decode('utf-8'), encoding="utf-8")
assert type(rule) == dict
assert len(rule.keys()) > 0
Test all rules but refnames.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check the rules
"""
import os
import pkg_resources
import json
import re
import seabird
def test_load_available_rules():
""" Try to read all available rules
https://github.com/castelao/seabird/issues/7
"""
rules_dir = 'rules'
rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir)
rule_files = [f for f in rule_files if re.match('^(?!refnames).*json$', f)]
for rule_file in rule_files:
print("loading rule: %s", (rule_file))
text = pkg_resources.resource_string(
seabird.__name__,
os.path.join(rules_dir, rule_file))
rule = json.loads(text.decode('utf-8'), encoding="utf-8")
assert type(rule) == dict
assert len(rule.keys()) > 0
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check the rules
"""
import os
import pkg_resources
import json
import re
import seabird
def test_load_available_rules():
""" Try to read all available rules
https://github.com/castelao/seabird/issues/7
"""
rules_dir = 'rules'
rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir)
rule_files = [f for f in rule_files if re.match('^cnv.*json$', f)]
for rule_file in rule_files:
print("loading rule: %s", (rule_file))
text = pkg_resources.resource_string(
seabird.__name__,
os.path.join(rules_dir, rule_file))
rule = json.loads(text.decode('utf-8'), encoding="utf-8")
assert type(rule) == dict
assert len(rule.keys()) > 0
<commit_msg>Test all rules but refnames.<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check the rules
"""
import os
import pkg_resources
import json
import re
import seabird
def test_load_available_rules():
""" Try to read all available rules
https://github.com/castelao/seabird/issues/7
"""
rules_dir = 'rules'
rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir)
rule_files = [f for f in rule_files if re.match('^(?!refnames).*json$', f)]
for rule_file in rule_files:
print("loading rule: %s", (rule_file))
text = pkg_resources.resource_string(
seabird.__name__,
os.path.join(rules_dir, rule_file))
rule = json.loads(text.decode('utf-8'), encoding="utf-8")
assert type(rule) == dict
assert len(rule.keys()) > 0
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check the rules
"""
import os
import pkg_resources
import json
import re
import seabird
def test_load_available_rules():
""" Try to read all available rules
https://github.com/castelao/seabird/issues/7
"""
rules_dir = 'rules'
rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir)
rule_files = [f for f in rule_files if re.match('^cnv.*json$', f)]
for rule_file in rule_files:
print("loading rule: %s", (rule_file))
text = pkg_resources.resource_string(
seabird.__name__,
os.path.join(rules_dir, rule_file))
rule = json.loads(text.decode('utf-8'), encoding="utf-8")
assert type(rule) == dict
assert len(rule.keys()) > 0
Test all rules but refnames.#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check the rules
"""
import os
import pkg_resources
import json
import re
import seabird
def test_load_available_rules():
""" Try to read all available rules
https://github.com/castelao/seabird/issues/7
"""
rules_dir = 'rules'
rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir)
rule_files = [f for f in rule_files if re.match('^(?!refnames).*json$', f)]
for rule_file in rule_files:
print("loading rule: %s", (rule_file))
text = pkg_resources.resource_string(
seabird.__name__,
os.path.join(rules_dir, rule_file))
rule = json.loads(text.decode('utf-8'), encoding="utf-8")
assert type(rule) == dict
assert len(rule.keys()) > 0
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check the rules
"""
import os
import pkg_resources
import json
import re
import seabird
def test_load_available_rules():
""" Try to read all available rules
https://github.com/castelao/seabird/issues/7
"""
rules_dir = 'rules'
rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir)
rule_files = [f for f in rule_files if re.match('^cnv.*json$', f)]
for rule_file in rule_files:
print("loading rule: %s", (rule_file))
text = pkg_resources.resource_string(
seabird.__name__,
os.path.join(rules_dir, rule_file))
rule = json.loads(text.decode('utf-8'), encoding="utf-8")
assert type(rule) == dict
assert len(rule.keys()) > 0
<commit_msg>Test all rules but refnames.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check the rules
"""
import os
import pkg_resources
import json
import re
import seabird
def test_load_available_rules():
""" Try to read all available rules
https://github.com/castelao/seabird/issues/7
"""
rules_dir = 'rules'
rule_files = pkg_resources.resource_listdir(seabird.__name__, rules_dir)
rule_files = [f for f in rule_files if re.match('^(?!refnames).*json$', f)]
for rule_file in rule_files:
print("loading rule: %s", (rule_file))
text = pkg_resources.resource_string(
seabird.__name__,
os.path.join(rules_dir, rule_file))
rule = json.loads(text.decode('utf-8'), encoding="utf-8")
assert type(rule) == dict
assert len(rule.keys()) > 0
|
f3eb6cbc0f518ed8ec6098d3dfdd205ed734022c
|
eval_kernel/eval_kernel.py
|
eval_kernel/eval_kernel.py
|
from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
resp = python_magic.eval(code.strip())
if not resp is None:
self.Print(str(resp))
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
|
from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
return python_magic.eval(code.strip())
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
|
Return python eval instead of printing it
|
Return python eval instead of printing it
|
Python
|
bsd-3-clause
|
Calysto/metakernel
|
from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
resp = python_magic.eval(code.strip())
if not resp is None:
self.Print(str(resp))
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
Return python eval instead of printing it
|
from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
return python_magic.eval(code.strip())
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
|
<commit_before>from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
resp = python_magic.eval(code.strip())
if not resp is None:
self.Print(str(resp))
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
<commit_msg>Return python eval instead of printing it<commit_after>
|
from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
return python_magic.eval(code.strip())
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
|
from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
resp = python_magic.eval(code.strip())
if not resp is None:
self.Print(str(resp))
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
Return python eval instead of printing itfrom __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
return python_magic.eval(code.strip())
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
|
<commit_before>from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
resp = python_magic.eval(code.strip())
if not resp is None:
self.Print(str(resp))
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
<commit_msg>Return python eval instead of printing it<commit_after>from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
def get_usage(self):
return "This is a usage statement."
def set_variable(self, name, value):
"""
Set a variable in the kernel language.
"""
self.env[name] = value
def get_variable(self, name):
"""
Get a variable from the kernel language.
"""
return self.env.get(name, None)
def do_execute_direct(self, code):
python_magic = self.line_magics['python']
return python_magic.eval(code.strip())
def get_completions(self, token):
python_magic = self.line_magics['python']
return python_magic.get_completions(token)
def get_kernel_help_on(self, expr, level=0):
python_magic = self.line_magics['python']
return python_magic.get_help_on(expr, level)
if __name__ == '__main__':
from IPython.kernel.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=EvalKernel)
|
a7be9a07a7f2d2556d6c93326098a00e0b2c67a8
|
tests/api/test_licenses.py
|
tests/api/test_licenses.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
"""pytest Licenses API wrapper tests and fixtures."""
import pytest
import ciscosparkapi
# Helper Functions
def get_list_of_licenses(api, orgId=None, max=None):
return api.licenses.list(orgId=orgId, max=max)
def get_license_by_id(api, licenseId):
return api.licenses.get(licenseId)
def is_valid_license(obj):
return isinstance(obj, ciscosparkapi.License) and obj.id is not None
def are_valid_licenses(iterable):
return all([is_valid_license(obj) for obj in iterable])
# pytest Fixtures
@pytest.fixture(scope="session")
def licenses_list(api):
return list(get_list_of_licenses(api))
@pytest.fixture(scope="session")
def licenses_dict(licenses_list):
return {lic.name: lic for lic in licenses_list}
# Tests
class TestLicensesAPI(object):
"""Test LicensesAPI methods."""
def test_list_licenses(self, licenses_list):
assert are_valid_licenses(licenses_list)
def test_list_licenses_with_paging(self, api):
paging_generator = get_list_of_licenses(api, max=1)
licenses = list(paging_generator)
assert licenses > 1
assert are_valid_licenses(licenses)
def test_get_licenses_for_organization(self, api, me):
licenses = list(get_list_of_licenses(api, orgId=me.orgId))
assert are_valid_licenses(licenses)
def test_get_license_by_id(self, api, licenses_list):
assert len(licenses_list) >= 1
license_id = licenses_list[0].id
license = get_license_by_id(api, licenseId=license_id)
assert is_valid_license(license)
|
Add tests and fixtures for the Licenses API wrapper
|
Add tests and fixtures for the Licenses API wrapper
|
Python
|
mit
|
jbogarin/ciscosparkapi
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Add tests and fixtures for the Licenses API wrapper
|
# -*- coding: utf-8 -*-
"""pytest Licenses API wrapper tests and fixtures."""
import pytest
import ciscosparkapi
# Helper Functions
def get_list_of_licenses(api, orgId=None, max=None):
return api.licenses.list(orgId=orgId, max=max)
def get_license_by_id(api, licenseId):
return api.licenses.get(licenseId)
def is_valid_license(obj):
return isinstance(obj, ciscosparkapi.License) and obj.id is not None
def are_valid_licenses(iterable):
return all([is_valid_license(obj) for obj in iterable])
# pytest Fixtures
@pytest.fixture(scope="session")
def licenses_list(api):
return list(get_list_of_licenses(api))
@pytest.fixture(scope="session")
def licenses_dict(licenses_list):
return {lic.name: lic for lic in licenses_list}
# Tests
class TestLicensesAPI(object):
"""Test LicensesAPI methods."""
def test_list_licenses(self, licenses_list):
assert are_valid_licenses(licenses_list)
def test_list_licenses_with_paging(self, api):
paging_generator = get_list_of_licenses(api, max=1)
licenses = list(paging_generator)
assert licenses > 1
assert are_valid_licenses(licenses)
def test_get_licenses_for_organization(self, api, me):
licenses = list(get_list_of_licenses(api, orgId=me.orgId))
assert are_valid_licenses(licenses)
def test_get_license_by_id(self, api, licenses_list):
assert len(licenses_list) >= 1
license_id = licenses_list[0].id
license = get_license_by_id(api, licenseId=license_id)
assert is_valid_license(license)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
<commit_msg>Add tests and fixtures for the Licenses API wrapper<commit_after>
|
# -*- coding: utf-8 -*-
"""pytest Licenses API wrapper tests and fixtures."""
import pytest
import ciscosparkapi
# Helper Functions
def get_list_of_licenses(api, orgId=None, max=None):
return api.licenses.list(orgId=orgId, max=max)
def get_license_by_id(api, licenseId):
return api.licenses.get(licenseId)
def is_valid_license(obj):
return isinstance(obj, ciscosparkapi.License) and obj.id is not None
def are_valid_licenses(iterable):
return all([is_valid_license(obj) for obj in iterable])
# pytest Fixtures
@pytest.fixture(scope="session")
def licenses_list(api):
return list(get_list_of_licenses(api))
@pytest.fixture(scope="session")
def licenses_dict(licenses_list):
return {lic.name: lic for lic in licenses_list}
# Tests
class TestLicensesAPI(object):
"""Test LicensesAPI methods."""
def test_list_licenses(self, licenses_list):
assert are_valid_licenses(licenses_list)
def test_list_licenses_with_paging(self, api):
paging_generator = get_list_of_licenses(api, max=1)
licenses = list(paging_generator)
assert licenses > 1
assert are_valid_licenses(licenses)
def test_get_licenses_for_organization(self, api, me):
licenses = list(get_list_of_licenses(api, orgId=me.orgId))
assert are_valid_licenses(licenses)
def test_get_license_by_id(self, api, licenses_list):
assert len(licenses_list) >= 1
license_id = licenses_list[0].id
license = get_license_by_id(api, licenseId=license_id)
assert is_valid_license(license)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Add tests and fixtures for the Licenses API wrapper# -*- coding: utf-8 -*-
"""pytest Licenses API wrapper tests and fixtures."""
import pytest
import ciscosparkapi
# Helper Functions
def get_list_of_licenses(api, orgId=None, max=None):
return api.licenses.list(orgId=orgId, max=max)
def get_license_by_id(api, licenseId):
return api.licenses.get(licenseId)
def is_valid_license(obj):
return isinstance(obj, ciscosparkapi.License) and obj.id is not None
def are_valid_licenses(iterable):
return all([is_valid_license(obj) for obj in iterable])
# pytest Fixtures
@pytest.fixture(scope="session")
def licenses_list(api):
return list(get_list_of_licenses(api))
@pytest.fixture(scope="session")
def licenses_dict(licenses_list):
return {lic.name: lic for lic in licenses_list}
# Tests
class TestLicensesAPI(object):
"""Test LicensesAPI methods."""
def test_list_licenses(self, licenses_list):
assert are_valid_licenses(licenses_list)
def test_list_licenses_with_paging(self, api):
paging_generator = get_list_of_licenses(api, max=1)
licenses = list(paging_generator)
assert licenses > 1
assert are_valid_licenses(licenses)
def test_get_licenses_for_organization(self, api, me):
licenses = list(get_list_of_licenses(api, orgId=me.orgId))
assert are_valid_licenses(licenses)
def test_get_license_by_id(self, api, licenses_list):
assert len(licenses_list) >= 1
license_id = licenses_list[0].id
license = get_license_by_id(api, licenseId=license_id)
assert is_valid_license(license)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
<commit_msg>Add tests and fixtures for the Licenses API wrapper<commit_after># -*- coding: utf-8 -*-
"""pytest Licenses API wrapper tests and fixtures."""
import pytest
import ciscosparkapi
# Helper Functions
def get_list_of_licenses(api, orgId=None, max=None):
return api.licenses.list(orgId=orgId, max=max)
def get_license_by_id(api, licenseId):
return api.licenses.get(licenseId)
def is_valid_license(obj):
return isinstance(obj, ciscosparkapi.License) and obj.id is not None
def are_valid_licenses(iterable):
return all([is_valid_license(obj) for obj in iterable])
# pytest Fixtures
@pytest.fixture(scope="session")
def licenses_list(api):
return list(get_list_of_licenses(api))
@pytest.fixture(scope="session")
def licenses_dict(licenses_list):
return {lic.name: lic for lic in licenses_list}
# Tests
class TestLicensesAPI(object):
"""Test LicensesAPI methods."""
def test_list_licenses(self, licenses_list):
assert are_valid_licenses(licenses_list)
def test_list_licenses_with_paging(self, api):
paging_generator = get_list_of_licenses(api, max=1)
licenses = list(paging_generator)
assert licenses > 1
assert are_valid_licenses(licenses)
def test_get_licenses_for_organization(self, api, me):
licenses = list(get_list_of_licenses(api, orgId=me.orgId))
assert are_valid_licenses(licenses)
def test_get_license_by_id(self, api, licenses_list):
assert len(licenses_list) >= 1
license_id = licenses_list[0].id
license = get_license_by_id(api, licenseId=license_id)
assert is_valid_license(license)
|
cf711889450bfe7d7147c170299cb15726a76b6c
|
sklearn_porter/language/Ruby/__init__.py
|
sklearn_porter/language/Ruby/__init__.py
|
# -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{name} = {value}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
|
# -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{{ name }} = {{ value }}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
|
Fix placeholders in template string
|
feature/oop-api-refactoring: Fix placeholders in template string
|
Python
|
bsd-3-clause
|
nok/sklearn-porter
|
# -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{name} = {value}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
feature/oop-api-refactoring: Fix placeholders in template string
|
# -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{{ name }} = {{ value }}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
|
<commit_before># -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{name} = {value}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
<commit_msg>feature/oop-api-refactoring: Fix placeholders in template string<commit_after>
|
# -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{{ name }} = {{ value }}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
|
# -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{name} = {value}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
feature/oop-api-refactoring: Fix placeholders in template string# -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{{ name }} = {{ value }}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
|
<commit_before># -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{name} = {value}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
<commit_msg>feature/oop-api-refactoring: Fix placeholders in template string<commit_after># -*- coding: utf-8 -*-
from sklearn_porter.language.LanguageABC import LanguageABC
class Ruby(LanguageABC):
KEY = 'ruby'
LABEL = 'Ruby'
DEPENDENCIES = ['ruby']
TEMP_DIR = 'ruby'
SUFFIX = 'rb'
CMD_COMPILE = None
# ruby estimator.rb <args>
CMD_EXECUTE = 'ruby {src_path}'
# yapf: disable
TEMPLATES = {
'init': '{{ name }} = {{ value }}',
# if/else condition:
'if': 'if {{ a }} {{ op }} {{ b }}',
'else': 'else',
'endif': 'end',
# Basics:
'indent': ' ',
'join': ' ',
'type': '{{ value }}',
# Arrays:
'in_brackets': '[{{ value }}]',
'arr[]': '{{ name }} = [{{ values }}]',
'arr[][]': '{{ name }} = [{{ values }}]',
'arr[][][]': '{{ name }} = [{{ values }}]',
# Primitive data types:
'int': '',
'double': ''
}
# yapf: enable
|
4139ff0361c499f5b9bc48b9ac6013b5bc61e955
|
test/test_exceptions.py
|
test/test_exceptions.py
|
import unittest
from pymodbus3.exceptions import *
class SimpleExceptionsTest(unittest.TestCase):
"""
This is the unittest for the pymodbus3.exceptions module
"""
def setUp(self):
""" Initializes the test environment """
self.exceptions = [
ModbusException("bad base"),
ModbusIOException("bad register"),
ParameterException("bad parameter"),
NotImplementedError("bad function"),
ConnectionException("bad connection"),
]
def tearDown(self):
""" Cleans up the test environment """
pass
def test_exceptions(self):
""" Test all module exceptions """
for ex in self.exceptions:
try:
raise ex
except ModbusException as ex:
self.assertTrue("Modbus Error:" in str(ex))
pass
else:
self.fail("Excepted a ModbusExceptions")
#---------------------------------------------------------------------------#
# Main
#---------------------------------------------------------------------------#
if __name__ == "__main__":
unittest.main()
|
import unittest
from pymodbus3.exceptions import *
class SimpleExceptionsTest(unittest.TestCase):
"""
This is the unittest for the pymodbus3.exceptions module
"""
def setUp(self):
""" Initializes the test environment """
self.exceptions = [
ModbusException("bad base"),
ModbusIOException("bad register"),
ParameterException("bad parameter"),
ConnectionException("bad connection"),
]
def tearDown(self):
""" Cleans up the test environment """
pass
def test_exceptions(self):
""" Test all module exceptions """
for ex in self.exceptions:
try:
raise ex
except ModbusException as ex:
self.assertTrue("Modbus Error:" in str(ex))
pass
else:
self.fail("Excepted a ModbusExceptions")
#---------------------------------------------------------------------------#
# Main
#---------------------------------------------------------------------------#
if __name__ == "__main__":
unittest.main()
|
Remove test of built-in "NotImplementedError" exception.
|
Remove test of built-in "NotImplementedError" exception.
|
Python
|
bsd-3-clause
|
gregorschatz/pymodbus3,uzumaxy/pymodbus3
|
import unittest
from pymodbus3.exceptions import *
class SimpleExceptionsTest(unittest.TestCase):
"""
This is the unittest for the pymodbus3.exceptions module
"""
def setUp(self):
""" Initializes the test environment """
self.exceptions = [
ModbusException("bad base"),
ModbusIOException("bad register"),
ParameterException("bad parameter"),
NotImplementedError("bad function"),
ConnectionException("bad connection"),
]
def tearDown(self):
""" Cleans up the test environment """
pass
def test_exceptions(self):
""" Test all module exceptions """
for ex in self.exceptions:
try:
raise ex
except ModbusException as ex:
self.assertTrue("Modbus Error:" in str(ex))
pass
else:
self.fail("Excepted a ModbusExceptions")
#---------------------------------------------------------------------------#
# Main
#---------------------------------------------------------------------------#
if __name__ == "__main__":
unittest.main()
Remove test of built-in "NotImplementedError" exception.
|
import unittest
from pymodbus3.exceptions import *
class SimpleExceptionsTest(unittest.TestCase):
"""
This is the unittest for the pymodbus3.exceptions module
"""
def setUp(self):
""" Initializes the test environment """
self.exceptions = [
ModbusException("bad base"),
ModbusIOException("bad register"),
ParameterException("bad parameter"),
ConnectionException("bad connection"),
]
def tearDown(self):
""" Cleans up the test environment """
pass
def test_exceptions(self):
""" Test all module exceptions """
for ex in self.exceptions:
try:
raise ex
except ModbusException as ex:
self.assertTrue("Modbus Error:" in str(ex))
pass
else:
self.fail("Excepted a ModbusExceptions")
#---------------------------------------------------------------------------#
# Main
#---------------------------------------------------------------------------#
if __name__ == "__main__":
unittest.main()
|
<commit_before>import unittest
from pymodbus3.exceptions import *
class SimpleExceptionsTest(unittest.TestCase):
"""
This is the unittest for the pymodbus3.exceptions module
"""
def setUp(self):
""" Initializes the test environment """
self.exceptions = [
ModbusException("bad base"),
ModbusIOException("bad register"),
ParameterException("bad parameter"),
NotImplementedError("bad function"),
ConnectionException("bad connection"),
]
def tearDown(self):
""" Cleans up the test environment """
pass
def test_exceptions(self):
""" Test all module exceptions """
for ex in self.exceptions:
try:
raise ex
except ModbusException as ex:
self.assertTrue("Modbus Error:" in str(ex))
pass
else:
self.fail("Excepted a ModbusExceptions")
#---------------------------------------------------------------------------#
# Main
#---------------------------------------------------------------------------#
if __name__ == "__main__":
unittest.main()
<commit_msg>Remove test of built-in "NotImplementedError" exception.<commit_after>
|
import unittest
from pymodbus3.exceptions import *
class SimpleExceptionsTest(unittest.TestCase):
"""
This is the unittest for the pymodbus3.exceptions module
"""
def setUp(self):
""" Initializes the test environment """
self.exceptions = [
ModbusException("bad base"),
ModbusIOException("bad register"),
ParameterException("bad parameter"),
ConnectionException("bad connection"),
]
def tearDown(self):
""" Cleans up the test environment """
pass
def test_exceptions(self):
""" Test all module exceptions """
for ex in self.exceptions:
try:
raise ex
except ModbusException as ex:
self.assertTrue("Modbus Error:" in str(ex))
pass
else:
self.fail("Excepted a ModbusExceptions")
#---------------------------------------------------------------------------#
# Main
#---------------------------------------------------------------------------#
if __name__ == "__main__":
unittest.main()
|
import unittest
from pymodbus3.exceptions import *
class SimpleExceptionsTest(unittest.TestCase):
"""
This is the unittest for the pymodbus3.exceptions module
"""
def setUp(self):
""" Initializes the test environment """
self.exceptions = [
ModbusException("bad base"),
ModbusIOException("bad register"),
ParameterException("bad parameter"),
NotImplementedError("bad function"),
ConnectionException("bad connection"),
]
def tearDown(self):
""" Cleans up the test environment """
pass
def test_exceptions(self):
""" Test all module exceptions """
for ex in self.exceptions:
try:
raise ex
except ModbusException as ex:
self.assertTrue("Modbus Error:" in str(ex))
pass
else:
self.fail("Excepted a ModbusExceptions")
#---------------------------------------------------------------------------#
# Main
#---------------------------------------------------------------------------#
if __name__ == "__main__":
unittest.main()
Remove test of built-in "NotImplementedError" exception.import unittest
from pymodbus3.exceptions import *
class SimpleExceptionsTest(unittest.TestCase):
"""
This is the unittest for the pymodbus3.exceptions module
"""
def setUp(self):
""" Initializes the test environment """
self.exceptions = [
ModbusException("bad base"),
ModbusIOException("bad register"),
ParameterException("bad parameter"),
ConnectionException("bad connection"),
]
def tearDown(self):
""" Cleans up the test environment """
pass
def test_exceptions(self):
""" Test all module exceptions """
for ex in self.exceptions:
try:
raise ex
except ModbusException as ex:
self.assertTrue("Modbus Error:" in str(ex))
pass
else:
self.fail("Excepted a ModbusExceptions")
#---------------------------------------------------------------------------#
# Main
#---------------------------------------------------------------------------#
if __name__ == "__main__":
unittest.main()
|
<commit_before>import unittest
from pymodbus3.exceptions import *
class SimpleExceptionsTest(unittest.TestCase):
"""
This is the unittest for the pymodbus3.exceptions module
"""
def setUp(self):
""" Initializes the test environment """
self.exceptions = [
ModbusException("bad base"),
ModbusIOException("bad register"),
ParameterException("bad parameter"),
NotImplementedError("bad function"),
ConnectionException("bad connection"),
]
def tearDown(self):
""" Cleans up the test environment """
pass
def test_exceptions(self):
""" Test all module exceptions """
for ex in self.exceptions:
try:
raise ex
except ModbusException as ex:
self.assertTrue("Modbus Error:" in str(ex))
pass
else:
self.fail("Excepted a ModbusExceptions")
#---------------------------------------------------------------------------#
# Main
#---------------------------------------------------------------------------#
if __name__ == "__main__":
unittest.main()
<commit_msg>Remove test of built-in "NotImplementedError" exception.<commit_after>import unittest
from pymodbus3.exceptions import *
class SimpleExceptionsTest(unittest.TestCase):
"""
This is the unittest for the pymodbus3.exceptions module
"""
def setUp(self):
""" Initializes the test environment """
self.exceptions = [
ModbusException("bad base"),
ModbusIOException("bad register"),
ParameterException("bad parameter"),
ConnectionException("bad connection"),
]
def tearDown(self):
""" Cleans up the test environment """
pass
def test_exceptions(self):
""" Test all module exceptions """
for ex in self.exceptions:
try:
raise ex
except ModbusException as ex:
self.assertTrue("Modbus Error:" in str(ex))
pass
else:
self.fail("Excepted a ModbusExceptions")
#---------------------------------------------------------------------------#
# Main
#---------------------------------------------------------------------------#
if __name__ == "__main__":
unittest.main()
|
beb7d06bd9f7b65ad3f25184ee05b808f893cfda
|
flatland/__init__.py
|
flatland/__init__.py
|
"""Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
|
"""Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
__version__='fix-imports'
|
Fix version string so that we can install with pip/setuptools
|
Fix version string so that we can install with pip/setuptools
|
Python
|
mit
|
wheeler-microfluidics/flatland-fork
|
"""Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
Fix version string so that we can install with pip/setuptools
|
"""Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
__version__='fix-imports'
|
<commit_before>"""Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
<commit_msg>Fix version string so that we can install with pip/setuptools<commit_after>
|
"""Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
__version__='fix-imports'
|
"""Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
Fix version string so that we can install with pip/setuptools"""Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
__version__='fix-imports'
|
<commit_before>"""Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
<commit_msg>Fix version string so that we can install with pip/setuptools<commit_after>"""Schemas for structured data."""
from flatland.exc import AdaptationError
from flatland.schema import Array, Boolean, Compound, Constrained, Container,\
Date, DateTime, DateYYYYMMDD, Decimal, Dict, Element, Enum, Float, Form,\
Integer, JoinedString, List, Long, Mapping, MultiValue, Number,\
Properties, Ref, Scalar, Sequence, Skip, SkipAll, SkipAllFalse,\
SparseDict, String, Time, Unevaluated, Unset
'''
from flatland.util.deferred import deferred_module
deferred_module.shadow(
'flatland',
{'exc': ('AdaptationError',),
'schema': ('Array',
'Boolean',
'Compound',
'Constrained',
'Container',
'Date',
'DateTime',
'DateYYYYMMDD',
'Decimal',
'Dict',
'Element',
'Enum',
'Float',
'Form',
'Integer',
'JoinedString',
'List',
'Long',
'Mapping',
'MultiValue',
'Number',
'Properties',
'Ref',
'Scalar',
'Sequence',
'Skip',
'SkipAll',
'SkipAllFalse',
'SparseDict',
'String',
'Time',
'Unevaluated',
'Unset',
),
'signals': (),
'util': ('Unspecified', 'class_cloner',),
'validation': (),
},
__version__='dev')
'''
__version__='fix-imports'
|
540bfff4a0622c3d9a001c09f0c39e65b29e1a0c
|
mrbelvedereci/build/management/commands/metaci_scheduled_jobs.py
|
mrbelvedereci/build/management/commands/metaci_scheduled_jobs.py
|
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from scheduler.models import RepeatableJob
class Command(BaseCommand):
help = 'Returns the API token for a given username. If one does not exist, a token is first created.'
def handle(self, *args, **options):
job, created = RepeatableJob.objects.get_or_create(
callable = 'mrbelvedereci.build.tasks.check_waiting_builds',
enabled = True,
name = 'check_waiting_builds',
queue = 'short',
defaults={
'interval': 1,
'interval_unit': 'minutes',
'scheduled_time': timezone.now(),
}
)
if created:
self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds'))
else:
self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds already exists'))
|
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from scheduler.models import RepeatableJob
class Command(BaseCommand):
help = 'Returns the API token for a given username. If one does not exist, a token is first created.'
def handle(self, *args, **options):
job, created = RepeatableJob.objects.get_or_create(
callable = 'mrbelvedereci.build.tasks.check_waiting_builds',
enabled = True,
name = 'check_waiting_builds',
queue = 'short',
defaults={
'interval': 1,
'interval_unit': 'minutes',
'scheduled_time': timezone.now(),
}
)
if created:
self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds with id {}'.format(job.id)))
else:
self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds with id {} already exists and is {}.'.format(job.id, 'enabled' if job.enabled else 'disabled')))
|
Add job id and enable/disabled status if the job already exists
|
Add job id and enable/disabled status if the job already exists
|
Python
|
bsd-3-clause
|
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
|
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from scheduler.models import RepeatableJob
class Command(BaseCommand):
help = 'Returns the API token for a given username. If one does not exist, a token is first created.'
def handle(self, *args, **options):
job, created = RepeatableJob.objects.get_or_create(
callable = 'mrbelvedereci.build.tasks.check_waiting_builds',
enabled = True,
name = 'check_waiting_builds',
queue = 'short',
defaults={
'interval': 1,
'interval_unit': 'minutes',
'scheduled_time': timezone.now(),
}
)
if created:
self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds'))
else:
self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds already exists'))
Add job id and enable/disabled status if the job already exists
|
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from scheduler.models import RepeatableJob
class Command(BaseCommand):
help = 'Returns the API token for a given username. If one does not exist, a token is first created.'
def handle(self, *args, **options):
job, created = RepeatableJob.objects.get_or_create(
callable = 'mrbelvedereci.build.tasks.check_waiting_builds',
enabled = True,
name = 'check_waiting_builds',
queue = 'short',
defaults={
'interval': 1,
'interval_unit': 'minutes',
'scheduled_time': timezone.now(),
}
)
if created:
self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds with id {}'.format(job.id)))
else:
self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds with id {} already exists and is {}.'.format(job.id, 'enabled' if job.enabled else 'disabled')))
|
<commit_before>from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from scheduler.models import RepeatableJob
class Command(BaseCommand):
help = 'Returns the API token for a given username. If one does not exist, a token is first created.'
def handle(self, *args, **options):
job, created = RepeatableJob.objects.get_or_create(
callable = 'mrbelvedereci.build.tasks.check_waiting_builds',
enabled = True,
name = 'check_waiting_builds',
queue = 'short',
defaults={
'interval': 1,
'interval_unit': 'minutes',
'scheduled_time': timezone.now(),
}
)
if created:
self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds'))
else:
self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds already exists'))
<commit_msg>Add job id and enable/disabled status if the job already exists<commit_after>
|
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from scheduler.models import RepeatableJob
class Command(BaseCommand):
help = 'Returns the API token for a given username. If one does not exist, a token is first created.'
def handle(self, *args, **options):
job, created = RepeatableJob.objects.get_or_create(
callable = 'mrbelvedereci.build.tasks.check_waiting_builds',
enabled = True,
name = 'check_waiting_builds',
queue = 'short',
defaults={
'interval': 1,
'interval_unit': 'minutes',
'scheduled_time': timezone.now(),
}
)
if created:
self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds with id {}'.format(job.id)))
else:
self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds with id {} already exists and is {}.'.format(job.id, 'enabled' if job.enabled else 'disabled')))
|
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from scheduler.models import RepeatableJob
class Command(BaseCommand):
help = 'Returns the API token for a given username. If one does not exist, a token is first created.'
def handle(self, *args, **options):
job, created = RepeatableJob.objects.get_or_create(
callable = 'mrbelvedereci.build.tasks.check_waiting_builds',
enabled = True,
name = 'check_waiting_builds',
queue = 'short',
defaults={
'interval': 1,
'interval_unit': 'minutes',
'scheduled_time': timezone.now(),
}
)
if created:
self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds'))
else:
self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds already exists'))
Add job id and enable/disabled status if the job already existsfrom django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from scheduler.models import RepeatableJob
class Command(BaseCommand):
help = 'Returns the API token for a given username. If one does not exist, a token is first created.'
def handle(self, *args, **options):
job, created = RepeatableJob.objects.get_or_create(
callable = 'mrbelvedereci.build.tasks.check_waiting_builds',
enabled = True,
name = 'check_waiting_builds',
queue = 'short',
defaults={
'interval': 1,
'interval_unit': 'minutes',
'scheduled_time': timezone.now(),
}
)
if created:
self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds with id {}'.format(job.id)))
else:
self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds with id {} already exists and is {}.'.format(job.id, 'enabled' if job.enabled else 'disabled')))
|
<commit_before>from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from scheduler.models import RepeatableJob
class Command(BaseCommand):
help = 'Returns the API token for a given username. If one does not exist, a token is first created.'
def handle(self, *args, **options):
job, created = RepeatableJob.objects.get_or_create(
callable = 'mrbelvedereci.build.tasks.check_waiting_builds',
enabled = True,
name = 'check_waiting_builds',
queue = 'short',
defaults={
'interval': 1,
'interval_unit': 'minutes',
'scheduled_time': timezone.now(),
}
)
if created:
self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds'))
else:
self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds already exists'))
<commit_msg>Add job id and enable/disabled status if the job already exists<commit_after>from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from scheduler.models import RepeatableJob
class Command(BaseCommand):
help = 'Returns the API token for a given username. If one does not exist, a token is first created.'
def handle(self, *args, **options):
job, created = RepeatableJob.objects.get_or_create(
callable = 'mrbelvedereci.build.tasks.check_waiting_builds',
enabled = True,
name = 'check_waiting_builds',
queue = 'short',
defaults={
'interval': 1,
'interval_unit': 'minutes',
'scheduled_time': timezone.now(),
}
)
if created:
self.stdout.write(self.style.SUCCESS('Created job check_waiting_builds with id {}'.format(job.id)))
else:
self.stdout.write(self.style.SUCCESS('Scheduled job check_waiting_builds with id {} already exists and is {}.'.format(job.id, 'enabled' if job.enabled else 'disabled')))
|
2d9c40ee9d41ef3e9c7d91410e410f1e764d8eb1
|
pdc/apps/release/migrations/0011_auto_20170912_1108.py
|
pdc/apps/release/migrations/0011_auto_20170912_1108.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('release', '0010_release_sigkey'),
]
operations = [
migrations.CreateModel(
name='CPE',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cpe', models.CharField(unique=True, max_length=300)),
('description', models.CharField(max_length=300, blank=True)),
],
),
migrations.AlterField(
model_name='variantcpe',
name='cpe',
field=models.ForeignKey(to='release.CPE'),
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('release', '0010_release_sigkey'),
]
operations = [
migrations.CreateModel(
name='CPE',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cpe', models.CharField(unique=True, max_length=300)),
('description', models.CharField(max_length=300, blank=True)),
],
),
migrations.RemoveField(
model_name='variantcpe',
name='cpe',
),
migrations.AddField(
model_name='variantcpe',
name='cpe',
field=models.ForeignKey(to='release.CPE'),
),
]
|
Fix migrating CPE field from string to ID
|
Fix migrating CPE field from string to ID
JIRA: PDC-2228
|
Python
|
mit
|
product-definition-center/product-definition-center,release-engineering/product-definition-center,release-engineering/product-definition-center,product-definition-center/product-definition-center,release-engineering/product-definition-center,product-definition-center/product-definition-center,release-engineering/product-definition-center,product-definition-center/product-definition-center
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('release', '0010_release_sigkey'),
]
operations = [
migrations.CreateModel(
name='CPE',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cpe', models.CharField(unique=True, max_length=300)),
('description', models.CharField(max_length=300, blank=True)),
],
),
migrations.AlterField(
model_name='variantcpe',
name='cpe',
field=models.ForeignKey(to='release.CPE'),
),
]
Fix migrating CPE field from string to ID
JIRA: PDC-2228
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('release', '0010_release_sigkey'),
]
operations = [
migrations.CreateModel(
name='CPE',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cpe', models.CharField(unique=True, max_length=300)),
('description', models.CharField(max_length=300, blank=True)),
],
),
migrations.RemoveField(
model_name='variantcpe',
name='cpe',
),
migrations.AddField(
model_name='variantcpe',
name='cpe',
field=models.ForeignKey(to='release.CPE'),
),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('release', '0010_release_sigkey'),
]
operations = [
migrations.CreateModel(
name='CPE',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cpe', models.CharField(unique=True, max_length=300)),
('description', models.CharField(max_length=300, blank=True)),
],
),
migrations.AlterField(
model_name='variantcpe',
name='cpe',
field=models.ForeignKey(to='release.CPE'),
),
]
<commit_msg>Fix migrating CPE field from string to ID
JIRA: PDC-2228<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('release', '0010_release_sigkey'),
]
operations = [
migrations.CreateModel(
name='CPE',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cpe', models.CharField(unique=True, max_length=300)),
('description', models.CharField(max_length=300, blank=True)),
],
),
migrations.RemoveField(
model_name='variantcpe',
name='cpe',
),
migrations.AddField(
model_name='variantcpe',
name='cpe',
field=models.ForeignKey(to='release.CPE'),
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('release', '0010_release_sigkey'),
]
operations = [
migrations.CreateModel(
name='CPE',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cpe', models.CharField(unique=True, max_length=300)),
('description', models.CharField(max_length=300, blank=True)),
],
),
migrations.AlterField(
model_name='variantcpe',
name='cpe',
field=models.ForeignKey(to='release.CPE'),
),
]
Fix migrating CPE field from string to ID
JIRA: PDC-2228# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('release', '0010_release_sigkey'),
]
operations = [
migrations.CreateModel(
name='CPE',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cpe', models.CharField(unique=True, max_length=300)),
('description', models.CharField(max_length=300, blank=True)),
],
),
migrations.RemoveField(
model_name='variantcpe',
name='cpe',
),
migrations.AddField(
model_name='variantcpe',
name='cpe',
field=models.ForeignKey(to='release.CPE'),
),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('release', '0010_release_sigkey'),
]
operations = [
migrations.CreateModel(
name='CPE',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cpe', models.CharField(unique=True, max_length=300)),
('description', models.CharField(max_length=300, blank=True)),
],
),
migrations.AlterField(
model_name='variantcpe',
name='cpe',
field=models.ForeignKey(to='release.CPE'),
),
]
<commit_msg>Fix migrating CPE field from string to ID
JIRA: PDC-2228<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('release', '0010_release_sigkey'),
]
operations = [
migrations.CreateModel(
name='CPE',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cpe', models.CharField(unique=True, max_length=300)),
('description', models.CharField(max_length=300, blank=True)),
],
),
migrations.RemoveField(
model_name='variantcpe',
name='cpe',
),
migrations.AddField(
model_name='variantcpe',
name='cpe',
field=models.ForeignKey(to='release.CPE'),
),
]
|
8929957d854f66c738c773bd629d9c6f18aa66a2
|
sports/admin.py
|
sports/admin.py
|
from django.contrib import admin
from .models import (Sport, Match, Session, CancelledSession)
@admin.register(Sport)
class SportAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(Match)
class MatchAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(CancelledSession)
class CancelledSessionAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
admin.site.register(Session)
|
from django.contrib import admin
from .models import (Sport, Match, Session, CancelledSession)
class SessionInline(admin.StackedInline):
model = Session
extra = 0
@admin.register(Sport)
class SportAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
inlines = [SessionInline,]
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(Match)
class MatchAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(CancelledSession)
class CancelledSessionAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
|
Move Session to Sport as an inline.
|
Move Session to Sport as an inline.
|
Python
|
mit
|
QSchulz/sportassociation,QSchulz/sportassociation,QSchulz/sportassociation
|
from django.contrib import admin
from .models import (Sport, Match, Session, CancelledSession)
@admin.register(Sport)
class SportAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(Match)
class MatchAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(CancelledSession)
class CancelledSessionAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
admin.site.register(Session)
Move Session to Sport as an inline.
|
from django.contrib import admin
from .models import (Sport, Match, Session, CancelledSession)
class SessionInline(admin.StackedInline):
model = Session
extra = 0
@admin.register(Sport)
class SportAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
inlines = [SessionInline,]
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(Match)
class MatchAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(CancelledSession)
class CancelledSessionAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
|
<commit_before>from django.contrib import admin
from .models import (Sport, Match, Session, CancelledSession)
@admin.register(Sport)
class SportAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(Match)
class MatchAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(CancelledSession)
class CancelledSessionAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
admin.site.register(Session)
<commit_msg>Move Session to Sport as an inline.<commit_after>
|
from django.contrib import admin
from .models import (Sport, Match, Session, CancelledSession)
class SessionInline(admin.StackedInline):
model = Session
extra = 0
@admin.register(Sport)
class SportAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
inlines = [SessionInline,]
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(Match)
class MatchAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(CancelledSession)
class CancelledSessionAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
|
from django.contrib import admin
from .models import (Sport, Match, Session, CancelledSession)
@admin.register(Sport)
class SportAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(Match)
class MatchAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(CancelledSession)
class CancelledSessionAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
admin.site.register(Session)
Move Session to Sport as an inline.from django.contrib import admin
from .models import (Sport, Match, Session, CancelledSession)
class SessionInline(admin.StackedInline):
model = Session
extra = 0
@admin.register(Sport)
class SportAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
inlines = [SessionInline,]
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(Match)
class MatchAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(CancelledSession)
class CancelledSessionAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
|
<commit_before>from django.contrib import admin
from .models import (Sport, Match, Session, CancelledSession)
@admin.register(Sport)
class SportAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(Match)
class MatchAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(CancelledSession)
class CancelledSessionAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
admin.site.register(Session)
<commit_msg>Move Session to Sport as an inline.<commit_after>from django.contrib import admin
from .models import (Sport, Match, Session, CancelledSession)
class SessionInline(admin.StackedInline):
model = Session
extra = 0
@admin.register(Sport)
class SportAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
inlines = [SessionInline,]
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(Match)
class MatchAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
@admin.register(CancelledSession)
class CancelledSessionAdmin(admin.ModelAdmin):
class Media:
js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js')
|
b739da9bcbc7c1f1fc95a04e1e12a44f23d0a1de
|
tests/test_extension.py
|
tests/test_extension.py
|
import unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_get_backend_classes(self):
ext = Extension()
backends = ext.get_backend_classes()
self.assertIn(backend_lib.SpotifyBackend, backends)
|
import mock, unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_setup(self):
registry = mock.Mock()
ext = Extension()
ext.setup(registry)
registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
|
Test extension with mock registry
|
Test extension with mock registry
|
Python
|
apache-2.0
|
kingosticks/mopidy-spotify,mopidy/mopidy-spotify,jodal/mopidy-spotify
|
import unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_get_backend_classes(self):
ext = Extension()
backends = ext.get_backend_classes()
self.assertIn(backend_lib.SpotifyBackend, backends)
Test extension with mock registry
|
import mock, unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_setup(self):
registry = mock.Mock()
ext = Extension()
ext.setup(registry)
registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
|
<commit_before>import unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_get_backend_classes(self):
ext = Extension()
backends = ext.get_backend_classes()
self.assertIn(backend_lib.SpotifyBackend, backends)
<commit_msg>Test extension with mock registry<commit_after>
|
import mock, unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_setup(self):
registry = mock.Mock()
ext = Extension()
ext.setup(registry)
registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
|
import unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_get_backend_classes(self):
ext = Extension()
backends = ext.get_backend_classes()
self.assertIn(backend_lib.SpotifyBackend, backends)
Test extension with mock registryimport mock, unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_setup(self):
registry = mock.Mock()
ext = Extension()
ext.setup(registry)
registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
|
<commit_before>import unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_get_backend_classes(self):
ext = Extension()
backends = ext.get_backend_classes()
self.assertIn(backend_lib.SpotifyBackend, backends)
<commit_msg>Test extension with mock registry<commit_after>import mock, unittest
from mopidy_spotify import Extension, backend as backend_lib
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
self.assertIn('[spotify]', config)
self.assertIn('enabled = true', config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn('username', schema)
self.assertIn('password', schema)
self.assertIn('bitrate', schema)
self.assertIn('timeout', schema)
self.assertIn('cache_dir', schema)
def test_setup(self):
registry = mock.Mock()
ext = Extension()
ext.setup(registry)
registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
|
b6389de5f531fa49e911b344cbaea29599260c82
|
src/tests/test_cleanup_marathon_orphaned_containers.py
|
src/tests/test_cleanup_marathon_orphaned_containers.py
|
#!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
'Names': ['/mesos-undeployed-old', ],
}
running_images = [
mesos_deployed_old,
nonmesos_undeployed_old,
mesos_undeployed_young,
mesos_undeployed_old,
]
def test_get_mesos_images():
actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
assert nonmesos_undeployed_old not in actual
def test_get_old_images():
pass
|
#!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
'Names': ['/mesos-undeployed-old', ],
}
running_images = [
mesos_deployed_old,
nonmesos_undeployed_old,
mesos_undeployed_young,
mesos_undeployed_old,
]
def test_get_mesos_images():
assert nonmesos_undeployed_old in running_images
actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
assert nonmesos_undeployed_old not in actual
def test_get_old_images():
pass
|
Clarify intent and fail fast
|
Clarify intent and fail fast
|
Python
|
apache-2.0
|
Yelp/paasta,somic/paasta,gstarnberger/paasta,somic/paasta,gstarnberger/paasta,Yelp/paasta
|
#!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
'Names': ['/mesos-undeployed-old', ],
}
running_images = [
mesos_deployed_old,
nonmesos_undeployed_old,
mesos_undeployed_young,
mesos_undeployed_old,
]
def test_get_mesos_images():
actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
assert nonmesos_undeployed_old not in actual
def test_get_old_images():
pass
Clarify intent and fail fast
|
#!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
'Names': ['/mesos-undeployed-old', ],
}
running_images = [
mesos_deployed_old,
nonmesos_undeployed_old,
mesos_undeployed_young,
mesos_undeployed_old,
]
def test_get_mesos_images():
assert nonmesos_undeployed_old in running_images
actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
assert nonmesos_undeployed_old not in actual
def test_get_old_images():
pass
|
<commit_before>#!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
'Names': ['/mesos-undeployed-old', ],
}
running_images = [
mesos_deployed_old,
nonmesos_undeployed_old,
mesos_undeployed_young,
mesos_undeployed_old,
]
def test_get_mesos_images():
actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
assert nonmesos_undeployed_old not in actual
def test_get_old_images():
pass
<commit_msg>Clarify intent and fail fast<commit_after>
|
#!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
'Names': ['/mesos-undeployed-old', ],
}
running_images = [
mesos_deployed_old,
nonmesos_undeployed_old,
mesos_undeployed_young,
mesos_undeployed_old,
]
def test_get_mesos_images():
assert nonmesos_undeployed_old in running_images
actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
assert nonmesos_undeployed_old not in actual
def test_get_old_images():
pass
|
#!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
'Names': ['/mesos-undeployed-old', ],
}
running_images = [
mesos_deployed_old,
nonmesos_undeployed_old,
mesos_undeployed_young,
mesos_undeployed_old,
]
def test_get_mesos_images():
actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
assert nonmesos_undeployed_old not in actual
def test_get_old_images():
pass
Clarify intent and fail fast#!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
'Names': ['/mesos-undeployed-old', ],
}
running_images = [
mesos_deployed_old,
nonmesos_undeployed_old,
mesos_undeployed_young,
mesos_undeployed_old,
]
def test_get_mesos_images():
assert nonmesos_undeployed_old in running_images
actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
assert nonmesos_undeployed_old not in actual
def test_get_old_images():
pass
|
<commit_before>#!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
'Names': ['/mesos-undeployed-old', ],
}
running_images = [
mesos_deployed_old,
nonmesos_undeployed_old,
mesos_undeployed_young,
mesos_undeployed_old,
]
def test_get_mesos_images():
actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
assert nonmesos_undeployed_old not in actual
def test_get_old_images():
pass
<commit_msg>Clarify intent and fail fast<commit_after>#!/usr/bin/env python
import cleanup_marathon_orphaned_images
# These should be left running
mesos_deployed_old = {
'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
'Names': ['/mesos-undeployed-old', ],
}
running_images = [
mesos_deployed_old,
nonmesos_undeployed_old,
mesos_undeployed_young,
mesos_undeployed_old,
]
def test_get_mesos_images():
assert nonmesos_undeployed_old in running_images
actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
assert nonmesos_undeployed_old not in actual
def test_get_old_images():
pass
|
72e857ddeca52caac621c33990b3dcf74f39d20a
|
external_tools/src/main/python/images/move_corrupt_images.py
|
external_tools/src/main/python/images/move_corrupt_images.py
|
"""
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname2 = fname.replace(split_string, replacement_string)
os.rename(fname, fname2)
|
"""
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname2 = fname.replace(split_string, replacement_string)
os.renames(fname, fname2)
|
Create intermidate dirs if they do not exist when moving files
|
Create intermidate dirs if they do not exist when moving files
|
Python
|
apache-2.0
|
mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData
|
"""
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname2 = fname.replace(split_string, replacement_string)
os.rename(fname, fname2)
Create intermidate dirs if they do not exist when moving files
|
"""
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname2 = fname.replace(split_string, replacement_string)
os.renames(fname, fname2)
|
<commit_before>"""
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname2 = fname.replace(split_string, replacement_string)
os.rename(fname, fname2)
<commit_msg>Create intermidate dirs if they do not exist when moving files<commit_after>
|
"""
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname2 = fname.replace(split_string, replacement_string)
os.renames(fname, fname2)
|
"""
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname2 = fname.replace(split_string, replacement_string)
os.rename(fname, fname2)
Create intermidate dirs if they do not exist when moving files"""
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname2 = fname.replace(split_string, replacement_string)
os.renames(fname, fname2)
|
<commit_before>"""
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname2 = fname.replace(split_string, replacement_string)
os.rename(fname, fname2)
<commit_msg>Create intermidate dirs if they do not exist when moving files<commit_after>"""
Script to move corrupt images to 'dirty' directory
Reads list of images to move. Does not verify that images are corrupt -
Simply moves to 'dirty' directory of appropriate data-release creating
the required directory structure
"""
import os
import argparse
parser = argparse.ArgumentParser(
description="Move corrupt images to 'dirty' dir")
parser.add_argument('-i', dest='inputFiles', required=True,
help='File containing list of images to move'
)
parser.add_argument('-s', dest='splitString',
help='token to separate the basedir from input files'
)
parser.add_argument('-r', dest='replacementString',
help='String to replace the split string with'
)
parser.add_argument('-d', dest='destDirBase', required=True,
help='Path to the base of the destination dir'
)
args = parser.parse_args()
input_files = args.inputFiles
split_string = "" if args.splitString is None else args.splitString
replacement_string = "" if args.replacementString is None else args.replacementString
with open(input_files,'rt') as f:
fnames = [fname.strip('\n') for fname in f.readlines()]
for fname in fnames:
fname2 = fname.replace(split_string, replacement_string)
os.renames(fname, fname2)
|
04e253ef897197bd9550d00870583c67db7f1d0a
|
tests/test_bmipytest.py
|
tests/test_bmipytest.py
|
from bmi_tester.bmipytest import load_component
entry_point = 'pymt_hydrotrend.bmi:Hydrotrend'
module_name, cls_name = entry_point.split(":")
def test_component_is_string():
component = load_component(entry_point)
assert isinstance(component, str)
def test_component_is_classname():
component = load_component(entry_point)
assert component == cls_name
|
from bmi_tester.bmipytest import load_component
entry_point = 'os:getcwd'
module_name, cls_name = entry_point.split(":")
def test_component_is_string():
component = load_component(entry_point)
assert isinstance(component, str)
def test_component_is_classname():
component = load_component(entry_point)
assert component == cls_name
|
Use a package in base Python distro for test
|
Use a package in base Python distro for test
I was too ambitious -- pymt_hydrotrend isn't a default on Windows.
Using os.getcwd() should be less fragile.
|
Python
|
mit
|
csdms/bmi-tester
|
from bmi_tester.bmipytest import load_component
entry_point = 'pymt_hydrotrend.bmi:Hydrotrend'
module_name, cls_name = entry_point.split(":")
def test_component_is_string():
component = load_component(entry_point)
assert isinstance(component, str)
def test_component_is_classname():
component = load_component(entry_point)
assert component == cls_name
Use a package in base Python distro for test
I was too ambitious -- pymt_hydrotrend isn't a default on Windows.
Using os.getcwd() should be less fragile.
|
from bmi_tester.bmipytest import load_component
entry_point = 'os:getcwd'
module_name, cls_name = entry_point.split(":")
def test_component_is_string():
component = load_component(entry_point)
assert isinstance(component, str)
def test_component_is_classname():
component = load_component(entry_point)
assert component == cls_name
|
<commit_before>from bmi_tester.bmipytest import load_component
entry_point = 'pymt_hydrotrend.bmi:Hydrotrend'
module_name, cls_name = entry_point.split(":")
def test_component_is_string():
component = load_component(entry_point)
assert isinstance(component, str)
def test_component_is_classname():
component = load_component(entry_point)
assert component == cls_name
<commit_msg>Use a package in base Python distro for test
I was too ambitious -- pymt_hydrotrend isn't a default on Windows.
Using os.getcwd() should be less fragile.<commit_after>
|
from bmi_tester.bmipytest import load_component
entry_point = 'os:getcwd'
module_name, cls_name = entry_point.split(":")
def test_component_is_string():
component = load_component(entry_point)
assert isinstance(component, str)
def test_component_is_classname():
component = load_component(entry_point)
assert component == cls_name
|
from bmi_tester.bmipytest import load_component
entry_point = 'pymt_hydrotrend.bmi:Hydrotrend'
module_name, cls_name = entry_point.split(":")
def test_component_is_string():
component = load_component(entry_point)
assert isinstance(component, str)
def test_component_is_classname():
component = load_component(entry_point)
assert component == cls_name
Use a package in base Python distro for test
I was too ambitious -- pymt_hydrotrend isn't a default on Windows.
Using os.getcwd() should be less fragile.from bmi_tester.bmipytest import load_component
entry_point = 'os:getcwd'
module_name, cls_name = entry_point.split(":")
def test_component_is_string():
component = load_component(entry_point)
assert isinstance(component, str)
def test_component_is_classname():
component = load_component(entry_point)
assert component == cls_name
|
<commit_before>from bmi_tester.bmipytest import load_component
entry_point = 'pymt_hydrotrend.bmi:Hydrotrend'
module_name, cls_name = entry_point.split(":")
def test_component_is_string():
component = load_component(entry_point)
assert isinstance(component, str)
def test_component_is_classname():
component = load_component(entry_point)
assert component == cls_name
<commit_msg>Use a package in base Python distro for test
I was too ambitious -- pymt_hydrotrend isn't a default on Windows.
Using os.getcwd() should be less fragile.<commit_after>from bmi_tester.bmipytest import load_component
entry_point = 'os:getcwd'
module_name, cls_name = entry_point.split(":")
def test_component_is_string():
component = load_component(entry_point)
assert isinstance(component, str)
def test_component_is_classname():
component = load_component(entry_point)
assert component == cls_name
|
052905dbff6f91740c8f8b9cb5e06aa07b06a186
|
tests/test_spicedham.py
|
tests/test_spicedham.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_spicedham
----------------------------------
Tests for `spicedham` module.
"""
import unittest
from spicedham import spicedham
class TestSpicedham(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_spicedham
----------------------------------
Tests for `spicedham` module.
"""
import os
import json
import tarfile
import unittest
from spicedham import SpicedHam
class TestSpicedham(unittest.TestCase):
def setUp(self, tarball='corpus.tar.gz', test_data_dir='corpus'):
if os.path.exists(test_data_dir):
pass
elif os.path.exists(tarball) :
tarfile.open(tarball)
tarfile.extractall()
tarfile.close()
else:
raise 'No test data found'
self.sh = SpicedHam()
dir_name = os.path.join(test_data_dir, 'train', 'ham')
for file_name in os.listdir(dir_name):
data = json.load(open(os.path.join(dir_name, file_name)))
self.sh.train(data, False)
def test_on_training_data(self, test_data_dir='corpus'):
self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'spam'), True)
self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'ham'), False)
def test_on_control_data(self, test_data_dir='corpus'):
self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'spam'), True)
self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'ham'), False)
def _test_all_files_in_dir(self, data_dir, should_be_spam):
tuning_factor = 0.5
for filename in os.listdir(data_dir):
f = open(os.path.join(data_dir, filename), 'r')
probability = self.sh.is_spam(json.load(f))
self.assertGreaterEqual(probability, 0.0)
self.assertLessEqual(probability, 1.0)
if should_be_spam:
self.assertGreaterEqual(tuning_factor, 0.5)
else:
self.assertLessEqual(tuning_factor, 0.5)
if __name__ == '__main__':
unittest.main()
|
Add tests based off of the corpus.
|
Add tests based off of the corpus.
|
Python
|
mpl-2.0
|
mozilla/spicedham,mozilla/spicedham
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_spicedham
----------------------------------
Tests for `spicedham` module.
"""
import unittest
from spicedham import spicedham
class TestSpicedham(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()Add tests based off of the corpus.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_spicedham
----------------------------------
Tests for `spicedham` module.
"""
import os
import json
import tarfile
import unittest
from spicedham import SpicedHam
class TestSpicedham(unittest.TestCase):
def setUp(self, tarball='corpus.tar.gz', test_data_dir='corpus'):
if os.path.exists(test_data_dir):
pass
elif os.path.exists(tarball) :
tarfile.open(tarball)
tarfile.extractall()
tarfile.close()
else:
raise 'No test data found'
self.sh = SpicedHam()
dir_name = os.path.join(test_data_dir, 'train', 'ham')
for file_name in os.listdir(dir_name):
data = json.load(open(os.path.join(dir_name, file_name)))
self.sh.train(data, False)
def test_on_training_data(self, test_data_dir='corpus'):
self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'spam'), True)
self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'ham'), False)
def test_on_control_data(self, test_data_dir='corpus'):
self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'spam'), True)
self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'ham'), False)
def _test_all_files_in_dir(self, data_dir, should_be_spam):
tuning_factor = 0.5
for filename in os.listdir(data_dir):
f = open(os.path.join(data_dir, filename), 'r')
probability = self.sh.is_spam(json.load(f))
self.assertGreaterEqual(probability, 0.0)
self.assertLessEqual(probability, 1.0)
if should_be_spam:
self.assertGreaterEqual(tuning_factor, 0.5)
else:
self.assertLessEqual(tuning_factor, 0.5)
if __name__ == '__main__':
unittest.main()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_spicedham
----------------------------------
Tests for `spicedham` module.
"""
import unittest
from spicedham import spicedham
class TestSpicedham(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()<commit_msg>Add tests based off of the corpus.<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_spicedham
----------------------------------
Tests for `spicedham` module.
"""
import os
import json
import tarfile
import unittest
from spicedham import SpicedHam
class TestSpicedham(unittest.TestCase):
def setUp(self, tarball='corpus.tar.gz', test_data_dir='corpus'):
if os.path.exists(test_data_dir):
pass
elif os.path.exists(tarball) :
tarfile.open(tarball)
tarfile.extractall()
tarfile.close()
else:
raise 'No test data found'
self.sh = SpicedHam()
dir_name = os.path.join(test_data_dir, 'train', 'ham')
for file_name in os.listdir(dir_name):
data = json.load(open(os.path.join(dir_name, file_name)))
self.sh.train(data, False)
def test_on_training_data(self, test_data_dir='corpus'):
self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'spam'), True)
self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'ham'), False)
def test_on_control_data(self, test_data_dir='corpus'):
self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'spam'), True)
self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'ham'), False)
def _test_all_files_in_dir(self, data_dir, should_be_spam):
tuning_factor = 0.5
for filename in os.listdir(data_dir):
f = open(os.path.join(data_dir, filename), 'r')
probability = self.sh.is_spam(json.load(f))
self.assertGreaterEqual(probability, 0.0)
self.assertLessEqual(probability, 1.0)
if should_be_spam:
self.assertGreaterEqual(tuning_factor, 0.5)
else:
self.assertLessEqual(tuning_factor, 0.5)
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_spicedham
----------------------------------
Tests for `spicedham` module.
"""
import unittest
from spicedham import spicedham
class TestSpicedham(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()Add tests based off of the corpus.#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_spicedham
----------------------------------
Tests for `spicedham` module.
"""
import os
import json
import tarfile
import unittest
from spicedham import SpicedHam
class TestSpicedham(unittest.TestCase):
def setUp(self, tarball='corpus.tar.gz', test_data_dir='corpus'):
if os.path.exists(test_data_dir):
pass
elif os.path.exists(tarball) :
tarfile.open(tarball)
tarfile.extractall()
tarfile.close()
else:
raise 'No test data found'
self.sh = SpicedHam()
dir_name = os.path.join(test_data_dir, 'train', 'ham')
for file_name in os.listdir(dir_name):
data = json.load(open(os.path.join(dir_name, file_name)))
self.sh.train(data, False)
def test_on_training_data(self, test_data_dir='corpus'):
self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'spam'), True)
self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'ham'), False)
def test_on_control_data(self, test_data_dir='corpus'):
self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'spam'), True)
self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'ham'), False)
def _test_all_files_in_dir(self, data_dir, should_be_spam):
tuning_factor = 0.5
for filename in os.listdir(data_dir):
f = open(os.path.join(data_dir, filename), 'r')
probability = self.sh.is_spam(json.load(f))
self.assertGreaterEqual(probability, 0.0)
self.assertLessEqual(probability, 1.0)
if should_be_spam:
self.assertGreaterEqual(tuning_factor, 0.5)
else:
self.assertLessEqual(tuning_factor, 0.5)
if __name__ == '__main__':
unittest.main()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_spicedham
----------------------------------
Tests for `spicedham` module.
"""
import unittest
from spicedham import spicedham
class TestSpicedham(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()<commit_msg>Add tests based off of the corpus.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_spicedham
----------------------------------
Tests for `spicedham` module.
"""
import os
import json
import tarfile
import unittest
from spicedham import SpicedHam
class TestSpicedham(unittest.TestCase):
def setUp(self, tarball='corpus.tar.gz', test_data_dir='corpus'):
if os.path.exists(test_data_dir):
pass
elif os.path.exists(tarball) :
tarfile.open(tarball)
tarfile.extractall()
tarfile.close()
else:
raise 'No test data found'
self.sh = SpicedHam()
dir_name = os.path.join(test_data_dir, 'train', 'ham')
for file_name in os.listdir(dir_name):
data = json.load(open(os.path.join(dir_name, file_name)))
self.sh.train(data, False)
def test_on_training_data(self, test_data_dir='corpus'):
self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'spam'), True)
self._test_all_files_in_dir(os.path.join(test_data_dir, 'train', 'ham'), False)
def test_on_control_data(self, test_data_dir='corpus'):
self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'spam'), True)
self._test_all_files_in_dir(os.path.join(test_data_dir, 'control', 'ham'), False)
def _test_all_files_in_dir(self, data_dir, should_be_spam):
tuning_factor = 0.5
for filename in os.listdir(data_dir):
f = open(os.path.join(data_dir, filename), 'r')
probability = self.sh.is_spam(json.load(f))
self.assertGreaterEqual(probability, 0.0)
self.assertLessEqual(probability, 1.0)
if should_be_spam:
self.assertGreaterEqual(tuning_factor, 0.5)
else:
self.assertLessEqual(tuning_factor, 0.5)
if __name__ == '__main__':
unittest.main()
|
fc637c488f095d8be7c7d974fc95f0b4edf611e2
|
springfield_mongo/utils.py
|
springfield_mongo/utils.py
|
from springfield import Entity
def entity_from_mongo(kls, values):
"""
Construct an Entity of type `kls` from a Mongo document.
"""
entity = kls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
|
from springfield import Entity
def entity_from_mongo(cls, values):
"""
Construct an Entity of type `cls` from a Mongo document.
"""
entity = cls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
|
Use a more standard variable name for the class argument.
|
Use a more standard variable name for the class argument.
|
Python
|
mit
|
six8/springfield-mongo
|
from springfield import Entity
def entity_from_mongo(kls, values):
"""
Construct an Entity of type `kls` from a Mongo document.
"""
entity = kls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
Use a more standard variable name for the class argument.
|
from springfield import Entity
def entity_from_mongo(cls, values):
"""
Construct an Entity of type `cls` from a Mongo document.
"""
entity = cls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
|
<commit_before>from springfield import Entity
def entity_from_mongo(kls, values):
"""
Construct an Entity of type `kls` from a Mongo document.
"""
entity = kls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
<commit_msg>Use a more standard variable name for the class argument.<commit_after>
|
from springfield import Entity
def entity_from_mongo(cls, values):
"""
Construct an Entity of type `cls` from a Mongo document.
"""
entity = cls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
|
from springfield import Entity
def entity_from_mongo(kls, values):
"""
Construct an Entity of type `kls` from a Mongo document.
"""
entity = kls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
Use a more standard variable name for the class argument.from springfield import Entity
def entity_from_mongo(cls, values):
"""
Construct an Entity of type `cls` from a Mongo document.
"""
entity = cls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
|
<commit_before>from springfield import Entity
def entity_from_mongo(kls, values):
"""
Construct an Entity of type `kls` from a Mongo document.
"""
entity = kls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
<commit_msg>Use a more standard variable name for the class argument.<commit_after>from springfield import Entity
def entity_from_mongo(cls, values):
"""
Construct an Entity of type `cls` from a Mongo document.
"""
entity = cls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
|
09268200fcc1ae21206659ae261c488eb1567071
|
app/__init__.py
|
app/__init__.py
|
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
application.register_blueprint(main_blueprint)
main_blueprint.config = application.config.copy()
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
application.before_request(requires_auth)
return application
|
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
main_blueprint.before_request(requires_auth)
application.register_blueprint(main_blueprint, url_prefix='/admin')
main_blueprint.config = application.config.copy()
return application
|
Add '/admin' url_prefix to main blueprint
|
Add '/admin' url_prefix to main blueprint
Also attaches the authentication check to main blueprint instead of
the app itself. This means we can use other blueprints for status
and internal use that don't require authentication.
One important note: before_request must be added before registering
the blueprint, otherwise it won't be activated.
|
Python
|
mit
|
alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend
|
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
application.register_blueprint(main_blueprint)
main_blueprint.config = application.config.copy()
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
application.before_request(requires_auth)
return application
Add '/admin' url_prefix to main blueprint
Also attaches the authentication check to main blueprint instead of
the app itself. This means we can use other blueprints for status
and internal use that don't require authentication.
One important note: before_request must be added before registering
the blueprint, otherwise it won't be activated.
|
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
main_blueprint.before_request(requires_auth)
application.register_blueprint(main_blueprint, url_prefix='/admin')
main_blueprint.config = application.config.copy()
return application
|
<commit_before>from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
application.register_blueprint(main_blueprint)
main_blueprint.config = application.config.copy()
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
application.before_request(requires_auth)
return application
<commit_msg>Add '/admin' url_prefix to main blueprint
Also attaches the authentication check to main blueprint instead of
the app itself. This means we can use other blueprints for status
and internal use that don't require authentication.
One important note: before_request must be added before registering
the blueprint, otherwise it won't be activated.<commit_after>
|
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
main_blueprint.before_request(requires_auth)
application.register_blueprint(main_blueprint, url_prefix='/admin')
main_blueprint.config = application.config.copy()
return application
|
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
application.register_blueprint(main_blueprint)
main_blueprint.config = application.config.copy()
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
application.before_request(requires_auth)
return application
Add '/admin' url_prefix to main blueprint
Also attaches the authentication check to main blueprint instead of
the app itself. This means we can use other blueprints for status
and internal use that don't require authentication.
One important note: before_request must be added before registering
the blueprint, otherwise it won't be activated.from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
main_blueprint.before_request(requires_auth)
application.register_blueprint(main_blueprint, url_prefix='/admin')
main_blueprint.config = application.config.copy()
return application
|
<commit_before>from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
application.register_blueprint(main_blueprint)
main_blueprint.config = application.config.copy()
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
application.before_request(requires_auth)
return application
<commit_msg>Add '/admin' url_prefix to main blueprint
Also attaches the authentication check to main blueprint instead of
the app itself. This means we can use other blueprints for status
and internal use that don't require authentication.
One important note: before_request must be added before registering
the blueprint, otherwise it won't be activated.<commit_after>from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from datetime import timedelta
from .main import main as main_blueprint
from .main.helpers.auth import requires_auth
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
if application.config['AUTHENTICATION']:
application.permanent_session_lifetime = timedelta(minutes=60)
main_blueprint.before_request(requires_auth)
application.register_blueprint(main_blueprint, url_prefix='/admin')
main_blueprint.config = application.config.copy()
return application
|
39fbce2a0e225591423f9b2d1edd111822063466
|
app/core/api.py
|
app/core/api.py
|
from flask import jsonify, request
from ..main import app
@app.route('/api/ip')
def api_ip():
return jsonify({'Success': True, 'ipAddress': get_client_ip()})
def get_client_ip():
return request.headers.get('X-Forwarded-For') or request.remote_addr
|
from flask import jsonify, request
from ..main import app
@app.route('/api/ip')
def api_ip():
"""Return client IP"""
return api_reply({'ipAddress': get_client_ip()})
def get_client_ip():
"""Return the client x-forwarded-for header or IP address"""
return request.headers.get('X-Forwarded-For') or request.remote_addr
def api_reply(body={}, success=True):
"""Create a standard API reply interface"""
return jsonify({**body, 'success': success})
|
Add a standard API reply interface
|
Add a standard API reply interface
|
Python
|
mit
|
jniedrauer/jniedrauer.com,jniedrauer/jniedrauer.com,jniedrauer/jniedrauer.com
|
from flask import jsonify, request
from ..main import app
@app.route('/api/ip')
def api_ip():
return jsonify({'Success': True, 'ipAddress': get_client_ip()})
def get_client_ip():
return request.headers.get('X-Forwarded-For') or request.remote_addr
Add a standard API reply interface
|
from flask import jsonify, request
from ..main import app
@app.route('/api/ip')
def api_ip():
"""Return client IP"""
return api_reply({'ipAddress': get_client_ip()})
def get_client_ip():
"""Return the client x-forwarded-for header or IP address"""
return request.headers.get('X-Forwarded-For') or request.remote_addr
def api_reply(body={}, success=True):
"""Create a standard API reply interface"""
return jsonify({**body, 'success': success})
|
<commit_before>from flask import jsonify, request
from ..main import app
@app.route('/api/ip')
def api_ip():
return jsonify({'Success': True, 'ipAddress': get_client_ip()})
def get_client_ip():
return request.headers.get('X-Forwarded-For') or request.remote_addr
<commit_msg>Add a standard API reply interface<commit_after>
|
from flask import jsonify, request
from ..main import app
@app.route('/api/ip')
def api_ip():
"""Return client IP"""
return api_reply({'ipAddress': get_client_ip()})
def get_client_ip():
"""Return the client x-forwarded-for header or IP address"""
return request.headers.get('X-Forwarded-For') or request.remote_addr
def api_reply(body={}, success=True):
"""Create a standard API reply interface"""
return jsonify({**body, 'success': success})
|
from flask import jsonify, request
from ..main import app
@app.route('/api/ip')
def api_ip():
return jsonify({'Success': True, 'ipAddress': get_client_ip()})
def get_client_ip():
return request.headers.get('X-Forwarded-For') or request.remote_addr
Add a standard API reply interfacefrom flask import jsonify, request
from ..main import app
@app.route('/api/ip')
def api_ip():
"""Return client IP"""
return api_reply({'ipAddress': get_client_ip()})
def get_client_ip():
"""Return the client x-forwarded-for header or IP address"""
return request.headers.get('X-Forwarded-For') or request.remote_addr
def api_reply(body={}, success=True):
"""Create a standard API reply interface"""
return jsonify({**body, 'success': success})
|
<commit_before>from flask import jsonify, request
from ..main import app
@app.route('/api/ip')
def api_ip():
return jsonify({'Success': True, 'ipAddress': get_client_ip()})
def get_client_ip():
return request.headers.get('X-Forwarded-For') or request.remote_addr
<commit_msg>Add a standard API reply interface<commit_after>from flask import jsonify, request
from ..main import app
@app.route('/api/ip')
def api_ip():
"""Return client IP"""
return api_reply({'ipAddress': get_client_ip()})
def get_client_ip():
"""Return the client x-forwarded-for header or IP address"""
return request.headers.get('X-Forwarded-For') or request.remote_addr
def api_reply(body={}, success=True):
"""Create a standard API reply interface"""
return jsonify({**body, 'success': success})
|
d244e80e3fa6672e94e39a60cd3b249d279b75ec
|
bqueryd/node.py
|
bqueryd/node.py
|
#!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')])
redis_url=config.get('Main', 'redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'downloader' in sys.argv:
bqueryd.DownloaderNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
|
#!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import configobj
config = configobj.ConfigObj('/etc/bqueryd.cfg')
redis_url = config.get('redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'downloader' in sys.argv:
bqueryd.DownloaderNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
|
Use configobj for config handling
|
Use configobj for config handling
|
Python
|
bsd-3-clause
|
visualfabriq/bqueryd
|
#!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')])
redis_url=config.get('Main', 'redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'downloader' in sys.argv:
bqueryd.DownloaderNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
Use configobj for config handling
|
#!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import configobj
config = configobj.ConfigObj('/etc/bqueryd.cfg')
redis_url = config.get('redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'downloader' in sys.argv:
bqueryd.DownloaderNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
|
<commit_before>#!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')])
redis_url=config.get('Main', 'redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'downloader' in sys.argv:
bqueryd.DownloaderNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
<commit_msg>Use configobj for config handling<commit_after>
|
#!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import configobj
config = configobj.ConfigObj('/etc/bqueryd.cfg')
redis_url = config.get('redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'downloader' in sys.argv:
bqueryd.DownloaderNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
|
#!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')])
redis_url=config.get('Main', 'redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'downloader' in sys.argv:
bqueryd.DownloaderNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
Use configobj for config handling#!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import configobj
config = configobj.ConfigObj('/etc/bqueryd.cfg')
redis_url = config.get('redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'downloader' in sys.argv:
bqueryd.DownloaderNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
|
<commit_before>#!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')])
redis_url=config.get('Main', 'redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'downloader' in sys.argv:
bqueryd.DownloaderNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
<commit_msg>Use configobj for config handling<commit_after>#!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import configobj
config = configobj.ConfigObj('/etc/bqueryd.cfg')
redis_url = config.get('redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
if 'controller' in sys.argv:
bqueryd.ControllerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'worker' in sys.argv:
bqueryd.WorkerNode(redis_url=redis_url, loglevel=loglevel).go()
elif 'downloader' in sys.argv:
bqueryd.DownloaderNode(redis_url=redis_url, loglevel=loglevel).go()
else:
if len(sys.argv) > 1 and sys.argv[1].startswith('tcp:'):
rpc = bqueryd.RPC(address=sys.argv[1], redis_url=redis_url, loglevel=loglevel)
else:
rpc = bqueryd.RPC(redis_url=redis_url, loglevel=loglevel)
sys.stderr.write('Run this script with python -i , and then you will have a variable named "rpc" as a connection.\n')
|
b56eccf32fc7fe80405350fd122d3d257aa55788
|
runtests.py
|
runtests.py
|
"""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 0
q = 0
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
q += 1
if q:
v = 0
else:
v = max(v, 1)
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
|
"""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 1
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
v = 0
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
|
Simplify and improve -v/-q handling.
|
Simplify and improve -v/-q handling.
|
Python
|
apache-2.0
|
GoogleCloudPlatform/datastore-ndb-python,GoogleCloudPlatform/datastore-ndb-python
|
"""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 0
q = 0
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
q += 1
if q:
v = 0
else:
v = max(v, 1)
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
Simplify and improve -v/-q handling.
|
"""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 1
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
v = 0
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
|
<commit_before>"""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 0
q = 0
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
q += 1
if q:
v = 0
else:
v = max(v, 1)
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
<commit_msg>Simplify and improve -v/-q handling.<commit_after>
|
"""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 1
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
v = 0
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
|
"""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 0
q = 0
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
q += 1
if q:
v = 0
else:
v = max(v, 1)
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
Simplify and improve -v/-q handling."""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 1
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
v = 0
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
|
<commit_before>"""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 0
q = 0
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
q += 1
if q:
v = 0
else:
v = max(v, 1)
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
<commit_msg>Simplify and improve -v/-q handling.<commit_after>"""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 1
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
v = 0
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
|
a485c2b107987cfab334137cfa4031c366617ccd
|
runtests.py
|
runtests.py
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
'django.contrib.sessions', # for USE_SESSION
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
'django.contrib.sessions', # for USE_SESSION
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if django.VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
Support Django 1.7 in test runner.
|
Support Django 1.7 in test runner.
|
Python
|
mit
|
extertioner/django-localeurl,carljm/django-localeurl
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
'django.contrib.sessions', # for USE_SESSION
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
Support Django 1.7 in test runner.
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
'django.contrib.sessions', # for USE_SESSION
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if django.VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
<commit_before>#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
'django.contrib.sessions', # for USE_SESSION
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
<commit_msg>Support Django 1.7 in test runner.<commit_after>
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
'django.contrib.sessions', # for USE_SESSION
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if django.VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
'django.contrib.sessions', # for USE_SESSION
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
Support Django 1.7 in test runner.#!/usr/bin/env python
from os.path import dirname, abspath
import sys
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
'django.contrib.sessions', # for USE_SESSION
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if django.VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
<commit_before>#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
'django.contrib.sessions', # for USE_SESSION
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
<commit_msg>Support Django 1.7 in test runner.<commit_after>#!/usr/bin/env python
from os.path import dirname, abspath
import sys
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
'django.contrib.sessions', # for USE_SESSION
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if django.VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
e44b240a4de44e9b6eb2863ce60b50a28f947ac4
|
tests/stonemason/service/tileserver/test_tileserver.py
|
tests/stonemason/service/tileserver/test_tileserver.py
|
# -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import json
import unittest
from stonemason.service.tileserver import StoneMasonApp
class TestStoneMasonApp(unittest.TestCase):
def setUp(self):
app = StoneMasonApp()
app.config['DEBUG'] = True
app.config['TESTING'] = True
self.client = app.test_client()
def test_get_theme(self):
resp = self.client.get('/themes/brick')
self.assertDictEqual(
{"result": {"name": "brick"}}, json.loads(resp.data))
def test_list_themes(self):
resp = self.client.get('/themes')
self.assertDictEqual({"result": []}, json.loads(resp.data))
def test_get_tile(self):
resp = self.client.get('/tile/brick/0/0/0.png')
self.assertEqual("Tile(brick, 0, 0, 0, 1x, png)", resp.data)
resp = self.client.get('/tile/brick/0/0/0@2x.png')
self.assertEqual("Tile(brick, 0, 0, 0, 2x, png)", resp.data)
|
# -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import six
import json
import unittest
from stonemason.service.tileserver import StoneMasonApp
class TestStoneMasonApp(unittest.TestCase):
def setUp(self):
app = StoneMasonApp()
app.config['DEBUG'] = True
app.config['TESTING'] = True
self.client = app.test_client()
def test_get_theme(self):
resp = self.client.get('/themes/brick')
self.assertDictEqual(
{
six.u("result"): {
six.u("name"): six.u("brick")
}
},
json.loads(resp.data.decode('utf-8'))
)
def test_list_themes(self):
resp = self.client.get('/themes')
self.assertDictEqual(
{
six.u("result"): []
},
json.loads(resp.data.decode('utf-8'))
)
def test_get_tile(self):
resp = self.client.get('/tile/brick/0/0/0.png')
self.assertEqual(
six.b("Tile(brick, 0, 0, 0, 1x, png)"),
resp.data
)
resp = self.client.get('/tile/brick/0/0/0@2x.png')
self.assertEqual(
six.b("Tile(brick, 0, 0, 0, 2x, png)"),
resp.data
)
|
Fix broken python 3 compatibility caused by unicode and bytes.
|
FIX: Fix broken python 3 compatibility caused by unicode and bytes.
|
Python
|
mit
|
Kotaimen/stonemason,Kotaimen/stonemason
|
# -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import json
import unittest
from stonemason.service.tileserver import StoneMasonApp
class TestStoneMasonApp(unittest.TestCase):
def setUp(self):
app = StoneMasonApp()
app.config['DEBUG'] = True
app.config['TESTING'] = True
self.client = app.test_client()
def test_get_theme(self):
resp = self.client.get('/themes/brick')
self.assertDictEqual(
{"result": {"name": "brick"}}, json.loads(resp.data))
def test_list_themes(self):
resp = self.client.get('/themes')
self.assertDictEqual({"result": []}, json.loads(resp.data))
def test_get_tile(self):
resp = self.client.get('/tile/brick/0/0/0.png')
self.assertEqual("Tile(brick, 0, 0, 0, 1x, png)", resp.data)
resp = self.client.get('/tile/brick/0/0/0@2x.png')
self.assertEqual("Tile(brick, 0, 0, 0, 2x, png)", resp.data)
FIX: Fix broken python 3 compatibility caused by unicode and bytes.
|
# -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import six
import json
import unittest
from stonemason.service.tileserver import StoneMasonApp
class TestStoneMasonApp(unittest.TestCase):
def setUp(self):
app = StoneMasonApp()
app.config['DEBUG'] = True
app.config['TESTING'] = True
self.client = app.test_client()
def test_get_theme(self):
resp = self.client.get('/themes/brick')
self.assertDictEqual(
{
six.u("result"): {
six.u("name"): six.u("brick")
}
},
json.loads(resp.data.decode('utf-8'))
)
def test_list_themes(self):
resp = self.client.get('/themes')
self.assertDictEqual(
{
six.u("result"): []
},
json.loads(resp.data.decode('utf-8'))
)
def test_get_tile(self):
resp = self.client.get('/tile/brick/0/0/0.png')
self.assertEqual(
six.b("Tile(brick, 0, 0, 0, 1x, png)"),
resp.data
)
resp = self.client.get('/tile/brick/0/0/0@2x.png')
self.assertEqual(
six.b("Tile(brick, 0, 0, 0, 2x, png)"),
resp.data
)
|
<commit_before># -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import json
import unittest
from stonemason.service.tileserver import StoneMasonApp
class TestStoneMasonApp(unittest.TestCase):
def setUp(self):
app = StoneMasonApp()
app.config['DEBUG'] = True
app.config['TESTING'] = True
self.client = app.test_client()
def test_get_theme(self):
resp = self.client.get('/themes/brick')
self.assertDictEqual(
{"result": {"name": "brick"}}, json.loads(resp.data))
def test_list_themes(self):
resp = self.client.get('/themes')
self.assertDictEqual({"result": []}, json.loads(resp.data))
def test_get_tile(self):
resp = self.client.get('/tile/brick/0/0/0.png')
self.assertEqual("Tile(brick, 0, 0, 0, 1x, png)", resp.data)
resp = self.client.get('/tile/brick/0/0/0@2x.png')
self.assertEqual("Tile(brick, 0, 0, 0, 2x, png)", resp.data)
<commit_msg>FIX: Fix broken python 3 compatibility caused by unicode and bytes.<commit_after>
|
# -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import six
import json
import unittest
from stonemason.service.tileserver import StoneMasonApp
class TestStoneMasonApp(unittest.TestCase):
def setUp(self):
app = StoneMasonApp()
app.config['DEBUG'] = True
app.config['TESTING'] = True
self.client = app.test_client()
def test_get_theme(self):
resp = self.client.get('/themes/brick')
self.assertDictEqual(
{
six.u("result"): {
six.u("name"): six.u("brick")
}
},
json.loads(resp.data.decode('utf-8'))
)
def test_list_themes(self):
resp = self.client.get('/themes')
self.assertDictEqual(
{
six.u("result"): []
},
json.loads(resp.data.decode('utf-8'))
)
def test_get_tile(self):
resp = self.client.get('/tile/brick/0/0/0.png')
self.assertEqual(
six.b("Tile(brick, 0, 0, 0, 1x, png)"),
resp.data
)
resp = self.client.get('/tile/brick/0/0/0@2x.png')
self.assertEqual(
six.b("Tile(brick, 0, 0, 0, 2x, png)"),
resp.data
)
|
# -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import json
import unittest
from stonemason.service.tileserver import StoneMasonApp
class TestStoneMasonApp(unittest.TestCase):
def setUp(self):
app = StoneMasonApp()
app.config['DEBUG'] = True
app.config['TESTING'] = True
self.client = app.test_client()
def test_get_theme(self):
resp = self.client.get('/themes/brick')
self.assertDictEqual(
{"result": {"name": "brick"}}, json.loads(resp.data))
def test_list_themes(self):
resp = self.client.get('/themes')
self.assertDictEqual({"result": []}, json.loads(resp.data))
def test_get_tile(self):
resp = self.client.get('/tile/brick/0/0/0.png')
self.assertEqual("Tile(brick, 0, 0, 0, 1x, png)", resp.data)
resp = self.client.get('/tile/brick/0/0/0@2x.png')
self.assertEqual("Tile(brick, 0, 0, 0, 2x, png)", resp.data)
FIX: Fix broken python 3 compatibility caused by unicode and bytes.# -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import six
import json
import unittest
from stonemason.service.tileserver import StoneMasonApp
class TestStoneMasonApp(unittest.TestCase):
def setUp(self):
app = StoneMasonApp()
app.config['DEBUG'] = True
app.config['TESTING'] = True
self.client = app.test_client()
def test_get_theme(self):
resp = self.client.get('/themes/brick')
self.assertDictEqual(
{
six.u("result"): {
six.u("name"): six.u("brick")
}
},
json.loads(resp.data.decode('utf-8'))
)
def test_list_themes(self):
resp = self.client.get('/themes')
self.assertDictEqual(
{
six.u("result"): []
},
json.loads(resp.data.decode('utf-8'))
)
def test_get_tile(self):
resp = self.client.get('/tile/brick/0/0/0.png')
self.assertEqual(
six.b("Tile(brick, 0, 0, 0, 1x, png)"),
resp.data
)
resp = self.client.get('/tile/brick/0/0/0@2x.png')
self.assertEqual(
six.b("Tile(brick, 0, 0, 0, 2x, png)"),
resp.data
)
|
<commit_before># -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import json
import unittest
from stonemason.service.tileserver import StoneMasonApp
class TestStoneMasonApp(unittest.TestCase):
def setUp(self):
app = StoneMasonApp()
app.config['DEBUG'] = True
app.config['TESTING'] = True
self.client = app.test_client()
def test_get_theme(self):
resp = self.client.get('/themes/brick')
self.assertDictEqual(
{"result": {"name": "brick"}}, json.loads(resp.data))
def test_list_themes(self):
resp = self.client.get('/themes')
self.assertDictEqual({"result": []}, json.loads(resp.data))
def test_get_tile(self):
resp = self.client.get('/tile/brick/0/0/0.png')
self.assertEqual("Tile(brick, 0, 0, 0, 1x, png)", resp.data)
resp = self.client.get('/tile/brick/0/0/0@2x.png')
self.assertEqual("Tile(brick, 0, 0, 0, 2x, png)", resp.data)
<commit_msg>FIX: Fix broken python 3 compatibility caused by unicode and bytes.<commit_after># -*- encoding: utf-8 -*-
"""
tests.stonemason.service.tileserver.test_tileserver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test interfaces of the tile server application.
"""
import six
import json
import unittest
from stonemason.service.tileserver import StoneMasonApp
class TestStoneMasonApp(unittest.TestCase):
def setUp(self):
app = StoneMasonApp()
app.config['DEBUG'] = True
app.config['TESTING'] = True
self.client = app.test_client()
def test_get_theme(self):
resp = self.client.get('/themes/brick')
self.assertDictEqual(
{
six.u("result"): {
six.u("name"): six.u("brick")
}
},
json.loads(resp.data.decode('utf-8'))
)
def test_list_themes(self):
resp = self.client.get('/themes')
self.assertDictEqual(
{
six.u("result"): []
},
json.loads(resp.data.decode('utf-8'))
)
def test_get_tile(self):
resp = self.client.get('/tile/brick/0/0/0.png')
self.assertEqual(
six.b("Tile(brick, 0, 0, 0, 1x, png)"),
resp.data
)
resp = self.client.get('/tile/brick/0/0/0@2x.png')
self.assertEqual(
six.b("Tile(brick, 0, 0, 0, 2x, png)"),
resp.data
)
|
039768aeacbf2ad3ca3d498d035f2fcf1163ff8f
|
pi_gpio/meta.py
|
pi_gpio/meta.py
|
from flask.ext.restful import Resource, marshal
class BasicResource(Resource):
def __init__(self):
super(BasicResource, self).__init__()
def response(self, data, code):
return marshal(data, self.fields), code
|
from flask.ext.restful import Resource, marshal, reqparse
class BasicResource(Resource):
def __init__(self):
super(BasicResource, self).__init__()
self.parser = reqparse.RequestParser()
def response(self, data, code):
return marshal(data, self.fields), code
|
Add parser to basic resource
|
Add parser to basic resource
|
Python
|
mit
|
thijstriemstra/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server
|
from flask.ext.restful import Resource, marshal
class BasicResource(Resource):
def __init__(self):
super(BasicResource, self).__init__()
def response(self, data, code):
return marshal(data, self.fields), code
Add parser to basic resource
|
from flask.ext.restful import Resource, marshal, reqparse
class BasicResource(Resource):
def __init__(self):
super(BasicResource, self).__init__()
self.parser = reqparse.RequestParser()
def response(self, data, code):
return marshal(data, self.fields), code
|
<commit_before>from flask.ext.restful import Resource, marshal
class BasicResource(Resource):
def __init__(self):
super(BasicResource, self).__init__()
def response(self, data, code):
return marshal(data, self.fields), code
<commit_msg>Add parser to basic resource<commit_after>
|
from flask.ext.restful import Resource, marshal, reqparse
class BasicResource(Resource):
def __init__(self):
super(BasicResource, self).__init__()
self.parser = reqparse.RequestParser()
def response(self, data, code):
return marshal(data, self.fields), code
|
from flask.ext.restful import Resource, marshal
class BasicResource(Resource):
def __init__(self):
super(BasicResource, self).__init__()
def response(self, data, code):
return marshal(data, self.fields), code
Add parser to basic resourcefrom flask.ext.restful import Resource, marshal, reqparse
class BasicResource(Resource):
def __init__(self):
super(BasicResource, self).__init__()
self.parser = reqparse.RequestParser()
def response(self, data, code):
return marshal(data, self.fields), code
|
<commit_before>from flask.ext.restful import Resource, marshal
class BasicResource(Resource):
def __init__(self):
super(BasicResource, self).__init__()
def response(self, data, code):
return marshal(data, self.fields), code
<commit_msg>Add parser to basic resource<commit_after>from flask.ext.restful import Resource, marshal, reqparse
class BasicResource(Resource):
def __init__(self):
super(BasicResource, self).__init__()
self.parser = reqparse.RequestParser()
def response(self, data, code):
return marshal(data, self.fields), code
|
67a149f01854a855e3973e11a0926a8c2ec8da06
|
dsub/_dsub_version.py
|
dsub/_dsub_version.py
|
# Copyright 2017 Google Inc. 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
"""
DSUB_VERSION = '0.1.1'
|
# Copyright 2017 Google Inc. 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
"""
DSUB_VERSION = '0.1.2-dev'
|
Set dsub version to 0.1.2-dev.
|
Set dsub version to 0.1.2-dev.
PiperOrigin-RevId: 172923102
|
Python
|
apache-2.0
|
DataBiosphere/dsub,DataBiosphere/dsub
|
# Copyright 2017 Google Inc. 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
"""
DSUB_VERSION = '0.1.1'
Set dsub version to 0.1.2-dev.
PiperOrigin-RevId: 172923102
|
# Copyright 2017 Google Inc. 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
"""
DSUB_VERSION = '0.1.2-dev'
|
<commit_before># Copyright 2017 Google Inc. 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
"""
DSUB_VERSION = '0.1.1'
<commit_msg>Set dsub version to 0.1.2-dev.
PiperOrigin-RevId: 172923102<commit_after>
|
# Copyright 2017 Google Inc. 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
"""
DSUB_VERSION = '0.1.2-dev'
|
# Copyright 2017 Google Inc. 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
"""
DSUB_VERSION = '0.1.1'
Set dsub version to 0.1.2-dev.
PiperOrigin-RevId: 172923102# Copyright 2017 Google Inc. 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
"""
DSUB_VERSION = '0.1.2-dev'
|
<commit_before># Copyright 2017 Google Inc. 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
"""
DSUB_VERSION = '0.1.1'
<commit_msg>Set dsub version to 0.1.2-dev.
PiperOrigin-RevId: 172923102<commit_after># Copyright 2017 Google Inc. 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
"""
DSUB_VERSION = '0.1.2-dev'
|
991725f873909a268d12cade08de85026b34f5a3
|
csunplugged/tests/infrastructure/test_resource_generation.py
|
csunplugged/tests/infrastructure/test_resource_generation.py
|
"""Tests for resource generation."""
import os
import re
from django.core import management
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resources_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
modes = ["dev", "prod"]
for mode in modes:
generated_resource_names = set()
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(
'makeresources \"(?P<resource_name>[^\"]*)\"',
contents,
re.M
)
generated_resource_names.update(results)
self.assertEqual(
generated_resource_names,
set(Resource.objects.values_list("name", flat=True))
)
|
"""Tests for resource generation."""
import os
import re
import copy
from django.core import management
from config.settings.base import DEFAULT_LANGUAGES as LANGUAGES
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resource_pdfs_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
# Generate all resource combinations in dictionary
modes = ["dev", "prod"]
resource_slugs = set(Resource.objects.values_list("slug", flat=True))
languages = [lang[0] for lang in LANGUAGES]
required_resources = dict()
for mode in modes:
required_resources[mode] = dict()
for resource_slug in resource_slugs:
required_resources[mode][resource_slug] = languages[:]
# Check files for resource generations
regex = re.compile(r'makeresources \"([^\n\"]*)\"(?: \"([^\n\"]*)\")?')
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(regex, contents)
update_mode_list(mode, required_resources, results)
# Check if any languages are missed
error_text = ''
for mode in modes:
for (resource_slug, languages) in required_resources[mode].items():
if languages:
error_text += f"\n{resource_slug} does not generate PDFs for the {mode} website for the following languages: {languages}"
if error_text:
raise Exception(error_text)
def update_mode_list(mode, required_resources, results):
for (resource_slug, language) in results:
if not language:
del required_resources[mode][resource_slug]
if language:
required_resources[mode][resource_slug].remove(language)
|
Fix test for checking resource PDF generation
|
Fix test for checking resource PDF generation
|
Python
|
mit
|
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
|
"""Tests for resource generation."""
import os
import re
from django.core import management
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resources_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
modes = ["dev", "prod"]
for mode in modes:
generated_resource_names = set()
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(
'makeresources \"(?P<resource_name>[^\"]*)\"',
contents,
re.M
)
generated_resource_names.update(results)
self.assertEqual(
generated_resource_names,
set(Resource.objects.values_list("name", flat=True))
)
Fix test for checking resource PDF generation
|
"""Tests for resource generation."""
import os
import re
import copy
from django.core import management
from config.settings.base import DEFAULT_LANGUAGES as LANGUAGES
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resource_pdfs_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
# Generate all resource combinations in dictionary
modes = ["dev", "prod"]
resource_slugs = set(Resource.objects.values_list("slug", flat=True))
languages = [lang[0] for lang in LANGUAGES]
required_resources = dict()
for mode in modes:
required_resources[mode] = dict()
for resource_slug in resource_slugs:
required_resources[mode][resource_slug] = languages[:]
# Check files for resource generations
regex = re.compile(r'makeresources \"([^\n\"]*)\"(?: \"([^\n\"]*)\")?')
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(regex, contents)
update_mode_list(mode, required_resources, results)
# Check if any languages are missed
error_text = ''
for mode in modes:
for (resource_slug, languages) in required_resources[mode].items():
if languages:
error_text += f"\n{resource_slug} does not generate PDFs for the {mode} website for the following languages: {languages}"
if error_text:
raise Exception(error_text)
def update_mode_list(mode, required_resources, results):
for (resource_slug, language) in results:
if not language:
del required_resources[mode][resource_slug]
if language:
required_resources[mode][resource_slug].remove(language)
|
<commit_before>"""Tests for resource generation."""
import os
import re
from django.core import management
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resources_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
modes = ["dev", "prod"]
for mode in modes:
generated_resource_names = set()
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(
'makeresources \"(?P<resource_name>[^\"]*)\"',
contents,
re.M
)
generated_resource_names.update(results)
self.assertEqual(
generated_resource_names,
set(Resource.objects.values_list("name", flat=True))
)
<commit_msg>Fix test for checking resource PDF generation<commit_after>
|
"""Tests for resource generation."""
import os
import re
import copy
from django.core import management
from config.settings.base import DEFAULT_LANGUAGES as LANGUAGES
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resource_pdfs_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
# Generate all resource combinations in dictionary
modes = ["dev", "prod"]
resource_slugs = set(Resource.objects.values_list("slug", flat=True))
languages = [lang[0] for lang in LANGUAGES]
required_resources = dict()
for mode in modes:
required_resources[mode] = dict()
for resource_slug in resource_slugs:
required_resources[mode][resource_slug] = languages[:]
# Check files for resource generations
regex = re.compile(r'makeresources \"([^\n\"]*)\"(?: \"([^\n\"]*)\")?')
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(regex, contents)
update_mode_list(mode, required_resources, results)
# Check if any languages are missed
error_text = ''
for mode in modes:
for (resource_slug, languages) in required_resources[mode].items():
if languages:
error_text += f"\n{resource_slug} does not generate PDFs for the {mode} website for the following languages: {languages}"
if error_text:
raise Exception(error_text)
def update_mode_list(mode, required_resources, results):
for (resource_slug, language) in results:
if not language:
del required_resources[mode][resource_slug]
if language:
required_resources[mode][resource_slug].remove(language)
|
"""Tests for resource generation."""
import os
import re
from django.core import management
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resources_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
modes = ["dev", "prod"]
for mode in modes:
generated_resource_names = set()
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(
'makeresources \"(?P<resource_name>[^\"]*)\"',
contents,
re.M
)
generated_resource_names.update(results)
self.assertEqual(
generated_resource_names,
set(Resource.objects.values_list("name", flat=True))
)
Fix test for checking resource PDF generation"""Tests for resource generation."""
import os
import re
import copy
from django.core import management
from config.settings.base import DEFAULT_LANGUAGES as LANGUAGES
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resource_pdfs_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
# Generate all resource combinations in dictionary
modes = ["dev", "prod"]
resource_slugs = set(Resource.objects.values_list("slug", flat=True))
languages = [lang[0] for lang in LANGUAGES]
required_resources = dict()
for mode in modes:
required_resources[mode] = dict()
for resource_slug in resource_slugs:
required_resources[mode][resource_slug] = languages[:]
# Check files for resource generations
regex = re.compile(r'makeresources \"([^\n\"]*)\"(?: \"([^\n\"]*)\")?')
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(regex, contents)
update_mode_list(mode, required_resources, results)
# Check if any languages are missed
error_text = ''
for mode in modes:
for (resource_slug, languages) in required_resources[mode].items():
if languages:
error_text += f"\n{resource_slug} does not generate PDFs for the {mode} website for the following languages: {languages}"
if error_text:
raise Exception(error_text)
def update_mode_list(mode, required_resources, results):
for (resource_slug, language) in results:
if not language:
del required_resources[mode][resource_slug]
if language:
required_resources[mode][resource_slug].remove(language)
|
<commit_before>"""Tests for resource generation."""
import os
import re
from django.core import management
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resources_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
modes = ["dev", "prod"]
for mode in modes:
generated_resource_names = set()
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(
'makeresources \"(?P<resource_name>[^\"]*)\"',
contents,
re.M
)
generated_resource_names.update(results)
self.assertEqual(
generated_resource_names,
set(Resource.objects.values_list("name", flat=True))
)
<commit_msg>Fix test for checking resource PDF generation<commit_after>"""Tests for resource generation."""
import os
import re
import copy
from django.core import management
from config.settings.base import DEFAULT_LANGUAGES as LANGUAGES
from tests.BaseTestWithDB import BaseTestWithDB
from resources.models import Resource
class ResourceGenerationTest(BaseTestWithDB):
"""Tests for resource generation."""
def test_all_resource_pdfs_are_generated(self):
# Check all resources are generated for each langage
management.call_command("loadresources")
# Generate all resource combinations in dictionary
modes = ["dev", "prod"]
resource_slugs = set(Resource.objects.values_list("slug", flat=True))
languages = [lang[0] for lang in LANGUAGES]
required_resources = dict()
for mode in modes:
required_resources[mode] = dict()
for resource_slug in resource_slugs:
required_resources[mode][resource_slug] = languages[:]
# Check files for resource generations
regex = re.compile(r'makeresources \"([^\n\"]*)\"(?: \"([^\n\"]*)\")?')
path = "../infrastructure/{}-deploy/".format(mode)
for filename in sorted(os.listdir(path)):
if filename.startswith("deploy-resources"):
with open(os.path.join(path, filename), "r") as f:
contents = f.read()
results = re.findall(regex, contents)
update_mode_list(mode, required_resources, results)
# Check if any languages are missed
error_text = ''
for mode in modes:
for (resource_slug, languages) in required_resources[mode].items():
if languages:
error_text += f"\n{resource_slug} does not generate PDFs for the {mode} website for the following languages: {languages}"
if error_text:
raise Exception(error_text)
def update_mode_list(mode, required_resources, results):
for (resource_slug, language) in results:
if not language:
del required_resources[mode][resource_slug]
if language:
required_resources[mode][resource_slug].remove(language)
|
c3e2c6f77dffc2ff5874c1bb495e6de119800cf4
|
rx/core/observable/merge.py
|
rx/core/observable/merge.py
|
import rx
from rx import operators as ops
from rx.core import Observable
def _merge(*args) -> Observable:
"""Merges all the observable sequences into a single observable
sequence.
1 - merged = rx.merge(xs, ys, zs)
2 - merged = rx.merge([xs, ys, zs])
Returns:
The observable sequence that merges the elements of the
observable sequences.
"""
sources = args[:]
if isinstance(sources[0], list):
sources = sources[0]
return rx.from_iterable(sources).pipe(ops.merge_all())
|
from typing import Iterable, Union
import rx
from rx import operators as ops
from rx.core import Observable
def _merge(*args: Union[Observable, Iterable[Observable]]) -> Observable:
"""Merges all the observable sequences into a single observable
sequence.
1 - merged = rx.merge(xs, ys, zs)
2 - merged = rx.merge([xs, ys, zs])
Returns:
The observable sequence that merges the elements of the
observable sequences.
"""
sources = args[:]
if isinstance(sources[0], Iterable):
sources = sources[0]
return rx.from_iterable(sources).pipe(ops.merge_all())
|
Fix typing and accept iterable instead of list
|
Fix typing and accept iterable instead of list
|
Python
|
mit
|
ReactiveX/RxPY,ReactiveX/RxPY
|
import rx
from rx import operators as ops
from rx.core import Observable
def _merge(*args) -> Observable:
"""Merges all the observable sequences into a single observable
sequence.
1 - merged = rx.merge(xs, ys, zs)
2 - merged = rx.merge([xs, ys, zs])
Returns:
The observable sequence that merges the elements of the
observable sequences.
"""
sources = args[:]
if isinstance(sources[0], list):
sources = sources[0]
return rx.from_iterable(sources).pipe(ops.merge_all())
Fix typing and accept iterable instead of list
|
from typing import Iterable, Union
import rx
from rx import operators as ops
from rx.core import Observable
def _merge(*args: Union[Observable, Iterable[Observable]]) -> Observable:
"""Merges all the observable sequences into a single observable
sequence.
1 - merged = rx.merge(xs, ys, zs)
2 - merged = rx.merge([xs, ys, zs])
Returns:
The observable sequence that merges the elements of the
observable sequences.
"""
sources = args[:]
if isinstance(sources[0], Iterable):
sources = sources[0]
return rx.from_iterable(sources).pipe(ops.merge_all())
|
<commit_before>import rx
from rx import operators as ops
from rx.core import Observable
def _merge(*args) -> Observable:
"""Merges all the observable sequences into a single observable
sequence.
1 - merged = rx.merge(xs, ys, zs)
2 - merged = rx.merge([xs, ys, zs])
Returns:
The observable sequence that merges the elements of the
observable sequences.
"""
sources = args[:]
if isinstance(sources[0], list):
sources = sources[0]
return rx.from_iterable(sources).pipe(ops.merge_all())
<commit_msg>Fix typing and accept iterable instead of list<commit_after>
|
from typing import Iterable, Union
import rx
from rx import operators as ops
from rx.core import Observable
def _merge(*args: Union[Observable, Iterable[Observable]]) -> Observable:
"""Merges all the observable sequences into a single observable
sequence.
1 - merged = rx.merge(xs, ys, zs)
2 - merged = rx.merge([xs, ys, zs])
Returns:
The observable sequence that merges the elements of the
observable sequences.
"""
sources = args[:]
if isinstance(sources[0], Iterable):
sources = sources[0]
return rx.from_iterable(sources).pipe(ops.merge_all())
|
import rx
from rx import operators as ops
from rx.core import Observable
def _merge(*args) -> Observable:
"""Merges all the observable sequences into a single observable
sequence.
1 - merged = rx.merge(xs, ys, zs)
2 - merged = rx.merge([xs, ys, zs])
Returns:
The observable sequence that merges the elements of the
observable sequences.
"""
sources = args[:]
if isinstance(sources[0], list):
sources = sources[0]
return rx.from_iterable(sources).pipe(ops.merge_all())
Fix typing and accept iterable instead of listfrom typing import Iterable, Union
import rx
from rx import operators as ops
from rx.core import Observable
def _merge(*args: Union[Observable, Iterable[Observable]]) -> Observable:
"""Merges all the observable sequences into a single observable
sequence.
1 - merged = rx.merge(xs, ys, zs)
2 - merged = rx.merge([xs, ys, zs])
Returns:
The observable sequence that merges the elements of the
observable sequences.
"""
sources = args[:]
if isinstance(sources[0], Iterable):
sources = sources[0]
return rx.from_iterable(sources).pipe(ops.merge_all())
|
<commit_before>import rx
from rx import operators as ops
from rx.core import Observable
def _merge(*args) -> Observable:
"""Merges all the observable sequences into a single observable
sequence.
1 - merged = rx.merge(xs, ys, zs)
2 - merged = rx.merge([xs, ys, zs])
Returns:
The observable sequence that merges the elements of the
observable sequences.
"""
sources = args[:]
if isinstance(sources[0], list):
sources = sources[0]
return rx.from_iterable(sources).pipe(ops.merge_all())
<commit_msg>Fix typing and accept iterable instead of list<commit_after>from typing import Iterable, Union
import rx
from rx import operators as ops
from rx.core import Observable
def _merge(*args: Union[Observable, Iterable[Observable]]) -> Observable:
"""Merges all the observable sequences into a single observable
sequence.
1 - merged = rx.merge(xs, ys, zs)
2 - merged = rx.merge([xs, ys, zs])
Returns:
The observable sequence that merges the elements of the
observable sequences.
"""
sources = args[:]
if isinstance(sources[0], Iterable):
sources = sources[0]
return rx.from_iterable(sources).pipe(ops.merge_all())
|
595555433d7495ab54cdeb26d37cb2bc6c58f830
|
plyades/core.py
|
plyades/core.py
|
import datetime
import numpy as np
class Epoch(datetime.datetime):
def get_jd(self, epoch=2000):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
if epoch == 2000:
return jd - 2451544.5
elif epoch == 1950:
return jd - 2433282.5
elif epoch == "mjd":
return jd - 2400000.5
elif epoch == 0:
return jd
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epoch
|
import datetime
import numpy as np
class Epoch(datetime.datetime):
@property
def jd(self):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
return jd
@property
def jd2000(self):
return self.jd - 2451544.5
@property
def jd1950(self):
return self.jd - 2433282.5
@property
def mjd(self):
return self.jd - 2400000.5
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epoch
|
Change julian date to be a property.
|
Change julian date to be a property.
|
Python
|
mit
|
helgee/plyades
|
import datetime
import numpy as np
class Epoch(datetime.datetime):
def get_jd(self, epoch=2000):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
if epoch == 2000:
return jd - 2451544.5
elif epoch == 1950:
return jd - 2433282.5
elif epoch == "mjd":
return jd - 2400000.5
elif epoch == 0:
return jd
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epochChange julian date to be a property.
|
import datetime
import numpy as np
class Epoch(datetime.datetime):
@property
def jd(self):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
return jd
@property
def jd2000(self):
return self.jd - 2451544.5
@property
def jd1950(self):
return self.jd - 2433282.5
@property
def mjd(self):
return self.jd - 2400000.5
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epoch
|
<commit_before>import datetime
import numpy as np
class Epoch(datetime.datetime):
def get_jd(self, epoch=2000):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
if epoch == 2000:
return jd - 2451544.5
elif epoch == 1950:
return jd - 2433282.5
elif epoch == "mjd":
return jd - 2400000.5
elif epoch == 0:
return jd
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epoch<commit_msg>Change julian date to be a property.<commit_after>
|
import datetime
import numpy as np
class Epoch(datetime.datetime):
@property
def jd(self):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
return jd
@property
def jd2000(self):
return self.jd - 2451544.5
@property
def jd1950(self):
return self.jd - 2433282.5
@property
def mjd(self):
return self.jd - 2400000.5
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epoch
|
import datetime
import numpy as np
class Epoch(datetime.datetime):
def get_jd(self, epoch=2000):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
if epoch == 2000:
return jd - 2451544.5
elif epoch == 1950:
return jd - 2433282.5
elif epoch == "mjd":
return jd - 2400000.5
elif epoch == 0:
return jd
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epochChange julian date to be a property.import datetime
import numpy as np
class Epoch(datetime.datetime):
@property
def jd(self):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
return jd
@property
def jd2000(self):
return self.jd - 2451544.5
@property
def jd1950(self):
return self.jd - 2433282.5
@property
def mjd(self):
return self.jd - 2400000.5
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epoch
|
<commit_before>import datetime
import numpy as np
class Epoch(datetime.datetime):
def get_jd(self, epoch=2000):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
if epoch == 2000:
return jd - 2451544.5
elif epoch == 1950:
return jd - 2433282.5
elif epoch == "mjd":
return jd - 2400000.5
elif epoch == 0:
return jd
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epoch<commit_msg>Change julian date to be a property.<commit_after>import datetime
import numpy as np
class Epoch(datetime.datetime):
@property
def jd(self):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
return jd
@property
def jd2000(self):
return self.jd - 2451544.5
@property
def jd1950(self):
return self.jd - 2433282.5
@property
def mjd(self):
return self.jd - 2400000.5
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epoch
|
d120e092c2e6422e63500666947aea43891908c2
|
progress_bar.py
|
progress_bar.py
|
import sys
import time
index = 0
for url_dict in range(100):
time.sleep(0.1)
index += 1
percentual = "%.2f%%" % index
sys.stdout.write('\r[{0}{1}] {2}'.format('#' * index,
' ' * (100-index),
percentual))
sys.stdout.flush()
print("")
|
import sys
import time
import math
n_messages = 650
for index, url_dict in enumerate(range(n_messages)):
index += 1
time.sleep(0.01)
progress_index = math.floor(index/n_messages*100)
percentual = "%.2f%%" % progress_index
sys.stdout.write('\r[{0}{1}] {2}'.format('#' * progress_index,
' ' * (100-progress_index),
percentual))
sys.stdout.flush()
print("")
|
Make it work properly with every number
|
Make it work properly with every number
|
Python
|
mit
|
victorpantoja/python-progress-bar
|
import sys
import time
index = 0
for url_dict in range(100):
time.sleep(0.1)
index += 1
percentual = "%.2f%%" % index
sys.stdout.write('\r[{0}{1}] {2}'.format('#' * index,
' ' * (100-index),
percentual))
sys.stdout.flush()
print("")
Make it work properly with every number
|
import sys
import time
import math
n_messages = 650
for index, url_dict in enumerate(range(n_messages)):
index += 1
time.sleep(0.01)
progress_index = math.floor(index/n_messages*100)
percentual = "%.2f%%" % progress_index
sys.stdout.write('\r[{0}{1}] {2}'.format('#' * progress_index,
' ' * (100-progress_index),
percentual))
sys.stdout.flush()
print("")
|
<commit_before>import sys
import time
index = 0
for url_dict in range(100):
time.sleep(0.1)
index += 1
percentual = "%.2f%%" % index
sys.stdout.write('\r[{0}{1}] {2}'.format('#' * index,
' ' * (100-index),
percentual))
sys.stdout.flush()
print("")
<commit_msg>Make it work properly with every number<commit_after>
|
import sys
import time
import math
n_messages = 650
for index, url_dict in enumerate(range(n_messages)):
index += 1
time.sleep(0.01)
progress_index = math.floor(index/n_messages*100)
percentual = "%.2f%%" % progress_index
sys.stdout.write('\r[{0}{1}] {2}'.format('#' * progress_index,
' ' * (100-progress_index),
percentual))
sys.stdout.flush()
print("")
|
import sys
import time
index = 0
for url_dict in range(100):
time.sleep(0.1)
index += 1
percentual = "%.2f%%" % index
sys.stdout.write('\r[{0}{1}] {2}'.format('#' * index,
' ' * (100-index),
percentual))
sys.stdout.flush()
print("")
Make it work properly with every numberimport sys
import time
import math
n_messages = 650
for index, url_dict in enumerate(range(n_messages)):
index += 1
time.sleep(0.01)
progress_index = math.floor(index/n_messages*100)
percentual = "%.2f%%" % progress_index
sys.stdout.write('\r[{0}{1}] {2}'.format('#' * progress_index,
' ' * (100-progress_index),
percentual))
sys.stdout.flush()
print("")
|
<commit_before>import sys
import time
index = 0
for url_dict in range(100):
time.sleep(0.1)
index += 1
percentual = "%.2f%%" % index
sys.stdout.write('\r[{0}{1}] {2}'.format('#' * index,
' ' * (100-index),
percentual))
sys.stdout.flush()
print("")
<commit_msg>Make it work properly with every number<commit_after>import sys
import time
import math
n_messages = 650
for index, url_dict in enumerate(range(n_messages)):
index += 1
time.sleep(0.01)
progress_index = math.floor(index/n_messages*100)
percentual = "%.2f%%" % progress_index
sys.stdout.write('\r[{0}{1}] {2}'.format('#' * progress_index,
' ' * (100-progress_index),
percentual))
sys.stdout.flush()
print("")
|
ad5eaca5dfc3f9cdc913932655808d3511bc29f3
|
python/setup.py
|
python/setup.py
|
from distutils.core import setup
long_description = open("README.rst").read()
long_description += "\n.. code-block:: python\n\n "
long_description += "\n ".join(open("output_example.py").read().split("\n"))
setup(
name="radiance",
version="0.1dev5",
packages=["radiance",],
license="MIT",
description="Python tools for the Radiance video art system",
long_description_content_type="text/x-rst",
long_description=long_description,
url="https://radiance.video",
author="Eric Van Albert",
author_email="eric@van.al",
)
|
from distutils.core import setup
long_description = open("README.rst").read()
long_description += "\n.. code-block:: python\n\n "
long_description += "\n ".join(open("output_example.py").read().split("\n"))
setup(
name="radiance",
version="0.1",
packages=["radiance",],
license="MIT",
description="Python tools for the Radiance video art system",
long_description_content_type="text/x-rst",
long_description=long_description,
url="https://radiance.video",
author="Eric Van Albert",
author_email="eric@van.al",
)
|
Change version to 0.1 for the pull request
|
Change version to 0.1 for the pull request
|
Python
|
mit
|
zbanks/radiance,zbanks/radiance,zbanks/radiance,zbanks/radiance
|
from distutils.core import setup
long_description = open("README.rst").read()
long_description += "\n.. code-block:: python\n\n "
long_description += "\n ".join(open("output_example.py").read().split("\n"))
setup(
name="radiance",
version="0.1dev5",
packages=["radiance",],
license="MIT",
description="Python tools for the Radiance video art system",
long_description_content_type="text/x-rst",
long_description=long_description,
url="https://radiance.video",
author="Eric Van Albert",
author_email="eric@van.al",
)
Change version to 0.1 for the pull request
|
from distutils.core import setup
long_description = open("README.rst").read()
long_description += "\n.. code-block:: python\n\n "
long_description += "\n ".join(open("output_example.py").read().split("\n"))
setup(
name="radiance",
version="0.1",
packages=["radiance",],
license="MIT",
description="Python tools for the Radiance video art system",
long_description_content_type="text/x-rst",
long_description=long_description,
url="https://radiance.video",
author="Eric Van Albert",
author_email="eric@van.al",
)
|
<commit_before>from distutils.core import setup
long_description = open("README.rst").read()
long_description += "\n.. code-block:: python\n\n "
long_description += "\n ".join(open("output_example.py").read().split("\n"))
setup(
name="radiance",
version="0.1dev5",
packages=["radiance",],
license="MIT",
description="Python tools for the Radiance video art system",
long_description_content_type="text/x-rst",
long_description=long_description,
url="https://radiance.video",
author="Eric Van Albert",
author_email="eric@van.al",
)
<commit_msg>Change version to 0.1 for the pull request<commit_after>
|
from distutils.core import setup
long_description = open("README.rst").read()
long_description += "\n.. code-block:: python\n\n "
long_description += "\n ".join(open("output_example.py").read().split("\n"))
setup(
name="radiance",
version="0.1",
packages=["radiance",],
license="MIT",
description="Python tools for the Radiance video art system",
long_description_content_type="text/x-rst",
long_description=long_description,
url="https://radiance.video",
author="Eric Van Albert",
author_email="eric@van.al",
)
|
from distutils.core import setup
long_description = open("README.rst").read()
long_description += "\n.. code-block:: python\n\n "
long_description += "\n ".join(open("output_example.py").read().split("\n"))
setup(
name="radiance",
version="0.1dev5",
packages=["radiance",],
license="MIT",
description="Python tools for the Radiance video art system",
long_description_content_type="text/x-rst",
long_description=long_description,
url="https://radiance.video",
author="Eric Van Albert",
author_email="eric@van.al",
)
Change version to 0.1 for the pull requestfrom distutils.core import setup
long_description = open("README.rst").read()
long_description += "\n.. code-block:: python\n\n "
long_description += "\n ".join(open("output_example.py").read().split("\n"))
setup(
name="radiance",
version="0.1",
packages=["radiance",],
license="MIT",
description="Python tools for the Radiance video art system",
long_description_content_type="text/x-rst",
long_description=long_description,
url="https://radiance.video",
author="Eric Van Albert",
author_email="eric@van.al",
)
|
<commit_before>from distutils.core import setup
long_description = open("README.rst").read()
long_description += "\n.. code-block:: python\n\n "
long_description += "\n ".join(open("output_example.py").read().split("\n"))
setup(
name="radiance",
version="0.1dev5",
packages=["radiance",],
license="MIT",
description="Python tools for the Radiance video art system",
long_description_content_type="text/x-rst",
long_description=long_description,
url="https://radiance.video",
author="Eric Van Albert",
author_email="eric@van.al",
)
<commit_msg>Change version to 0.1 for the pull request<commit_after>from distutils.core import setup
long_description = open("README.rst").read()
long_description += "\n.. code-block:: python\n\n "
long_description += "\n ".join(open("output_example.py").read().split("\n"))
setup(
name="radiance",
version="0.1",
packages=["radiance",],
license="MIT",
description="Python tools for the Radiance video art system",
long_description_content_type="text/x-rst",
long_description=long_description,
url="https://radiance.video",
author="Eric Van Albert",
author_email="eric@van.al",
)
|
ec3c033a9140f3ef6aaf3d278704513a6db7d847
|
inthe_am/taskmanager/management/commands/runtests.py
|
inthe_am/taskmanager/management/commands/runtests.py
|
import os
import subprocess
import sys
import threading
import time
from .run import Command as RunserverCommand
class Command(RunserverCommand):
def run_tests(self):
env = os.environ.copy()
env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001'
return subprocess.call(
[
'python',
'manage.py',
'test',
'taskmanager',
],
env=env,
)
def handle(self, *args, **kwargs):
fnull = open(os.devnull, 'w')
ember = threading.Thread(
target=self.run_ember,
#kwargs={
# 'stdout': fnull,
# 'stderr': subprocess.STDOUT
#}
)
ember.daemon = True
ember.start()
time.sleep(10)
sys.exit(self.run_tests())
|
import os
import subprocess
import sys
import threading
import time
from .run import Command as RunserverCommand
class Command(RunserverCommand):
def run_tests(self):
env = os.environ.copy()
env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001'
return subprocess.call(
[
'python',
'manage.py',
'test',
'taskmanager',
],
env=env,
)
def handle(self, *args, **kwargs):
fnull = open(os.devnull, 'w')
ember = threading.Thread(
target=self.run_ember,
kwargs={
'stdout': fnull,
'stderr': subprocess.STDOUT
}
)
ember.daemon = True
ember.start()
time.sleep(10)
sys.exit(self.run_tests())
|
Hide ember.js output from Travis.ci tests.
|
Hide ember.js output from Travis.ci tests.
|
Python
|
agpl-3.0
|
coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am
|
import os
import subprocess
import sys
import threading
import time
from .run import Command as RunserverCommand
class Command(RunserverCommand):
def run_tests(self):
env = os.environ.copy()
env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001'
return subprocess.call(
[
'python',
'manage.py',
'test',
'taskmanager',
],
env=env,
)
def handle(self, *args, **kwargs):
fnull = open(os.devnull, 'w')
ember = threading.Thread(
target=self.run_ember,
#kwargs={
# 'stdout': fnull,
# 'stderr': subprocess.STDOUT
#}
)
ember.daemon = True
ember.start()
time.sleep(10)
sys.exit(self.run_tests())
Hide ember.js output from Travis.ci tests.
|
import os
import subprocess
import sys
import threading
import time
from .run import Command as RunserverCommand
class Command(RunserverCommand):
def run_tests(self):
env = os.environ.copy()
env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001'
return subprocess.call(
[
'python',
'manage.py',
'test',
'taskmanager',
],
env=env,
)
def handle(self, *args, **kwargs):
fnull = open(os.devnull, 'w')
ember = threading.Thread(
target=self.run_ember,
kwargs={
'stdout': fnull,
'stderr': subprocess.STDOUT
}
)
ember.daemon = True
ember.start()
time.sleep(10)
sys.exit(self.run_tests())
|
<commit_before>import os
import subprocess
import sys
import threading
import time
from .run import Command as RunserverCommand
class Command(RunserverCommand):
def run_tests(self):
env = os.environ.copy()
env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001'
return subprocess.call(
[
'python',
'manage.py',
'test',
'taskmanager',
],
env=env,
)
def handle(self, *args, **kwargs):
fnull = open(os.devnull, 'w')
ember = threading.Thread(
target=self.run_ember,
#kwargs={
# 'stdout': fnull,
# 'stderr': subprocess.STDOUT
#}
)
ember.daemon = True
ember.start()
time.sleep(10)
sys.exit(self.run_tests())
<commit_msg>Hide ember.js output from Travis.ci tests.<commit_after>
|
import os
import subprocess
import sys
import threading
import time
from .run import Command as RunserverCommand
class Command(RunserverCommand):
def run_tests(self):
env = os.environ.copy()
env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001'
return subprocess.call(
[
'python',
'manage.py',
'test',
'taskmanager',
],
env=env,
)
def handle(self, *args, **kwargs):
fnull = open(os.devnull, 'w')
ember = threading.Thread(
target=self.run_ember,
kwargs={
'stdout': fnull,
'stderr': subprocess.STDOUT
}
)
ember.daemon = True
ember.start()
time.sleep(10)
sys.exit(self.run_tests())
|
import os
import subprocess
import sys
import threading
import time
from .run import Command as RunserverCommand
class Command(RunserverCommand):
def run_tests(self):
env = os.environ.copy()
env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001'
return subprocess.call(
[
'python',
'manage.py',
'test',
'taskmanager',
],
env=env,
)
def handle(self, *args, **kwargs):
fnull = open(os.devnull, 'w')
ember = threading.Thread(
target=self.run_ember,
#kwargs={
# 'stdout': fnull,
# 'stderr': subprocess.STDOUT
#}
)
ember.daemon = True
ember.start()
time.sleep(10)
sys.exit(self.run_tests())
Hide ember.js output from Travis.ci tests.import os
import subprocess
import sys
import threading
import time
from .run import Command as RunserverCommand
class Command(RunserverCommand):
def run_tests(self):
env = os.environ.copy()
env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001'
return subprocess.call(
[
'python',
'manage.py',
'test',
'taskmanager',
],
env=env,
)
def handle(self, *args, **kwargs):
fnull = open(os.devnull, 'w')
ember = threading.Thread(
target=self.run_ember,
kwargs={
'stdout': fnull,
'stderr': subprocess.STDOUT
}
)
ember.daemon = True
ember.start()
time.sleep(10)
sys.exit(self.run_tests())
|
<commit_before>import os
import subprocess
import sys
import threading
import time
from .run import Command as RunserverCommand
class Command(RunserverCommand):
def run_tests(self):
env = os.environ.copy()
env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001'
return subprocess.call(
[
'python',
'manage.py',
'test',
'taskmanager',
],
env=env,
)
def handle(self, *args, **kwargs):
fnull = open(os.devnull, 'w')
ember = threading.Thread(
target=self.run_ember,
#kwargs={
# 'stdout': fnull,
# 'stderr': subprocess.STDOUT
#}
)
ember.daemon = True
ember.start()
time.sleep(10)
sys.exit(self.run_tests())
<commit_msg>Hide ember.js output from Travis.ci tests.<commit_after>import os
import subprocess
import sys
import threading
import time
from .run import Command as RunserverCommand
class Command(RunserverCommand):
def run_tests(self):
env = os.environ.copy()
env['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = 'localhost:8001'
return subprocess.call(
[
'python',
'manage.py',
'test',
'taskmanager',
],
env=env,
)
def handle(self, *args, **kwargs):
fnull = open(os.devnull, 'w')
ember = threading.Thread(
target=self.run_ember,
kwargs={
'stdout': fnull,
'stderr': subprocess.STDOUT
}
)
ember.daemon = True
ember.start()
time.sleep(10)
sys.exit(self.run_tests())
|
33e1c781b0e430cb1e0df19d02ed06a193f9d202
|
waterbutler/identity.py
|
waterbutler/identity.py
|
import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
IDENTITY_METHODS = {
'rest': fetch_rest_identity
}
get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]
|
import asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identity(func):
IDENTITY_METHODS[name] = func
return func
return _register_identity
def get_identity(name, **kwargs):
return get_identity_func(name)(**kwargs)
@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
|
Make use of a register decorator
|
Make use of a register decorator
|
Python
|
apache-2.0
|
CenterForOpenScience/waterbutler,kwierman/waterbutler,TomBaxter/waterbutler,rafaeldelucena/waterbutler,Ghalko/waterbutler,RCOSDP/waterbutler,hmoco/waterbutler,felliott/waterbutler,rdhyee/waterbutler,Johnetordoff/waterbutler,icereval/waterbutler,chrisseto/waterbutler,cosenal/waterbutler
|
import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
IDENTITY_METHODS = {
'rest': fetch_rest_identity
}
get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]
Make use of a register decorator
|
import asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identity(func):
IDENTITY_METHODS[name] = func
return func
return _register_identity
def get_identity(name, **kwargs):
return get_identity_func(name)(**kwargs)
@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
|
<commit_before>import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
IDENTITY_METHODS = {
'rest': fetch_rest_identity
}
get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]
<commit_msg>Make use of a register decorator<commit_after>
|
import asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identity(func):
IDENTITY_METHODS[name] = func
return func
return _register_identity
def get_identity(name, **kwargs):
return get_identity_func(name)(**kwargs)
@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
|
import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
IDENTITY_METHODS = {
'rest': fetch_rest_identity
}
get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]
Make use of a register decoratorimport asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identity(func):
IDENTITY_METHODS[name] = func
return func
return _register_identity
def get_identity(name, **kwargs):
return get_identity_func(name)(**kwargs)
@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
|
<commit_before>import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
IDENTITY_METHODS = {
'rest': fetch_rest_identity
}
get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]
<commit_msg>Make use of a register decorator<commit_after>import asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identity(func):
IDENTITY_METHODS[name] = func
return func
return _register_identity
def get_identity(name, **kwargs):
return get_identity_func(name)(**kwargs)
@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
|
0fe125a0816eaca0986ffe288b583b3dc27b6752
|
masters/master.tryserver.chromium.perf/master_site_config.py
|
masters/master.tryserver.chromium.perf/master_site_config.py
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try'
last_good_url = base_app_url + '/lkgr'
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try-perf'
last_good_url = base_app_url + '/lkgr'
|
Change tryserver.chromium.perf to watch chrome-try/try-perf
|
Change tryserver.chromium.perf to watch chrome-try/try-perf
so that perf bisect tryjobs are isolated to their own repo to avoid
cross contamination.
BUG=416009
Review URL: https://codereview.chromium.org/588353002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292078 0039d316-1c4b-4281-b951-d872f2087c98
|
Python
|
bsd-3-clause
|
eunchong/build,eunchong/build,eunchong/build,eunchong/build
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try'
last_good_url = base_app_url + '/lkgr'
Change tryserver.chromium.perf to watch chrome-try/try-perf
so that perf bisect tryjobs are isolated to their own repo to avoid
cross contamination.
BUG=416009
Review URL: https://codereview.chromium.org/588353002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292078 0039d316-1c4b-4281-b951-d872f2087c98
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try-perf'
last_good_url = base_app_url + '/lkgr'
|
<commit_before># Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try'
last_good_url = base_app_url + '/lkgr'
<commit_msg>Change tryserver.chromium.perf to watch chrome-try/try-perf
so that perf bisect tryjobs are isolated to their own repo to avoid
cross contamination.
BUG=416009
Review URL: https://codereview.chromium.org/588353002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292078 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try-perf'
last_good_url = base_app_url + '/lkgr'
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try'
last_good_url = base_app_url + '/lkgr'
Change tryserver.chromium.perf to watch chrome-try/try-perf
so that perf bisect tryjobs are isolated to their own repo to avoid
cross contamination.
BUG=416009
Review URL: https://codereview.chromium.org/588353002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292078 0039d316-1c4b-4281-b951-d872f2087c98# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try-perf'
last_good_url = base_app_url + '/lkgr'
|
<commit_before># Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try'
last_good_url = base_app_url + '/lkgr'
<commit_msg>Change tryserver.chromium.perf to watch chrome-try/try-perf
so that perf bisect tryjobs are isolated to their own repo to avoid
cross contamination.
BUG=416009
Review URL: https://codereview.chromium.org/588353002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292078 0039d316-1c4b-4281-b951-d872f2087c98<commit_after># Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumPerfTryServer(Master.Master4):
project_name = 'Chromium Perf Try Server'
master_port = 8041
slave_port = 8141
master_port_alt = 8241
try_job_port = 8341
# Select tree status urls and codereview location.
reply_to = 'chrome-troopers+tryserver@google.com'
base_app_url = 'https://chromium-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
svn_url = 'svn://svn-mirror.golo.chromium.org/chrome-try/try-perf'
last_good_url = base_app_url + '/lkgr'
|
b33b063e49b394265bc890f6d3b39da08e355416
|
blogs/tests/test_parser.py
|
blogs/tests/test_parser.py
|
from unittest import TestCase
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(TestCase):
def setUp(self):
self.test_file_path = get_test_rss_path()
self.entries = get_all_entries("file://{}".format(self.test_file_path))
def test_entries(self):
""" Make sure we can parse RSS entries """
self.assertEqual(len(self.entries), 25)
|
import datetime
import unittest
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_file_path = get_test_rss_path()
cls.entries = get_all_entries("file://{}".format(cls.test_file_path))
def test_entries(self):
self.assertEqual(len(self.entries), 25)
self.assertEqual(
self.entries[0]['title'],
'Introducing Electronic Contributor Agreements'
)
self.assertIn(
"We're happy to announce the new way to file a contributor "
"agreement: on the web at",
self.entries[0]['summary']
)
self.assertIsInstance(self.entries[0]['pub_date'], datetime.datetime)
self.assertEqual(
self.entries[0]['url'],
'http://feedproxy.google.com/~r/PythonInsider/~3/tGNCqyOiun4/introducing-electronic-contributor.html'
)
|
Add some tests to make sure we can parse RSS feeds
|
Add some tests to make sure we can parse RSS feeds
|
Python
|
apache-2.0
|
manhhomienbienthuy/pythondotorg,proevo/pythondotorg,manhhomienbienthuy/pythondotorg,proevo/pythondotorg,Mariatta/pythondotorg,Mariatta/pythondotorg,proevo/pythondotorg,python/pythondotorg,manhhomienbienthuy/pythondotorg,python/pythondotorg,Mariatta/pythondotorg,manhhomienbienthuy/pythondotorg,Mariatta/pythondotorg,python/pythondotorg,proevo/pythondotorg,python/pythondotorg
|
from unittest import TestCase
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(TestCase):
def setUp(self):
self.test_file_path = get_test_rss_path()
self.entries = get_all_entries("file://{}".format(self.test_file_path))
def test_entries(self):
""" Make sure we can parse RSS entries """
self.assertEqual(len(self.entries), 25)
Add some tests to make sure we can parse RSS feeds
|
import datetime
import unittest
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_file_path = get_test_rss_path()
cls.entries = get_all_entries("file://{}".format(cls.test_file_path))
def test_entries(self):
self.assertEqual(len(self.entries), 25)
self.assertEqual(
self.entries[0]['title'],
'Introducing Electronic Contributor Agreements'
)
self.assertIn(
"We're happy to announce the new way to file a contributor "
"agreement: on the web at",
self.entries[0]['summary']
)
self.assertIsInstance(self.entries[0]['pub_date'], datetime.datetime)
self.assertEqual(
self.entries[0]['url'],
'http://feedproxy.google.com/~r/PythonInsider/~3/tGNCqyOiun4/introducing-electronic-contributor.html'
)
|
<commit_before>from unittest import TestCase
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(TestCase):
def setUp(self):
self.test_file_path = get_test_rss_path()
self.entries = get_all_entries("file://{}".format(self.test_file_path))
def test_entries(self):
""" Make sure we can parse RSS entries """
self.assertEqual(len(self.entries), 25)
<commit_msg>Add some tests to make sure we can parse RSS feeds<commit_after>
|
import datetime
import unittest
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_file_path = get_test_rss_path()
cls.entries = get_all_entries("file://{}".format(cls.test_file_path))
def test_entries(self):
self.assertEqual(len(self.entries), 25)
self.assertEqual(
self.entries[0]['title'],
'Introducing Electronic Contributor Agreements'
)
self.assertIn(
"We're happy to announce the new way to file a contributor "
"agreement: on the web at",
self.entries[0]['summary']
)
self.assertIsInstance(self.entries[0]['pub_date'], datetime.datetime)
self.assertEqual(
self.entries[0]['url'],
'http://feedproxy.google.com/~r/PythonInsider/~3/tGNCqyOiun4/introducing-electronic-contributor.html'
)
|
from unittest import TestCase
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(TestCase):
def setUp(self):
self.test_file_path = get_test_rss_path()
self.entries = get_all_entries("file://{}".format(self.test_file_path))
def test_entries(self):
""" Make sure we can parse RSS entries """
self.assertEqual(len(self.entries), 25)
Add some tests to make sure we can parse RSS feedsimport datetime
import unittest
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_file_path = get_test_rss_path()
cls.entries = get_all_entries("file://{}".format(cls.test_file_path))
def test_entries(self):
self.assertEqual(len(self.entries), 25)
self.assertEqual(
self.entries[0]['title'],
'Introducing Electronic Contributor Agreements'
)
self.assertIn(
"We're happy to announce the new way to file a contributor "
"agreement: on the web at",
self.entries[0]['summary']
)
self.assertIsInstance(self.entries[0]['pub_date'], datetime.datetime)
self.assertEqual(
self.entries[0]['url'],
'http://feedproxy.google.com/~r/PythonInsider/~3/tGNCqyOiun4/introducing-electronic-contributor.html'
)
|
<commit_before>from unittest import TestCase
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(TestCase):
def setUp(self):
self.test_file_path = get_test_rss_path()
self.entries = get_all_entries("file://{}".format(self.test_file_path))
def test_entries(self):
""" Make sure we can parse RSS entries """
self.assertEqual(len(self.entries), 25)
<commit_msg>Add some tests to make sure we can parse RSS feeds<commit_after>import datetime
import unittest
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_file_path = get_test_rss_path()
cls.entries = get_all_entries("file://{}".format(cls.test_file_path))
def test_entries(self):
self.assertEqual(len(self.entries), 25)
self.assertEqual(
self.entries[0]['title'],
'Introducing Electronic Contributor Agreements'
)
self.assertIn(
"We're happy to announce the new way to file a contributor "
"agreement: on the web at",
self.entries[0]['summary']
)
self.assertIsInstance(self.entries[0]['pub_date'], datetime.datetime)
self.assertEqual(
self.entries[0]['url'],
'http://feedproxy.google.com/~r/PythonInsider/~3/tGNCqyOiun4/introducing-electronic-contributor.html'
)
|
5c677c11b35dcb49b9b33807685284bfe9d86338
|
xgds_map_server/urls.py
|
xgds_map_server/urls.py
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.conf.urls.defaults import *
from xgds_map_server import settings
from xgds_map_server.views import *
urlpatterns = patterns(
'',
(r'^$', getMapListPage,
{'readOnly': True},
'xgds_map_server_index'),
# Map server urls
# HTML list of maps with description and links to individual maps, and a link to the kml feed
(r'^list/', getMapListPage,
{'readOnly': True},
'mapList'),
# This URL should receive a static files
(r'^data/(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR,
'show_indexes' : True,
'readOnly': True},
'xgds_map_server_static'),
# By default if you just load the app you should see the list
(r'^feed/(?P<feedname>.*)', getMapFeed,
{'readOnly': True,
'challenge': settings.SECURITY_GOOGLE_EARTH_CHALLENGE},
'xgds_map_server_feed'),
)
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.conf.urls.defaults import *
from xgds_map_server import settings
from xgds_map_server.views import *
urlpatterns = patterns(
'',
(r'^$', getMapListPage,
{'readOnly': True},
'xgds_map_server_index'),
# Map server urls
# HTML list of maps with description and links to individual maps, and a link to the kml feed
(r'^list/', getMapListPage,
{'readOnly': True},
'mapList'),
# This URL should receive a static files
(r'^data/(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR,
'show_indexes' : True,
'readOnly': True},
'xgds_map_server_static'),
# By default if you just load the app you should see the list
(r'^feed/(?P<feedname>.*)', getMapFeed,
{'readOnly': True,
'loginRequired': False},
'xgds_map_server_feed'),
)
|
Tweak login required and auth settings to work with C3
|
Tweak login required and auth settings to work with C3
|
Python
|
apache-2.0
|
xgds/xgds_map_server,xgds/xgds_map_server,xgds/xgds_map_server
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.conf.urls.defaults import *
from xgds_map_server import settings
from xgds_map_server.views import *
urlpatterns = patterns(
'',
(r'^$', getMapListPage,
{'readOnly': True},
'xgds_map_server_index'),
# Map server urls
# HTML list of maps with description and links to individual maps, and a link to the kml feed
(r'^list/', getMapListPage,
{'readOnly': True},
'mapList'),
# This URL should receive a static files
(r'^data/(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR,
'show_indexes' : True,
'readOnly': True},
'xgds_map_server_static'),
# By default if you just load the app you should see the list
(r'^feed/(?P<feedname>.*)', getMapFeed,
{'readOnly': True,
'challenge': settings.SECURITY_GOOGLE_EARTH_CHALLENGE},
'xgds_map_server_feed'),
)
Tweak login required and auth settings to work with C3
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.conf.urls.defaults import *
from xgds_map_server import settings
from xgds_map_server.views import *
urlpatterns = patterns(
'',
(r'^$', getMapListPage,
{'readOnly': True},
'xgds_map_server_index'),
# Map server urls
# HTML list of maps with description and links to individual maps, and a link to the kml feed
(r'^list/', getMapListPage,
{'readOnly': True},
'mapList'),
# This URL should receive a static files
(r'^data/(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR,
'show_indexes' : True,
'readOnly': True},
'xgds_map_server_static'),
# By default if you just load the app you should see the list
(r'^feed/(?P<feedname>.*)', getMapFeed,
{'readOnly': True,
'loginRequired': False},
'xgds_map_server_feed'),
)
|
<commit_before># __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.conf.urls.defaults import *
from xgds_map_server import settings
from xgds_map_server.views import *
urlpatterns = patterns(
'',
(r'^$', getMapListPage,
{'readOnly': True},
'xgds_map_server_index'),
# Map server urls
# HTML list of maps with description and links to individual maps, and a link to the kml feed
(r'^list/', getMapListPage,
{'readOnly': True},
'mapList'),
# This URL should receive a static files
(r'^data/(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR,
'show_indexes' : True,
'readOnly': True},
'xgds_map_server_static'),
# By default if you just load the app you should see the list
(r'^feed/(?P<feedname>.*)', getMapFeed,
{'readOnly': True,
'challenge': settings.SECURITY_GOOGLE_EARTH_CHALLENGE},
'xgds_map_server_feed'),
)
<commit_msg>Tweak login required and auth settings to work with C3<commit_after>
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.conf.urls.defaults import *
from xgds_map_server import settings
from xgds_map_server.views import *
urlpatterns = patterns(
'',
(r'^$', getMapListPage,
{'readOnly': True},
'xgds_map_server_index'),
# Map server urls
# HTML list of maps with description and links to individual maps, and a link to the kml feed
(r'^list/', getMapListPage,
{'readOnly': True},
'mapList'),
# This URL should receive a static files
(r'^data/(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR,
'show_indexes' : True,
'readOnly': True},
'xgds_map_server_static'),
# By default if you just load the app you should see the list
(r'^feed/(?P<feedname>.*)', getMapFeed,
{'readOnly': True,
'loginRequired': False},
'xgds_map_server_feed'),
)
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.conf.urls.defaults import *
from xgds_map_server import settings
from xgds_map_server.views import *
urlpatterns = patterns(
'',
(r'^$', getMapListPage,
{'readOnly': True},
'xgds_map_server_index'),
# Map server urls
# HTML list of maps with description and links to individual maps, and a link to the kml feed
(r'^list/', getMapListPage,
{'readOnly': True},
'mapList'),
# This URL should receive a static files
(r'^data/(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR,
'show_indexes' : True,
'readOnly': True},
'xgds_map_server_static'),
# By default if you just load the app you should see the list
(r'^feed/(?P<feedname>.*)', getMapFeed,
{'readOnly': True,
'challenge': settings.SECURITY_GOOGLE_EARTH_CHALLENGE},
'xgds_map_server_feed'),
)
Tweak login required and auth settings to work with C3# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.conf.urls.defaults import *
from xgds_map_server import settings
from xgds_map_server.views import *
urlpatterns = patterns(
'',
(r'^$', getMapListPage,
{'readOnly': True},
'xgds_map_server_index'),
# Map server urls
# HTML list of maps with description and links to individual maps, and a link to the kml feed
(r'^list/', getMapListPage,
{'readOnly': True},
'mapList'),
# This URL should receive a static files
(r'^data/(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR,
'show_indexes' : True,
'readOnly': True},
'xgds_map_server_static'),
# By default if you just load the app you should see the list
(r'^feed/(?P<feedname>.*)', getMapFeed,
{'readOnly': True,
'loginRequired': False},
'xgds_map_server_feed'),
)
|
<commit_before># __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.conf.urls.defaults import *
from xgds_map_server import settings
from xgds_map_server.views import *
urlpatterns = patterns(
'',
(r'^$', getMapListPage,
{'readOnly': True},
'xgds_map_server_index'),
# Map server urls
# HTML list of maps with description and links to individual maps, and a link to the kml feed
(r'^list/', getMapListPage,
{'readOnly': True},
'mapList'),
# This URL should receive a static files
(r'^data/(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR,
'show_indexes' : True,
'readOnly': True},
'xgds_map_server_static'),
# By default if you just load the app you should see the list
(r'^feed/(?P<feedname>.*)', getMapFeed,
{'readOnly': True,
'challenge': settings.SECURITY_GOOGLE_EARTH_CHALLENGE},
'xgds_map_server_feed'),
)
<commit_msg>Tweak login required and auth settings to work with C3<commit_after># __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.conf.urls.defaults import *
from xgds_map_server import settings
from xgds_map_server.views import *
urlpatterns = patterns(
'',
(r'^$', getMapListPage,
{'readOnly': True},
'xgds_map_server_index'),
# Map server urls
# HTML list of maps with description and links to individual maps, and a link to the kml feed
(r'^list/', getMapListPage,
{'readOnly': True},
'mapList'),
# This URL should receive a static files
(r'^data/(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : settings.DATA_URL + settings.XGDS_MAP_SERVER_DATA_SUBDIR,
'show_indexes' : True,
'readOnly': True},
'xgds_map_server_static'),
# By default if you just load the app you should see the list
(r'^feed/(?P<feedname>.*)', getMapFeed,
{'readOnly': True,
'loginRequired': False},
'xgds_map_server_feed'),
)
|
b3e20fff43c3d04677f552ec5c7522a840359104
|
schematics/types/temporal.py
|
schematics/types/temporal.py
|
from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
return TimeStampType.timestamp_to_date(value)
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
|
from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType, ConversionError
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
MESSAGES = {
'negative': u'Timestamp cannot be negative.',
}
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
if value < 0:
raise ConversionError(self.messages['negative'])
return TimeStampType.timestamp_to_date(value)
except ConversionError as e:
raise e
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
|
Change TimeStampType to not accept negative values
|
Change TimeStampType to not accept negative values
This is to work around a Python bug (http://bugs.python.org/issue1777412)
|
Python
|
bsd-3-clause
|
nKey/schematics
|
from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
return TimeStampType.timestamp_to_date(value)
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
Change TimeStampType to not accept negative values
This is to work around a Python bug (http://bugs.python.org/issue1777412)
|
from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType, ConversionError
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
MESSAGES = {
'negative': u'Timestamp cannot be negative.',
}
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
if value < 0:
raise ConversionError(self.messages['negative'])
return TimeStampType.timestamp_to_date(value)
except ConversionError as e:
raise e
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
|
<commit_before>from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
return TimeStampType.timestamp_to_date(value)
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
<commit_msg>Change TimeStampType to not accept negative values
This is to work around a Python bug (http://bugs.python.org/issue1777412)<commit_after>
|
from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType, ConversionError
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
MESSAGES = {
'negative': u'Timestamp cannot be negative.',
}
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
if value < 0:
raise ConversionError(self.messages['negative'])
return TimeStampType.timestamp_to_date(value)
except ConversionError as e:
raise e
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
|
from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
return TimeStampType.timestamp_to_date(value)
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
Change TimeStampType to not accept negative values
This is to work around a Python bug (http://bugs.python.org/issue1777412)from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType, ConversionError
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
MESSAGES = {
'negative': u'Timestamp cannot be negative.',
}
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
if value < 0:
raise ConversionError(self.messages['negative'])
return TimeStampType.timestamp_to_date(value)
except ConversionError as e:
raise e
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
|
<commit_before>from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
return TimeStampType.timestamp_to_date(value)
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
<commit_msg>Change TimeStampType to not accept negative values
This is to work around a Python bug (http://bugs.python.org/issue1777412)<commit_after>from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType, ConversionError
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
MESSAGES = {
'negative': u'Timestamp cannot be negative.',
}
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
if value < 0:
raise ConversionError(self.messages['negative'])
return TimeStampType.timestamp_to_date(value)
except ConversionError as e:
raise e
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
|
02c125755a1e29f36f8bd45279327c811fadff33
|
datapipe/targets/objects.py
|
datapipe/targets/objects.py
|
from ..target import Target
import hashlib
import dill
import joblib
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
self._memory['obj'] = dill.dumps(obj).encode('base64')
def is_damaged(self):
mem = self.stored()
if mem and 'obj' in mem:
if self._obj is None:
self._memory['obj'] = mem['obj']
self._obj = dill.loads(mem['obj'].decode('base64'))
return self._obj is None
else:
return joblib.hash(self._obj) != joblib.hash(dill.loads(mem['obj'].decode('base64')))
else:
return self._obj is None
|
from ..target import Target
import hashlib
import dill
import joblib
import binascii
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
self._memory['obj'] = binascii.hexlify(dill.dumps(obj))
def is_damaged(self):
mem = self.stored()
if mem and 'obj' in mem:
if self._obj is None:
self._memory['obj'] = mem['obj']
self._obj = dill.loads(mem['obj'].decode('base64'))
return self._obj is None
else:
return joblib.hash(self._obj) != joblib.hash(dill.loads(binascii.unhexlify(mem['obj'])))
else:
return self._obj is None
|
Fix error on Python 3
|
Fix error on Python 3
|
Python
|
mit
|
ibab/datapipe
|
from ..target import Target
import hashlib
import dill
import joblib
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
self._memory['obj'] = dill.dumps(obj).encode('base64')
def is_damaged(self):
mem = self.stored()
if mem and 'obj' in mem:
if self._obj is None:
self._memory['obj'] = mem['obj']
self._obj = dill.loads(mem['obj'].decode('base64'))
return self._obj is None
else:
return joblib.hash(self._obj) != joblib.hash(dill.loads(mem['obj'].decode('base64')))
else:
return self._obj is None
Fix error on Python 3
|
from ..target import Target
import hashlib
import dill
import joblib
import binascii
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
self._memory['obj'] = binascii.hexlify(dill.dumps(obj))
def is_damaged(self):
mem = self.stored()
if mem and 'obj' in mem:
if self._obj is None:
self._memory['obj'] = mem['obj']
self._obj = dill.loads(mem['obj'].decode('base64'))
return self._obj is None
else:
return joblib.hash(self._obj) != joblib.hash(dill.loads(binascii.unhexlify(mem['obj'])))
else:
return self._obj is None
|
<commit_before>from ..target import Target
import hashlib
import dill
import joblib
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
self._memory['obj'] = dill.dumps(obj).encode('base64')
def is_damaged(self):
mem = self.stored()
if mem and 'obj' in mem:
if self._obj is None:
self._memory['obj'] = mem['obj']
self._obj = dill.loads(mem['obj'].decode('base64'))
return self._obj is None
else:
return joblib.hash(self._obj) != joblib.hash(dill.loads(mem['obj'].decode('base64')))
else:
return self._obj is None
<commit_msg>Fix error on Python 3<commit_after>
|
from ..target import Target
import hashlib
import dill
import joblib
import binascii
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
self._memory['obj'] = binascii.hexlify(dill.dumps(obj))
def is_damaged(self):
mem = self.stored()
if mem and 'obj' in mem:
if self._obj is None:
self._memory['obj'] = mem['obj']
self._obj = dill.loads(mem['obj'].decode('base64'))
return self._obj is None
else:
return joblib.hash(self._obj) != joblib.hash(dill.loads(binascii.unhexlify(mem['obj'])))
else:
return self._obj is None
|
from ..target import Target
import hashlib
import dill
import joblib
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
self._memory['obj'] = dill.dumps(obj).encode('base64')
def is_damaged(self):
mem = self.stored()
if mem and 'obj' in mem:
if self._obj is None:
self._memory['obj'] = mem['obj']
self._obj = dill.loads(mem['obj'].decode('base64'))
return self._obj is None
else:
return joblib.hash(self._obj) != joblib.hash(dill.loads(mem['obj'].decode('base64')))
else:
return self._obj is None
Fix error on Python 3from ..target import Target
import hashlib
import dill
import joblib
import binascii
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
self._memory['obj'] = binascii.hexlify(dill.dumps(obj))
def is_damaged(self):
mem = self.stored()
if mem and 'obj' in mem:
if self._obj is None:
self._memory['obj'] = mem['obj']
self._obj = dill.loads(mem['obj'].decode('base64'))
return self._obj is None
else:
return joblib.hash(self._obj) != joblib.hash(dill.loads(binascii.unhexlify(mem['obj'])))
else:
return self._obj is None
|
<commit_before>from ..target import Target
import hashlib
import dill
import joblib
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
self._memory['obj'] = dill.dumps(obj).encode('base64')
def is_damaged(self):
mem = self.stored()
if mem and 'obj' in mem:
if self._obj is None:
self._memory['obj'] = mem['obj']
self._obj = dill.loads(mem['obj'].decode('base64'))
return self._obj is None
else:
return joblib.hash(self._obj) != joblib.hash(dill.loads(mem['obj'].decode('base64')))
else:
return self._obj is None
<commit_msg>Fix error on Python 3<commit_after>from ..target import Target
import hashlib
import dill
import joblib
import binascii
class PyTarget(Target):
def __init__(self, name, obj=None):
self._name = name
self._obj = obj
super(PyTarget, self).__init__()
if not obj is None:
self.set(obj)
def identifier(self):
return self._name
def get(self):
return self._obj
def set(self, obj):
self._obj = obj
self._memory['obj'] = binascii.hexlify(dill.dumps(obj))
def is_damaged(self):
mem = self.stored()
if mem and 'obj' in mem:
if self._obj is None:
self._memory['obj'] = mem['obj']
self._obj = dill.loads(mem['obj'].decode('base64'))
return self._obj is None
else:
return joblib.hash(self._obj) != joblib.hash(dill.loads(binascii.unhexlify(mem['obj'])))
else:
return self._obj is None
|
9126a1b65e907c3c23fccf85295042a9bd4c36c2
|
reobject/models/fields.py
|
reobject/models/fields.py
|
from attr import ib, Factory
def Field(*args, **kwargs):
default = kwargs.get('default')
if callable(default):
kwargs.pop('default')
return ib(*args, default=Factory(default), **kwargs)
else:
return ib(*args, **kwargs)
|
import attr
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
def ManyToManyField(cls, *args, **kwargs):
metadata = {
'related': {
'target': cls,
'type': 'ManyToMany',
}
}
return attr.ib(*args, **kwargs, metadata=metadata)
|
Introduce dummy ManyToManyField with attrs metadata
|
Introduce dummy ManyToManyField with attrs metadata
|
Python
|
apache-2.0
|
onyb/reobject,onyb/reobject
|
from attr import ib, Factory
def Field(*args, **kwargs):
default = kwargs.get('default')
if callable(default):
kwargs.pop('default')
return ib(*args, default=Factory(default), **kwargs)
else:
return ib(*args, **kwargs)
Introduce dummy ManyToManyField with attrs metadata
|
import attr
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
def ManyToManyField(cls, *args, **kwargs):
metadata = {
'related': {
'target': cls,
'type': 'ManyToMany',
}
}
return attr.ib(*args, **kwargs, metadata=metadata)
|
<commit_before>from attr import ib, Factory
def Field(*args, **kwargs):
default = kwargs.get('default')
if callable(default):
kwargs.pop('default')
return ib(*args, default=Factory(default), **kwargs)
else:
return ib(*args, **kwargs)
<commit_msg>Introduce dummy ManyToManyField with attrs metadata<commit_after>
|
import attr
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
def ManyToManyField(cls, *args, **kwargs):
metadata = {
'related': {
'target': cls,
'type': 'ManyToMany',
}
}
return attr.ib(*args, **kwargs, metadata=metadata)
|
from attr import ib, Factory
def Field(*args, **kwargs):
default = kwargs.get('default')
if callable(default):
kwargs.pop('default')
return ib(*args, default=Factory(default), **kwargs)
else:
return ib(*args, **kwargs)
Introduce dummy ManyToManyField with attrs metadataimport attr
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
def ManyToManyField(cls, *args, **kwargs):
metadata = {
'related': {
'target': cls,
'type': 'ManyToMany',
}
}
return attr.ib(*args, **kwargs, metadata=metadata)
|
<commit_before>from attr import ib, Factory
def Field(*args, **kwargs):
default = kwargs.get('default')
if callable(default):
kwargs.pop('default')
return ib(*args, default=Factory(default), **kwargs)
else:
return ib(*args, **kwargs)
<commit_msg>Introduce dummy ManyToManyField with attrs metadata<commit_after>import attr
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
def ManyToManyField(cls, *args, **kwargs):
metadata = {
'related': {
'target': cls,
'type': 'ManyToMany',
}
}
return attr.ib(*args, **kwargs, metadata=metadata)
|
3ae33e8d637b6c5230d124430e6f53cb183aee8e
|
src/sentry/plugins/sentry_urls/models.py
|
src/sentry/plugins/sentry_urls/models.py
|
"""
sentry.plugins.sentry_urls.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sentry
from django.utils.translation import ugettext_lazy as _
from sentry.plugins import register
from sentry.plugins.bases.tag import TagPlugin
class UrlsPlugin(TagPlugin):
"""
Automatically adds the 'url' tag from events containing interface data
from ``sentry.interfaes.Http``.
"""
slug = 'urls'
title = _('Auto Tag: URLs')
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
tag = 'url'
tag_label = _('URL')
project_default_enabled = True
def get_tag_values(self, event):
http = event.interfaces.get('sentry.interfaces.Http')
if not http:
return []
if not http.url:
return []
return [http.url]
register(UrlsPlugin)
|
"""
sentry.plugins.sentry_urls.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sentry
from django.utils.translation import ugettext_lazy as _
from sentry.plugins import register
from sentry.plugins.bases.tag import TagPlugin
class UrlsPlugin(TagPlugin):
"""
Automatically adds the 'url' tag from events containing interface data
from ``sentry.interfaces.Http``.
"""
slug = 'urls'
title = _('Auto Tag: URLs')
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
tag = 'url'
tag_label = _('URL')
project_default_enabled = True
def get_tag_values(self, event):
http = event.interfaces.get('sentry.interfaces.Http')
if not http:
return []
if not http.url:
return []
return [http.url]
register(UrlsPlugin)
|
Fix typo in class name.
|
Fix typo in class name.
|
Python
|
bsd-3-clause
|
wujuguang/sentry,BayanGroup/sentry,jean/sentry,fuziontech/sentry,BuildingLink/sentry,songyi199111/sentry,Natim/sentry,mvaled/sentry,mvaled/sentry,looker/sentry,rdio/sentry,drcapulet/sentry,pauloschilling/sentry,gencer/sentry,argonemyth/sentry,looker/sentry,Natim/sentry,jean/sentry,ewdurbin/sentry,jokey2k/sentry,alexm92/sentry,wong2/sentry,mitsuhiko/sentry,TedaLIEz/sentry,llonchj/sentry,BuildingLink/sentry,zenefits/sentry,ifduyue/sentry,kevinastone/sentry,rdio/sentry,Kryz/sentry,korealerts1/sentry,kevinastone/sentry,SilentCircle/sentry,zenefits/sentry,ngonzalvez/sentry,zenefits/sentry,Kryz/sentry,nicholasserra/sentry,looker/sentry,daevaorn/sentry,felixbuenemann/sentry,Natim/sentry,camilonova/sentry,songyi199111/sentry,zenefits/sentry,drcapulet/sentry,beni55/sentry,hongliang5623/sentry,JackDanger/sentry,vperron/sentry,JackDanger/sentry,fuziontech/sentry,JTCunning/sentry,fotinakis/sentry,daevaorn/sentry,gencer/sentry,boneyao/sentry,beeftornado/sentry,argonemyth/sentry,gencer/sentry,jean/sentry,mvaled/sentry,beni55/sentry,rdio/sentry,beni55/sentry,daevaorn/sentry,hongliang5623/sentry,mvaled/sentry,JTCunning/sentry,wujuguang/sentry,kevinlondon/sentry,zenefits/sentry,drcapulet/sentry,llonchj/sentry,kevinlondon/sentry,Kryz/sentry,alexm92/sentry,felixbuenemann/sentry,rdio/sentry,SilentCircle/sentry,fotinakis/sentry,mvaled/sentry,vperron/sentry,ifduyue/sentry,gencer/sentry,fotinakis/sentry,NickPresta/sentry,JamesMura/sentry,argonemyth/sentry,daevaorn/sentry,1tush/sentry,camilonova/sentry,ifduyue/sentry,BuildingLink/sentry,wong2/sentry,1tush/sentry,gg7/sentry,ewdurbin/sentry,looker/sentry,wujuguang/sentry,kevinlondon/sentry,jean/sentry,jokey2k/sentry,korealerts1/sentry,JamesMura/sentry,gg7/sentry,jokey2k/sentry,imankulov/sentry,JackDanger/sentry,camilonova/sentry,JamesMura/sentry,boneyao/sentry,JamesMura/sentry,ngonzalvez/sentry,boneyao/sentry,alexm92/sentry,ifduyue/sentry,BayanGroup/sentry,fuziontech/sentry,ifduyue/sentry,looker/sentry,nicholasserra/sentry,korealerts1/sentry,gencer/sentry,felixbuenemann/sentry,vperron/sentry,imankulov/sentry,JTCunning/sentry,TedaLIEz/sentry,kevinastone/sentry,1tush/sentry,gg7/sentry,NickPresta/sentry,wong2/sentry,hongliang5623/sentry,NickPresta/sentry,mitsuhiko/sentry,TedaLIEz/sentry,beeftornado/sentry,songyi199111/sentry,beeftornado/sentry,nicholasserra/sentry,fotinakis/sentry,pauloschilling/sentry,imankulov/sentry,llonchj/sentry,ewdurbin/sentry,jean/sentry,ngonzalvez/sentry,mvaled/sentry,BayanGroup/sentry,SilentCircle/sentry,JamesMura/sentry,BuildingLink/sentry,NickPresta/sentry,BuildingLink/sentry,SilentCircle/sentry,pauloschilling/sentry
|
"""
sentry.plugins.sentry_urls.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sentry
from django.utils.translation import ugettext_lazy as _
from sentry.plugins import register
from sentry.plugins.bases.tag import TagPlugin
class UrlsPlugin(TagPlugin):
"""
Automatically adds the 'url' tag from events containing interface data
from ``sentry.interfaes.Http``.
"""
slug = 'urls'
title = _('Auto Tag: URLs')
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
tag = 'url'
tag_label = _('URL')
project_default_enabled = True
def get_tag_values(self, event):
http = event.interfaces.get('sentry.interfaces.Http')
if not http:
return []
if not http.url:
return []
return [http.url]
register(UrlsPlugin)
Fix typo in class name.
|
"""
sentry.plugins.sentry_urls.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sentry
from django.utils.translation import ugettext_lazy as _
from sentry.plugins import register
from sentry.plugins.bases.tag import TagPlugin
class UrlsPlugin(TagPlugin):
"""
Automatically adds the 'url' tag from events containing interface data
from ``sentry.interfaces.Http``.
"""
slug = 'urls'
title = _('Auto Tag: URLs')
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
tag = 'url'
tag_label = _('URL')
project_default_enabled = True
def get_tag_values(self, event):
http = event.interfaces.get('sentry.interfaces.Http')
if not http:
return []
if not http.url:
return []
return [http.url]
register(UrlsPlugin)
|
<commit_before>"""
sentry.plugins.sentry_urls.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sentry
from django.utils.translation import ugettext_lazy as _
from sentry.plugins import register
from sentry.plugins.bases.tag import TagPlugin
class UrlsPlugin(TagPlugin):
"""
Automatically adds the 'url' tag from events containing interface data
from ``sentry.interfaes.Http``.
"""
slug = 'urls'
title = _('Auto Tag: URLs')
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
tag = 'url'
tag_label = _('URL')
project_default_enabled = True
def get_tag_values(self, event):
http = event.interfaces.get('sentry.interfaces.Http')
if not http:
return []
if not http.url:
return []
return [http.url]
register(UrlsPlugin)
<commit_msg>Fix typo in class name.<commit_after>
|
"""
sentry.plugins.sentry_urls.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sentry
from django.utils.translation import ugettext_lazy as _
from sentry.plugins import register
from sentry.plugins.bases.tag import TagPlugin
class UrlsPlugin(TagPlugin):
"""
Automatically adds the 'url' tag from events containing interface data
from ``sentry.interfaces.Http``.
"""
slug = 'urls'
title = _('Auto Tag: URLs')
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
tag = 'url'
tag_label = _('URL')
project_default_enabled = True
def get_tag_values(self, event):
http = event.interfaces.get('sentry.interfaces.Http')
if not http:
return []
if not http.url:
return []
return [http.url]
register(UrlsPlugin)
|
"""
sentry.plugins.sentry_urls.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sentry
from django.utils.translation import ugettext_lazy as _
from sentry.plugins import register
from sentry.plugins.bases.tag import TagPlugin
class UrlsPlugin(TagPlugin):
"""
Automatically adds the 'url' tag from events containing interface data
from ``sentry.interfaes.Http``.
"""
slug = 'urls'
title = _('Auto Tag: URLs')
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
tag = 'url'
tag_label = _('URL')
project_default_enabled = True
def get_tag_values(self, event):
http = event.interfaces.get('sentry.interfaces.Http')
if not http:
return []
if not http.url:
return []
return [http.url]
register(UrlsPlugin)
Fix typo in class name."""
sentry.plugins.sentry_urls.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sentry
from django.utils.translation import ugettext_lazy as _
from sentry.plugins import register
from sentry.plugins.bases.tag import TagPlugin
class UrlsPlugin(TagPlugin):
"""
Automatically adds the 'url' tag from events containing interface data
from ``sentry.interfaces.Http``.
"""
slug = 'urls'
title = _('Auto Tag: URLs')
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
tag = 'url'
tag_label = _('URL')
project_default_enabled = True
def get_tag_values(self, event):
http = event.interfaces.get('sentry.interfaces.Http')
if not http:
return []
if not http.url:
return []
return [http.url]
register(UrlsPlugin)
|
<commit_before>"""
sentry.plugins.sentry_urls.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sentry
from django.utils.translation import ugettext_lazy as _
from sentry.plugins import register
from sentry.plugins.bases.tag import TagPlugin
class UrlsPlugin(TagPlugin):
"""
Automatically adds the 'url' tag from events containing interface data
from ``sentry.interfaes.Http``.
"""
slug = 'urls'
title = _('Auto Tag: URLs')
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
tag = 'url'
tag_label = _('URL')
project_default_enabled = True
def get_tag_values(self, event):
http = event.interfaces.get('sentry.interfaces.Http')
if not http:
return []
if not http.url:
return []
return [http.url]
register(UrlsPlugin)
<commit_msg>Fix typo in class name.<commit_after>"""
sentry.plugins.sentry_urls.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sentry
from django.utils.translation import ugettext_lazy as _
from sentry.plugins import register
from sentry.plugins.bases.tag import TagPlugin
class UrlsPlugin(TagPlugin):
"""
Automatically adds the 'url' tag from events containing interface data
from ``sentry.interfaces.Http``.
"""
slug = 'urls'
title = _('Auto Tag: URLs')
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
tag = 'url'
tag_label = _('URL')
project_default_enabled = True
def get_tag_values(self, event):
http = event.interfaces.get('sentry.interfaces.Http')
if not http:
return []
if not http.url:
return []
return [http.url]
register(UrlsPlugin)
|
62f2d7b4fe2e39863067c6e2f56f385117d5f66a
|
helusers/jwt.py
|
helusers/jwt.py
|
from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = super().authenticate_credentials(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return get_or_create_user(payload)
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
|
from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = get_or_create_user(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return user
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
|
Fix JWTAuthentication active user check
|
Fix JWTAuthentication active user check
|
Python
|
bsd-2-clause
|
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
|
from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = super().authenticate_credentials(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return get_or_create_user(payload)
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
Fix JWTAuthentication active user check
|
from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = get_or_create_user(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return user
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
|
<commit_before>from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = super().authenticate_credentials(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return get_or_create_user(payload)
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
<commit_msg>Fix JWTAuthentication active user check<commit_after>
|
from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = get_or_create_user(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return user
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
|
from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = super().authenticate_credentials(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return get_or_create_user(payload)
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
Fix JWTAuthentication active user checkfrom django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = get_or_create_user(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return user
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
|
<commit_before>from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = super().authenticate_credentials(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return get_or_create_user(payload)
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
<commit_msg>Fix JWTAuthentication active user check<commit_after>from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = api_settings.defaults
defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = (
__name__ + '.get_user_id_from_payload_handler')
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return
from allauth.socialaccount.models import SocialApp
try:
app = SocialApp.objects.get(provider='helsinki')
except SocialApp.DoesNotExist:
return
defaults['JWT_SECRET_KEY'] = app.secret
defaults['JWT_AUDIENCE'] = app.client_id
# Disable automatic settings patching for now because it breaks Travis.
# patch_jwt_settings()
class JWTAuthentication(JSONWebTokenAuthentication):
def authenticate_credentials(self, payload):
user = get_or_create_user(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return user
def get_user_id_from_payload_handler(payload):
return payload.get('sub')
|
5a565f457b5763a2d24ebfa60d842996276ef70c
|
src/smsfly/versiontools.py
|
src/smsfly/versiontools.py
|
"""Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date',
):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
root=root,
relative_to=relative_to,
local_scheme=local_scheme,
)
except LookupError:
return 'unknown'
def cut_local_version_on_upload(version):
"""Return empty local version if uploading to PyPI."""
is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true'
if is_pypi_upload:
return ''
import setuptools_scm.version # only available during setup time
return setuptools_scm.version.get_local_node_and_date(version)
def get_self_version():
"""Calculate the version of the dist itself."""
return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
|
"""Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date'
):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
root=root,
relative_to=relative_to,
local_scheme=local_scheme,
)
except LookupError:
return 'unknown'
def cut_local_version_on_upload(version):
"""Return empty local version if uploading to PyPI."""
is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true'
if is_pypi_upload:
return ''
import setuptools_scm.version # only available during setup time
return setuptools_scm.version.get_local_node_and_date(version)
def get_self_version():
"""Calculate the version of the dist itself."""
return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
|
Drop trailing arg list comma to support Python 3.5
|
Drop trailing arg list comma to support Python 3.5
|
Python
|
mit
|
wk-tech/python-smsfly
|
"""Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date',
):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
root=root,
relative_to=relative_to,
local_scheme=local_scheme,
)
except LookupError:
return 'unknown'
def cut_local_version_on_upload(version):
"""Return empty local version if uploading to PyPI."""
is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true'
if is_pypi_upload:
return ''
import setuptools_scm.version # only available during setup time
return setuptools_scm.version.get_local_node_and_date(version)
def get_self_version():
"""Calculate the version of the dist itself."""
return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
Drop trailing arg list comma to support Python 3.5
|
"""Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date'
):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
root=root,
relative_to=relative_to,
local_scheme=local_scheme,
)
except LookupError:
return 'unknown'
def cut_local_version_on_upload(version):
"""Return empty local version if uploading to PyPI."""
is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true'
if is_pypi_upload:
return ''
import setuptools_scm.version # only available during setup time
return setuptools_scm.version.get_local_node_and_date(version)
def get_self_version():
"""Calculate the version of the dist itself."""
return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
|
<commit_before>"""Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date',
):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
root=root,
relative_to=relative_to,
local_scheme=local_scheme,
)
except LookupError:
return 'unknown'
def cut_local_version_on_upload(version):
"""Return empty local version if uploading to PyPI."""
is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true'
if is_pypi_upload:
return ''
import setuptools_scm.version # only available during setup time
return setuptools_scm.version.get_local_node_and_date(version)
def get_self_version():
"""Calculate the version of the dist itself."""
return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
<commit_msg>Drop trailing arg list comma to support Python 3.5<commit_after>
|
"""Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date'
):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
root=root,
relative_to=relative_to,
local_scheme=local_scheme,
)
except LookupError:
return 'unknown'
def cut_local_version_on_upload(version):
"""Return empty local version if uploading to PyPI."""
is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true'
if is_pypi_upload:
return ''
import setuptools_scm.version # only available during setup time
return setuptools_scm.version.get_local_node_and_date(version)
def get_self_version():
"""Calculate the version of the dist itself."""
return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
|
"""Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date',
):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
root=root,
relative_to=relative_to,
local_scheme=local_scheme,
)
except LookupError:
return 'unknown'
def cut_local_version_on_upload(version):
"""Return empty local version if uploading to PyPI."""
is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true'
if is_pypi_upload:
return ''
import setuptools_scm.version # only available during setup time
return setuptools_scm.version.get_local_node_and_date(version)
def get_self_version():
"""Calculate the version of the dist itself."""
return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
Drop trailing arg list comma to support Python 3.5"""Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date'
):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
root=root,
relative_to=relative_to,
local_scheme=local_scheme,
)
except LookupError:
return 'unknown'
def cut_local_version_on_upload(version):
"""Return empty local version if uploading to PyPI."""
is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true'
if is_pypi_upload:
return ''
import setuptools_scm.version # only available during setup time
return setuptools_scm.version.get_local_node_and_date(version)
def get_self_version():
"""Calculate the version of the dist itself."""
return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
|
<commit_before>"""Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date',
):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
root=root,
relative_to=relative_to,
local_scheme=local_scheme,
)
except LookupError:
return 'unknown'
def cut_local_version_on_upload(version):
"""Return empty local version if uploading to PyPI."""
is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true'
if is_pypi_upload:
return ''
import setuptools_scm.version # only available during setup time
return setuptools_scm.version.get_local_node_and_date(version)
def get_self_version():
"""Calculate the version of the dist itself."""
return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
<commit_msg>Drop trailing arg list comma to support Python 3.5<commit_after>"""Version tools set."""
import os
from setuptools_scm import get_version
def get_version_from_scm_tag(
*,
root='.',
relative_to=None,
local_scheme='node-and-date'
):
"""Retrieve the version from SCM tag in Git or Hg."""
try:
return get_version(
root=root,
relative_to=relative_to,
local_scheme=local_scheme,
)
except LookupError:
return 'unknown'
def cut_local_version_on_upload(version):
"""Return empty local version if uploading to PyPI."""
is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true'
if is_pypi_upload:
return ''
import setuptools_scm.version # only available during setup time
return setuptools_scm.version.get_local_node_and_date(version)
def get_self_version():
"""Calculate the version of the dist itself."""
return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
|
893b06261bb97407736ef7572d800bd5843f24f6
|
robber/matchers/called.py
|
robber/matchers/called.py
|
from robber import expect
from robber.matchers.base import Base
class Called(Base):
"""
expect(function).to.be.called()
"""
def matches(self):
try:
return self.actual.called
except AttributeError:
raise TypeError('{function} is not a mock'.format(function=self.actual))
def failure_message(self):
return 'Expected {function} to be called'.format(function=self.actual)
expect.register('called', Called)
expect.register('__called__', Called)
|
from robber import expect
from robber.matchers.base import Base
class Called(Base):
"""
expect(function).to.be.called()
"""
def matches(self):
try:
return self.actual.called
except AttributeError:
raise TypeError('{actual} is not a mock'.format(actual=self.actual))
def failure_message(self):
return 'Expected {actual} to be called'.format(actual=self.actual)
expect.register('called', Called)
expect.register('__called__', Called)
|
Use `actual` in string format
|
[f] Use `actual` in string format
|
Python
|
mit
|
vesln/robber.py
|
from robber import expect
from robber.matchers.base import Base
class Called(Base):
"""
expect(function).to.be.called()
"""
def matches(self):
try:
return self.actual.called
except AttributeError:
raise TypeError('{function} is not a mock'.format(function=self.actual))
def failure_message(self):
return 'Expected {function} to be called'.format(function=self.actual)
expect.register('called', Called)
expect.register('__called__', Called)
[f] Use `actual` in string format
|
from robber import expect
from robber.matchers.base import Base
class Called(Base):
"""
expect(function).to.be.called()
"""
def matches(self):
try:
return self.actual.called
except AttributeError:
raise TypeError('{actual} is not a mock'.format(actual=self.actual))
def failure_message(self):
return 'Expected {actual} to be called'.format(actual=self.actual)
expect.register('called', Called)
expect.register('__called__', Called)
|
<commit_before>from robber import expect
from robber.matchers.base import Base
class Called(Base):
"""
expect(function).to.be.called()
"""
def matches(self):
try:
return self.actual.called
except AttributeError:
raise TypeError('{function} is not a mock'.format(function=self.actual))
def failure_message(self):
return 'Expected {function} to be called'.format(function=self.actual)
expect.register('called', Called)
expect.register('__called__', Called)
<commit_msg>[f] Use `actual` in string format<commit_after>
|
from robber import expect
from robber.matchers.base import Base
class Called(Base):
"""
expect(function).to.be.called()
"""
def matches(self):
try:
return self.actual.called
except AttributeError:
raise TypeError('{actual} is not a mock'.format(actual=self.actual))
def failure_message(self):
return 'Expected {actual} to be called'.format(actual=self.actual)
expect.register('called', Called)
expect.register('__called__', Called)
|
from robber import expect
from robber.matchers.base import Base
class Called(Base):
"""
expect(function).to.be.called()
"""
def matches(self):
try:
return self.actual.called
except AttributeError:
raise TypeError('{function} is not a mock'.format(function=self.actual))
def failure_message(self):
return 'Expected {function} to be called'.format(function=self.actual)
expect.register('called', Called)
expect.register('__called__', Called)
[f] Use `actual` in string formatfrom robber import expect
from robber.matchers.base import Base
class Called(Base):
"""
expect(function).to.be.called()
"""
def matches(self):
try:
return self.actual.called
except AttributeError:
raise TypeError('{actual} is not a mock'.format(actual=self.actual))
def failure_message(self):
return 'Expected {actual} to be called'.format(actual=self.actual)
expect.register('called', Called)
expect.register('__called__', Called)
|
<commit_before>from robber import expect
from robber.matchers.base import Base
class Called(Base):
"""
expect(function).to.be.called()
"""
def matches(self):
try:
return self.actual.called
except AttributeError:
raise TypeError('{function} is not a mock'.format(function=self.actual))
def failure_message(self):
return 'Expected {function} to be called'.format(function=self.actual)
expect.register('called', Called)
expect.register('__called__', Called)
<commit_msg>[f] Use `actual` in string format<commit_after>from robber import expect
from robber.matchers.base import Base
class Called(Base):
"""
expect(function).to.be.called()
"""
def matches(self):
try:
return self.actual.called
except AttributeError:
raise TypeError('{actual} is not a mock'.format(actual=self.actual))
def failure_message(self):
return 'Expected {actual} to be called'.format(actual=self.actual)
expect.register('called', Called)
expect.register('__called__', Called)
|
0f6f4857eb7cd6675313325714f080f181c08c76
|
tests/users.py
|
tests/users.py
|
"""
A static dictionary with SAML testusers that can be used as response.
"""
USERS = {
"testuser1": {
"sn": ["Testsson 1"],
"givenName": ["Test 1"],
"eduPersonAffiliation": ["student"],
"eduPersonScopedAffiliation": ["student@example.com"],
"eduPersonPrincipalName": ["test@example.com"],
"uid": ["testuser1"],
"eduPersonTargetedID": ["one!for!all"],
"c": ["SE"],
"o": ["Example Co."],
"ou": ["IT"],
"initials": ["P"],
"schacHomeOrganization": ["example.com"],
"email": ["test@example.com"],
"displayName": ["Test Testsson"],
"labeledURL": ["http://www.example.com/haho My homepage"],
"norEduPersonNIN": ["SE199012315555"],
}
}
|
"""
A static dictionary with SAML testusers that can be used as response.
"""
USERS = {
"testuser1": {
"sn": ["Testsson 1"],
"givenName": ["Test 1"],
"eduPersonAffiliation": ["student"],
"eduPersonScopedAffiliation": ["student@example.com"],
"eduPersonPrincipalName": ["test@example.com"],
"uid": ["testuser1"],
"eduPersonTargetedID": ["one!for!all"],
"c": ["SE"],
"o": ["Example Co."],
"ou": ["IT"],
"initials": ["P"],
"schacHomeOrganization": ["example.com"],
"email": ["test@example.com"],
"displayName": ["Test Testsson"],
"norEduPersonNIN": ["SE199012315555"]
}
}
|
Remove non-standard attribute in test user.
|
Remove non-standard attribute in test user.
|
Python
|
apache-2.0
|
irtnog/SATOSA,SUNET/SATOSA,its-dirg/SATOSA,irtnog/SATOSA,SUNET/SATOSA
|
"""
A static dictionary with SAML testusers that can be used as response.
"""
USERS = {
"testuser1": {
"sn": ["Testsson 1"],
"givenName": ["Test 1"],
"eduPersonAffiliation": ["student"],
"eduPersonScopedAffiliation": ["student@example.com"],
"eduPersonPrincipalName": ["test@example.com"],
"uid": ["testuser1"],
"eduPersonTargetedID": ["one!for!all"],
"c": ["SE"],
"o": ["Example Co."],
"ou": ["IT"],
"initials": ["P"],
"schacHomeOrganization": ["example.com"],
"email": ["test@example.com"],
"displayName": ["Test Testsson"],
"labeledURL": ["http://www.example.com/haho My homepage"],
"norEduPersonNIN": ["SE199012315555"],
}
}
Remove non-standard attribute in test user.
|
"""
A static dictionary with SAML testusers that can be used as response.
"""
USERS = {
"testuser1": {
"sn": ["Testsson 1"],
"givenName": ["Test 1"],
"eduPersonAffiliation": ["student"],
"eduPersonScopedAffiliation": ["student@example.com"],
"eduPersonPrincipalName": ["test@example.com"],
"uid": ["testuser1"],
"eduPersonTargetedID": ["one!for!all"],
"c": ["SE"],
"o": ["Example Co."],
"ou": ["IT"],
"initials": ["P"],
"schacHomeOrganization": ["example.com"],
"email": ["test@example.com"],
"displayName": ["Test Testsson"],
"norEduPersonNIN": ["SE199012315555"]
}
}
|
<commit_before>"""
A static dictionary with SAML testusers that can be used as response.
"""
USERS = {
"testuser1": {
"sn": ["Testsson 1"],
"givenName": ["Test 1"],
"eduPersonAffiliation": ["student"],
"eduPersonScopedAffiliation": ["student@example.com"],
"eduPersonPrincipalName": ["test@example.com"],
"uid": ["testuser1"],
"eduPersonTargetedID": ["one!for!all"],
"c": ["SE"],
"o": ["Example Co."],
"ou": ["IT"],
"initials": ["P"],
"schacHomeOrganization": ["example.com"],
"email": ["test@example.com"],
"displayName": ["Test Testsson"],
"labeledURL": ["http://www.example.com/haho My homepage"],
"norEduPersonNIN": ["SE199012315555"],
}
}
<commit_msg>Remove non-standard attribute in test user.<commit_after>
|
"""
A static dictionary with SAML testusers that can be used as response.
"""
USERS = {
"testuser1": {
"sn": ["Testsson 1"],
"givenName": ["Test 1"],
"eduPersonAffiliation": ["student"],
"eduPersonScopedAffiliation": ["student@example.com"],
"eduPersonPrincipalName": ["test@example.com"],
"uid": ["testuser1"],
"eduPersonTargetedID": ["one!for!all"],
"c": ["SE"],
"o": ["Example Co."],
"ou": ["IT"],
"initials": ["P"],
"schacHomeOrganization": ["example.com"],
"email": ["test@example.com"],
"displayName": ["Test Testsson"],
"norEduPersonNIN": ["SE199012315555"]
}
}
|
"""
A static dictionary with SAML testusers that can be used as response.
"""
USERS = {
"testuser1": {
"sn": ["Testsson 1"],
"givenName": ["Test 1"],
"eduPersonAffiliation": ["student"],
"eduPersonScopedAffiliation": ["student@example.com"],
"eduPersonPrincipalName": ["test@example.com"],
"uid": ["testuser1"],
"eduPersonTargetedID": ["one!for!all"],
"c": ["SE"],
"o": ["Example Co."],
"ou": ["IT"],
"initials": ["P"],
"schacHomeOrganization": ["example.com"],
"email": ["test@example.com"],
"displayName": ["Test Testsson"],
"labeledURL": ["http://www.example.com/haho My homepage"],
"norEduPersonNIN": ["SE199012315555"],
}
}
Remove non-standard attribute in test user."""
A static dictionary with SAML testusers that can be used as response.
"""
USERS = {
"testuser1": {
"sn": ["Testsson 1"],
"givenName": ["Test 1"],
"eduPersonAffiliation": ["student"],
"eduPersonScopedAffiliation": ["student@example.com"],
"eduPersonPrincipalName": ["test@example.com"],
"uid": ["testuser1"],
"eduPersonTargetedID": ["one!for!all"],
"c": ["SE"],
"o": ["Example Co."],
"ou": ["IT"],
"initials": ["P"],
"schacHomeOrganization": ["example.com"],
"email": ["test@example.com"],
"displayName": ["Test Testsson"],
"norEduPersonNIN": ["SE199012315555"]
}
}
|
<commit_before>"""
A static dictionary with SAML testusers that can be used as response.
"""
USERS = {
"testuser1": {
"sn": ["Testsson 1"],
"givenName": ["Test 1"],
"eduPersonAffiliation": ["student"],
"eduPersonScopedAffiliation": ["student@example.com"],
"eduPersonPrincipalName": ["test@example.com"],
"uid": ["testuser1"],
"eduPersonTargetedID": ["one!for!all"],
"c": ["SE"],
"o": ["Example Co."],
"ou": ["IT"],
"initials": ["P"],
"schacHomeOrganization": ["example.com"],
"email": ["test@example.com"],
"displayName": ["Test Testsson"],
"labeledURL": ["http://www.example.com/haho My homepage"],
"norEduPersonNIN": ["SE199012315555"],
}
}
<commit_msg>Remove non-standard attribute in test user.<commit_after>"""
A static dictionary with SAML testusers that can be used as response.
"""
USERS = {
"testuser1": {
"sn": ["Testsson 1"],
"givenName": ["Test 1"],
"eduPersonAffiliation": ["student"],
"eduPersonScopedAffiliation": ["student@example.com"],
"eduPersonPrincipalName": ["test@example.com"],
"uid": ["testuser1"],
"eduPersonTargetedID": ["one!for!all"],
"c": ["SE"],
"o": ["Example Co."],
"ou": ["IT"],
"initials": ["P"],
"schacHomeOrganization": ["example.com"],
"email": ["test@example.com"],
"displayName": ["Test Testsson"],
"norEduPersonNIN": ["SE199012315555"]
}
}
|
4b2fbad0d2cf4b9efc3c3f89e47c0ac2a83ad08d
|
tests/utils.py
|
tests/utils.py
|
from os import environ
JOB_ID = environ.get("TRAVIS_JOB_ID", "loc")
ENTITY_MAX_LEN = 36
BASE_NAME_MAX_LEN = ENTITY_MAX_LEN - 3 - 3 - 2
counters = {}
def generate_entity_id(base_name="entity"):
# Keep only the first characters
base_name = base_name[:BASE_NAME_MAX_LEN]
counter = counters[base_name] if base_name in counters else 0
counter += 1
counters[base_name] = counter
return "{}_{:03}_{}".format(base_name, counter, JOB_ID[-3:])
|
from os import environ
ENTITY_MAX_LEN = 36
BASE_NAME_MAX_LEN = ENTITY_MAX_LEN - 3 - 3 - 2
counters = {}
def generate_entity_id(base_name="entity"):
# Keep only the first characters
base_name = base_name[:BASE_NAME_MAX_LEN]
counter = counters[base_name] if base_name in counters else 0
counter += 1
counters[base_name] = counter
return "{}_{:03}".format(base_name, counter)
|
Remove the job id in the test to have conssitent name that does not change
|
Remove the job id in the test to have conssitent name that does not change
|
Python
|
bsd-3-clause
|
craft-ai/craft-ai-client-python,craft-ai/craft-ai-client-python
|
from os import environ
JOB_ID = environ.get("TRAVIS_JOB_ID", "loc")
ENTITY_MAX_LEN = 36
BASE_NAME_MAX_LEN = ENTITY_MAX_LEN - 3 - 3 - 2
counters = {}
def generate_entity_id(base_name="entity"):
# Keep only the first characters
base_name = base_name[:BASE_NAME_MAX_LEN]
counter = counters[base_name] if base_name in counters else 0
counter += 1
counters[base_name] = counter
return "{}_{:03}_{}".format(base_name, counter, JOB_ID[-3:])
Remove the job id in the test to have conssitent name that does not change
|
from os import environ
ENTITY_MAX_LEN = 36
BASE_NAME_MAX_LEN = ENTITY_MAX_LEN - 3 - 3 - 2
counters = {}
def generate_entity_id(base_name="entity"):
# Keep only the first characters
base_name = base_name[:BASE_NAME_MAX_LEN]
counter = counters[base_name] if base_name in counters else 0
counter += 1
counters[base_name] = counter
return "{}_{:03}".format(base_name, counter)
|
<commit_before>from os import environ
JOB_ID = environ.get("TRAVIS_JOB_ID", "loc")
ENTITY_MAX_LEN = 36
BASE_NAME_MAX_LEN = ENTITY_MAX_LEN - 3 - 3 - 2
counters = {}
def generate_entity_id(base_name="entity"):
# Keep only the first characters
base_name = base_name[:BASE_NAME_MAX_LEN]
counter = counters[base_name] if base_name in counters else 0
counter += 1
counters[base_name] = counter
return "{}_{:03}_{}".format(base_name, counter, JOB_ID[-3:])
<commit_msg>Remove the job id in the test to have conssitent name that does not change<commit_after>
|
from os import environ
ENTITY_MAX_LEN = 36
BASE_NAME_MAX_LEN = ENTITY_MAX_LEN - 3 - 3 - 2
counters = {}
def generate_entity_id(base_name="entity"):
# Keep only the first characters
base_name = base_name[:BASE_NAME_MAX_LEN]
counter = counters[base_name] if base_name in counters else 0
counter += 1
counters[base_name] = counter
return "{}_{:03}".format(base_name, counter)
|
from os import environ
JOB_ID = environ.get("TRAVIS_JOB_ID", "loc")
ENTITY_MAX_LEN = 36
BASE_NAME_MAX_LEN = ENTITY_MAX_LEN - 3 - 3 - 2
counters = {}
def generate_entity_id(base_name="entity"):
# Keep only the first characters
base_name = base_name[:BASE_NAME_MAX_LEN]
counter = counters[base_name] if base_name in counters else 0
counter += 1
counters[base_name] = counter
return "{}_{:03}_{}".format(base_name, counter, JOB_ID[-3:])
Remove the job id in the test to have conssitent name that does not changefrom os import environ
ENTITY_MAX_LEN = 36
BASE_NAME_MAX_LEN = ENTITY_MAX_LEN - 3 - 3 - 2
counters = {}
def generate_entity_id(base_name="entity"):
# Keep only the first characters
base_name = base_name[:BASE_NAME_MAX_LEN]
counter = counters[base_name] if base_name in counters else 0
counter += 1
counters[base_name] = counter
return "{}_{:03}".format(base_name, counter)
|
<commit_before>from os import environ
JOB_ID = environ.get("TRAVIS_JOB_ID", "loc")
ENTITY_MAX_LEN = 36
BASE_NAME_MAX_LEN = ENTITY_MAX_LEN - 3 - 3 - 2
counters = {}
def generate_entity_id(base_name="entity"):
# Keep only the first characters
base_name = base_name[:BASE_NAME_MAX_LEN]
counter = counters[base_name] if base_name in counters else 0
counter += 1
counters[base_name] = counter
return "{}_{:03}_{}".format(base_name, counter, JOB_ID[-3:])
<commit_msg>Remove the job id in the test to have conssitent name that does not change<commit_after>from os import environ
ENTITY_MAX_LEN = 36
BASE_NAME_MAX_LEN = ENTITY_MAX_LEN - 3 - 3 - 2
counters = {}
def generate_entity_id(base_name="entity"):
# Keep only the first characters
base_name = base_name[:BASE_NAME_MAX_LEN]
counter = counters[base_name] if base_name in counters else 0
counter += 1
counters[base_name] = counter
return "{}_{:03}".format(base_name, counter)
|
2979efa38e1b31424c69374b20bb6cf70c285395
|
source/globals/fieldtests.py
|
source/globals/fieldtests.py
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
def FieldEnabled(field):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled()
else:
return field.IsEnabled()
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
# \param enabled
# \b \e bool : Check if enabled or disabled
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
Add 'enabled' argument to FieldEnabled to test negative values
|
Add 'enabled' argument to FieldEnabled to test negative values
|
Python
|
mit
|
AntumDeluge/desktop_recorder,AntumDeluge/desktop_recorder
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
def FieldEnabled(field):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled()
else:
return field.IsEnabled()
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
Add 'enabled' argument to FieldEnabled to test negative values
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
# \param enabled
# \b \e bool : Check if enabled or disabled
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
<commit_before># -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
def FieldEnabled(field):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled()
else:
return field.IsEnabled()
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
<commit_msg>Add 'enabled' argument to FieldEnabled to test negative values<commit_after>
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
# \param enabled
# \b \e bool : Check if enabled or disabled
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
def FieldEnabled(field):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled()
else:
return field.IsEnabled()
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
Add 'enabled' argument to FieldEnabled to test negative values# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
# \param enabled
# \b \e bool : Check if enabled or disabled
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
<commit_before># -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
def FieldEnabled(field):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled()
else:
return field.IsEnabled()
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
<commit_msg>Add 'enabled' argument to FieldEnabled to test negative values<commit_after># -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
# \param enabled
# \b \e bool : Check if enabled or disabled
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
1d2237655ef0ba225e6fa0b8d0959ed6b3e75726
|
runtests.py
|
runtests.py
|
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=20'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
|
Add timeout to all tests
|
Add timeout to all tests
|
Python
|
mit
|
spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal
|
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
Add timeout to all tests
|
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=20'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
|
<commit_before># -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
<commit_msg>Add timeout to all tests<commit_after>
|
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=20'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
Add timeout to all tests# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=20'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
|
<commit_before># -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
<commit_msg>Add timeout to all tests<commit_after># -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=20'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
|
ac40e8a936f35757a43769f00fdef84a40919829
|
runtests.py
|
runtests.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import sys
import numba
sys.exit(0 if numba.test(sys.argv[1:]) == 0 else 1)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import sys
import numba
# TODO: Use argparse
if '--loop' in sys.argv:
whitelist = [arg for arg in sys.argv[1:] if arg != '--loop']
while True:
exit_status = numba.test(whitelist)
if exit_status != 0:
sys.exit(exit_status)
else:
sys.exit(numba.test(sys.argv[1:]))
|
Add "loop until fail" option to test runner (--loop)
|
Add "loop until fail" option to test runner (--loop)
|
Python
|
bsd-2-clause
|
gdementen/numba,stonebig/numba,gdementen/numba,seibert/numba,gmarkall/numba,jriehl/numba,sklam/numba,numba/numba,IntelLabs/numba,shiquanwang/numba,jriehl/numba,stuartarchibald/numba,sklam/numba,cpcloud/numba,jriehl/numba,sklam/numba,GaZ3ll3/numba,stuartarchibald/numba,IntelLabs/numba,stuartarchibald/numba,shiquanwang/numba,cpcloud/numba,ssarangi/numba,stonebig/numba,pombredanne/numba,stuartarchibald/numba,seibert/numba,IntelLabs/numba,pitrou/numba,gmarkall/numba,stefanseefeld/numba,pombredanne/numba,pombredanne/numba,numba/numba,GaZ3ll3/numba,ssarangi/numba,jriehl/numba,cpcloud/numba,sklam/numba,pombredanne/numba,pombredanne/numba,gdementen/numba,stefanseefeld/numba,GaZ3ll3/numba,stonebig/numba,stonebig/numba,GaZ3ll3/numba,GaZ3ll3/numba,IntelLabs/numba,pitrou/numba,stonebig/numba,shiquanwang/numba,stefanseefeld/numba,seibert/numba,stuartarchibald/numba,gmarkall/numba,IntelLabs/numba,ssarangi/numba,gmarkall/numba,gdementen/numba,numba/numba,numba/numba,sklam/numba,cpcloud/numba,pitrou/numba,seibert/numba,jriehl/numba,pitrou/numba,numba/numba,stefanseefeld/numba,gmarkall/numba,gdementen/numba,pitrou/numba,cpcloud/numba,stefanseefeld/numba,ssarangi/numba,seibert/numba,ssarangi/numba
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import sys
import numba
sys.exit(0 if numba.test(sys.argv[1:]) == 0 else 1)
Add "loop until fail" option to test runner (--loop)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import sys
import numba
# TODO: Use argparse
if '--loop' in sys.argv:
whitelist = [arg for arg in sys.argv[1:] if arg != '--loop']
while True:
exit_status = numba.test(whitelist)
if exit_status != 0:
sys.exit(exit_status)
else:
sys.exit(numba.test(sys.argv[1:]))
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import sys
import numba
sys.exit(0 if numba.test(sys.argv[1:]) == 0 else 1)
<commit_msg>Add "loop until fail" option to test runner (--loop)<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import sys
import numba
# TODO: Use argparse
if '--loop' in sys.argv:
whitelist = [arg for arg in sys.argv[1:] if arg != '--loop']
while True:
exit_status = numba.test(whitelist)
if exit_status != 0:
sys.exit(exit_status)
else:
sys.exit(numba.test(sys.argv[1:]))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import sys
import numba
sys.exit(0 if numba.test(sys.argv[1:]) == 0 else 1)
Add "loop until fail" option to test runner (--loop)#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import sys
import numba
# TODO: Use argparse
if '--loop' in sys.argv:
whitelist = [arg for arg in sys.argv[1:] if arg != '--loop']
while True:
exit_status = numba.test(whitelist)
if exit_status != 0:
sys.exit(exit_status)
else:
sys.exit(numba.test(sys.argv[1:]))
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import sys
import numba
sys.exit(0 if numba.test(sys.argv[1:]) == 0 else 1)
<commit_msg>Add "loop until fail" option to test runner (--loop)<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import sys
import numba
# TODO: Use argparse
if '--loop' in sys.argv:
whitelist = [arg for arg in sys.argv[1:] if arg != '--loop']
while True:
exit_status = numba.test(whitelist)
if exit_status != 0:
sys.exit(exit_status)
else:
sys.exit(numba.test(sys.argv[1:]))
|
26a8e03bf45594ce59d5f1b045fb72286994d497
|
test_todolist.py
|
test_todolist.py
|
# -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_empty_db(client):
user_resp = client.get('/user/1')
todo_resp = client.get('/todo/1')
assert b'No user here' in user_resp
assert b'No todo here' in todo_resp
assert 0 == 1
|
# -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_no_user(client):
user_resp = client.get('/user/1')
assert b'No user here' in user_resp.data
def test_no_todo(client):
todo_resp = client.get('/todo/1')
assert b'No ToDo here' in todo_resp.data
|
Split up tests and fixed misspelling.
|
Split up tests and fixed misspelling.
|
Python
|
mit
|
rtzll/flask-todolist,polyfunc/flask-todolist,0xfoo/flask-todolist,rtzll/flask-todolist,guillaumededrie/flask-todolist,poulp/flask-todolist,poulp/flask-todolist,poulp/flask-todolist,guillaumededrie/flask-todolist,polyfunc/flask-todolist,0xfoo/flask-todolist,guillaumededrie/flask-todolist,0xfoo/flask-todolist,rtzll/flask-todolist,polyfunc/flask-todolist,rtzll/flask-todolist
|
# -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_empty_db(client):
user_resp = client.get('/user/1')
todo_resp = client.get('/todo/1')
assert b'No user here' in user_resp
assert b'No todo here' in todo_resp
assert 0 == 1
Split up tests and fixed misspelling.
|
# -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_no_user(client):
user_resp = client.get('/user/1')
assert b'No user here' in user_resp.data
def test_no_todo(client):
todo_resp = client.get('/todo/1')
assert b'No ToDo here' in todo_resp.data
|
<commit_before># -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_empty_db(client):
user_resp = client.get('/user/1')
todo_resp = client.get('/todo/1')
assert b'No user here' in user_resp
assert b'No todo here' in todo_resp
assert 0 == 1
<commit_msg>Split up tests and fixed misspelling.<commit_after>
|
# -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_no_user(client):
user_resp = client.get('/user/1')
assert b'No user here' in user_resp.data
def test_no_todo(client):
todo_resp = client.get('/todo/1')
assert b'No ToDo here' in todo_resp.data
|
# -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_empty_db(client):
user_resp = client.get('/user/1')
todo_resp = client.get('/todo/1')
assert b'No user here' in user_resp
assert b'No todo here' in todo_resp
assert 0 == 1
Split up tests and fixed misspelling.# -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_no_user(client):
user_resp = client.get('/user/1')
assert b'No user here' in user_resp.data
def test_no_todo(client):
todo_resp = client.get('/todo/1')
assert b'No ToDo here' in todo_resp.data
|
<commit_before># -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_empty_db(client):
user_resp = client.get('/user/1')
todo_resp = client.get('/todo/1')
assert b'No user here' in user_resp
assert b'No todo here' in todo_resp
assert 0 == 1
<commit_msg>Split up tests and fixed misspelling.<commit_after># -*- coding: utf-8 -*-
import pytest
import os
import todolist
import tempfile
import manage
@pytest.fixture
def client(request):
db_fd, todolist.app.config['DATABASE'] = tempfile.mkstemp()
todolist.app.config['TESTING'] = True
client = todolist.app.test_client()
with todolist.app.app_context():
manage.initdb()
def teardown():
os.close(db_fd)
os.unlink(todolist.app.config['DATABASE'])
request.addfinalizer(teardown)
return client
def test_no_user(client):
user_resp = client.get('/user/1')
assert b'No user here' in user_resp.data
def test_no_todo(client):
todo_resp = client.get('/todo/1')
assert b'No ToDo here' in todo_resp.data
|
030f8fec423acb99574bc2a9b8760e3b9a8e0025
|
tests/apptest.py
|
tests/apptest.py
|
#ToDo : Write tests for application interface
import pytest
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from mp3wav.application import Mp3WavApp
from mp3wav.exceptions.fileexception import FileTypeException
from mp3wav.exceptions.libraryexception import LibraryException
from mp3wav.exceptions.filenotexistexception import FileNotExistException
from mp3wav.exceptions.samefileexception import SameFileException
from mp3wav.exceptions.overwriteexception import OverWriteException
def windowTest(qtbot):
testapp = Mp3WavApp()
testapp.show()
qtbot.addWidget(testapp)
assert testapp.isVisible()
assert testapp.close()
def correctConvertTest(qtbot, tmpdir):
testapp = Mp3WavApp()
qtbot.addWidget(testapp)
infile = tmpdir.mkdir("files").join("demo.mp3")
infile.write("something")
testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3")))
testapp.outputFileLine.setText(str(tmpdir.join('files')))
testapp.outputFileLineName.setText(str(tmpdir.join('files', 'demo.wav')))
qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
assert os.path.exists(str(tmpdir.join('files', 'demo.wav')))
|
#ToDo : Write tests for application interface
import pytest
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from mp3wav.application import Mp3WavApp
from mp3wav.exceptions.fileexception import FileTypeException
from mp3wav.exceptions.libraryexception import LibraryException
from mp3wav.exceptions.filenotexistexception import FileNotExistException
from mp3wav.exceptions.samefileexception import SameFileException
from mp3wav.exceptions.overwriteexception import OverWriteException
def windowTest(qtbot):
testapp = Mp3WavApp()
testapp.show()
qtbot.addWidget(testapp)
assert testapp.isVisible()
assert testapp.close()
def fileTypeTest(qtbot, tmpdir):
testapp = Mp3WavApp()
qtbot.addWidget(testapp)
infile = tmpdir.mkdir("files").join("demo.mp3")
infile.write("something")
testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3")))
testapp.outputFileLine.setText(str(tmpdir.join('files')))
testapp.outputFileLineName.setText('demo.wave')
with pytest.raises(FileTypeException):
qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
|
Test modified to check for exception in lack of ffmpeg in travis
|
Test modified to check for exception in lack of ffmpeg in travis
|
Python
|
mit
|
kapilgarg1996/mp3wav
|
#ToDo : Write tests for application interface
import pytest
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from mp3wav.application import Mp3WavApp
from mp3wav.exceptions.fileexception import FileTypeException
from mp3wav.exceptions.libraryexception import LibraryException
from mp3wav.exceptions.filenotexistexception import FileNotExistException
from mp3wav.exceptions.samefileexception import SameFileException
from mp3wav.exceptions.overwriteexception import OverWriteException
def windowTest(qtbot):
testapp = Mp3WavApp()
testapp.show()
qtbot.addWidget(testapp)
assert testapp.isVisible()
assert testapp.close()
def correctConvertTest(qtbot, tmpdir):
testapp = Mp3WavApp()
qtbot.addWidget(testapp)
infile = tmpdir.mkdir("files").join("demo.mp3")
infile.write("something")
testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3")))
testapp.outputFileLine.setText(str(tmpdir.join('files')))
testapp.outputFileLineName.setText(str(tmpdir.join('files', 'demo.wav')))
qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
assert os.path.exists(str(tmpdir.join('files', 'demo.wav')))
Test modified to check for exception in lack of ffmpeg in travis
|
#ToDo : Write tests for application interface
import pytest
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from mp3wav.application import Mp3WavApp
from mp3wav.exceptions.fileexception import FileTypeException
from mp3wav.exceptions.libraryexception import LibraryException
from mp3wav.exceptions.filenotexistexception import FileNotExistException
from mp3wav.exceptions.samefileexception import SameFileException
from mp3wav.exceptions.overwriteexception import OverWriteException
def windowTest(qtbot):
testapp = Mp3WavApp()
testapp.show()
qtbot.addWidget(testapp)
assert testapp.isVisible()
assert testapp.close()
def fileTypeTest(qtbot, tmpdir):
testapp = Mp3WavApp()
qtbot.addWidget(testapp)
infile = tmpdir.mkdir("files").join("demo.mp3")
infile.write("something")
testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3")))
testapp.outputFileLine.setText(str(tmpdir.join('files')))
testapp.outputFileLineName.setText('demo.wave')
with pytest.raises(FileTypeException):
qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
|
<commit_before>#ToDo : Write tests for application interface
import pytest
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from mp3wav.application import Mp3WavApp
from mp3wav.exceptions.fileexception import FileTypeException
from mp3wav.exceptions.libraryexception import LibraryException
from mp3wav.exceptions.filenotexistexception import FileNotExistException
from mp3wav.exceptions.samefileexception import SameFileException
from mp3wav.exceptions.overwriteexception import OverWriteException
def windowTest(qtbot):
testapp = Mp3WavApp()
testapp.show()
qtbot.addWidget(testapp)
assert testapp.isVisible()
assert testapp.close()
def correctConvertTest(qtbot, tmpdir):
testapp = Mp3WavApp()
qtbot.addWidget(testapp)
infile = tmpdir.mkdir("files").join("demo.mp3")
infile.write("something")
testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3")))
testapp.outputFileLine.setText(str(tmpdir.join('files')))
testapp.outputFileLineName.setText(str(tmpdir.join('files', 'demo.wav')))
qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
assert os.path.exists(str(tmpdir.join('files', 'demo.wav')))
<commit_msg>Test modified to check for exception in lack of ffmpeg in travis<commit_after>
|
#ToDo : Write tests for application interface
import pytest
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from mp3wav.application import Mp3WavApp
from mp3wav.exceptions.fileexception import FileTypeException
from mp3wav.exceptions.libraryexception import LibraryException
from mp3wav.exceptions.filenotexistexception import FileNotExistException
from mp3wav.exceptions.samefileexception import SameFileException
from mp3wav.exceptions.overwriteexception import OverWriteException
def windowTest(qtbot):
testapp = Mp3WavApp()
testapp.show()
qtbot.addWidget(testapp)
assert testapp.isVisible()
assert testapp.close()
def fileTypeTest(qtbot, tmpdir):
testapp = Mp3WavApp()
qtbot.addWidget(testapp)
infile = tmpdir.mkdir("files").join("demo.mp3")
infile.write("something")
testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3")))
testapp.outputFileLine.setText(str(tmpdir.join('files')))
testapp.outputFileLineName.setText('demo.wave')
with pytest.raises(FileTypeException):
qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
|
#ToDo : Write tests for application interface
import pytest
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from mp3wav.application import Mp3WavApp
from mp3wav.exceptions.fileexception import FileTypeException
from mp3wav.exceptions.libraryexception import LibraryException
from mp3wav.exceptions.filenotexistexception import FileNotExistException
from mp3wav.exceptions.samefileexception import SameFileException
from mp3wav.exceptions.overwriteexception import OverWriteException
def windowTest(qtbot):
testapp = Mp3WavApp()
testapp.show()
qtbot.addWidget(testapp)
assert testapp.isVisible()
assert testapp.close()
def correctConvertTest(qtbot, tmpdir):
testapp = Mp3WavApp()
qtbot.addWidget(testapp)
infile = tmpdir.mkdir("files").join("demo.mp3")
infile.write("something")
testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3")))
testapp.outputFileLine.setText(str(tmpdir.join('files')))
testapp.outputFileLineName.setText(str(tmpdir.join('files', 'demo.wav')))
qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
assert os.path.exists(str(tmpdir.join('files', 'demo.wav')))
Test modified to check for exception in lack of ffmpeg in travis#ToDo : Write tests for application interface
import pytest
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from mp3wav.application import Mp3WavApp
from mp3wav.exceptions.fileexception import FileTypeException
from mp3wav.exceptions.libraryexception import LibraryException
from mp3wav.exceptions.filenotexistexception import FileNotExistException
from mp3wav.exceptions.samefileexception import SameFileException
from mp3wav.exceptions.overwriteexception import OverWriteException
def windowTest(qtbot):
testapp = Mp3WavApp()
testapp.show()
qtbot.addWidget(testapp)
assert testapp.isVisible()
assert testapp.close()
def fileTypeTest(qtbot, tmpdir):
testapp = Mp3WavApp()
qtbot.addWidget(testapp)
infile = tmpdir.mkdir("files").join("demo.mp3")
infile.write("something")
testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3")))
testapp.outputFileLine.setText(str(tmpdir.join('files')))
testapp.outputFileLineName.setText('demo.wave')
with pytest.raises(FileTypeException):
qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
|
<commit_before>#ToDo : Write tests for application interface
import pytest
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from mp3wav.application import Mp3WavApp
from mp3wav.exceptions.fileexception import FileTypeException
from mp3wav.exceptions.libraryexception import LibraryException
from mp3wav.exceptions.filenotexistexception import FileNotExistException
from mp3wav.exceptions.samefileexception import SameFileException
from mp3wav.exceptions.overwriteexception import OverWriteException
def windowTest(qtbot):
testapp = Mp3WavApp()
testapp.show()
qtbot.addWidget(testapp)
assert testapp.isVisible()
assert testapp.close()
def correctConvertTest(qtbot, tmpdir):
testapp = Mp3WavApp()
qtbot.addWidget(testapp)
infile = tmpdir.mkdir("files").join("demo.mp3")
infile.write("something")
testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3")))
testapp.outputFileLine.setText(str(tmpdir.join('files')))
testapp.outputFileLineName.setText(str(tmpdir.join('files', 'demo.wav')))
qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
assert os.path.exists(str(tmpdir.join('files', 'demo.wav')))
<commit_msg>Test modified to check for exception in lack of ffmpeg in travis<commit_after>#ToDo : Write tests for application interface
import pytest
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from mp3wav.application import Mp3WavApp
from mp3wav.exceptions.fileexception import FileTypeException
from mp3wav.exceptions.libraryexception import LibraryException
from mp3wav.exceptions.filenotexistexception import FileNotExistException
from mp3wav.exceptions.samefileexception import SameFileException
from mp3wav.exceptions.overwriteexception import OverWriteException
def windowTest(qtbot):
testapp = Mp3WavApp()
testapp.show()
qtbot.addWidget(testapp)
assert testapp.isVisible()
assert testapp.close()
def fileTypeTest(qtbot, tmpdir):
testapp = Mp3WavApp()
qtbot.addWidget(testapp)
infile = tmpdir.mkdir("files").join("demo.mp3")
infile.write("something")
testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3")))
testapp.outputFileLine.setText(str(tmpdir.join('files')))
testapp.outputFileLineName.setText('demo.wave')
with pytest.raises(FileTypeException):
qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
|
359445fa4d554d3dd2ba2cb2850af4b892d7090e
|
binder/tests/testapp/models/animal.py
|
binder/tests/testapp/models/animal.py
|
from django.db import models
from binder.models import BinderModel
# From the api docs: an animal with a name. We don't use the
# CaseInsensitiveCharField because it's so much simpler to use
# memory-backed sqlite than Postgres in the tests. Eventually we
# might switch and require Postgres for tests, if we need many
# Postgres-specific things.
class Animal(BinderModel):
name = models.TextField(max_length=64)
zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
deleted = models.BooleanField(default=False) # Softdelete
def __str__(self):
return 'animal %d: %s' % (self.pk or 0, self.name)
class Binder:
history = True
|
from django.db import models
from binder.models import BinderModel
from binder.exceptions import BinderValidationError
# From the api docs: an animal with a name. We don't use the
# CaseInsensitiveCharField because it's so much simpler to use
# memory-backed sqlite than Postgres in the tests. Eventually we
# might switch and require Postgres for tests, if we need many
# Postgres-specific things.
class Animal(BinderModel):
name = models.TextField(max_length=64)
zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
deleted = models.BooleanField(default=False) # Softdelete
def __str__(self):
return 'animal %d: %s' % (self.pk or 0, self.name)
def _binder_unset_relation_caretaker(self):
raise BinderValidationError({'animal': {self.pk: {'caretaker': [{
'code': 'cant_unset',
'message': 'You can\'t unset zoo.',
}]}}})
class Binder:
history = True
|
Add overridden behaviour to testapp.
|
Add overridden behaviour to testapp.
|
Python
|
mit
|
CodeYellowBV/django-binder
|
from django.db import models
from binder.models import BinderModel
# From the api docs: an animal with a name. We don't use the
# CaseInsensitiveCharField because it's so much simpler to use
# memory-backed sqlite than Postgres in the tests. Eventually we
# might switch and require Postgres for tests, if we need many
# Postgres-specific things.
class Animal(BinderModel):
name = models.TextField(max_length=64)
zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
deleted = models.BooleanField(default=False) # Softdelete
def __str__(self):
return 'animal %d: %s' % (self.pk or 0, self.name)
class Binder:
history = True
Add overridden behaviour to testapp.
|
from django.db import models
from binder.models import BinderModel
from binder.exceptions import BinderValidationError
# From the api docs: an animal with a name. We don't use the
# CaseInsensitiveCharField because it's so much simpler to use
# memory-backed sqlite than Postgres in the tests. Eventually we
# might switch and require Postgres for tests, if we need many
# Postgres-specific things.
class Animal(BinderModel):
name = models.TextField(max_length=64)
zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
deleted = models.BooleanField(default=False) # Softdelete
def __str__(self):
return 'animal %d: %s' % (self.pk or 0, self.name)
def _binder_unset_relation_caretaker(self):
raise BinderValidationError({'animal': {self.pk: {'caretaker': [{
'code': 'cant_unset',
'message': 'You can\'t unset zoo.',
}]}}})
class Binder:
history = True
|
<commit_before>from django.db import models
from binder.models import BinderModel
# From the api docs: an animal with a name. We don't use the
# CaseInsensitiveCharField because it's so much simpler to use
# memory-backed sqlite than Postgres in the tests. Eventually we
# might switch and require Postgres for tests, if we need many
# Postgres-specific things.
class Animal(BinderModel):
name = models.TextField(max_length=64)
zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
deleted = models.BooleanField(default=False) # Softdelete
def __str__(self):
return 'animal %d: %s' % (self.pk or 0, self.name)
class Binder:
history = True
<commit_msg>Add overridden behaviour to testapp.<commit_after>
|
from django.db import models
from binder.models import BinderModel
from binder.exceptions import BinderValidationError
# From the api docs: an animal with a name. We don't use the
# CaseInsensitiveCharField because it's so much simpler to use
# memory-backed sqlite than Postgres in the tests. Eventually we
# might switch and require Postgres for tests, if we need many
# Postgres-specific things.
class Animal(BinderModel):
name = models.TextField(max_length=64)
zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
deleted = models.BooleanField(default=False) # Softdelete
def __str__(self):
return 'animal %d: %s' % (self.pk or 0, self.name)
def _binder_unset_relation_caretaker(self):
raise BinderValidationError({'animal': {self.pk: {'caretaker': [{
'code': 'cant_unset',
'message': 'You can\'t unset zoo.',
}]}}})
class Binder:
history = True
|
from django.db import models
from binder.models import BinderModel
# From the api docs: an animal with a name. We don't use the
# CaseInsensitiveCharField because it's so much simpler to use
# memory-backed sqlite than Postgres in the tests. Eventually we
# might switch and require Postgres for tests, if we need many
# Postgres-specific things.
class Animal(BinderModel):
name = models.TextField(max_length=64)
zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
deleted = models.BooleanField(default=False) # Softdelete
def __str__(self):
return 'animal %d: %s' % (self.pk or 0, self.name)
class Binder:
history = True
Add overridden behaviour to testapp.from django.db import models
from binder.models import BinderModel
from binder.exceptions import BinderValidationError
# From the api docs: an animal with a name. We don't use the
# CaseInsensitiveCharField because it's so much simpler to use
# memory-backed sqlite than Postgres in the tests. Eventually we
# might switch and require Postgres for tests, if we need many
# Postgres-specific things.
class Animal(BinderModel):
name = models.TextField(max_length=64)
zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
deleted = models.BooleanField(default=False) # Softdelete
def __str__(self):
return 'animal %d: %s' % (self.pk or 0, self.name)
def _binder_unset_relation_caretaker(self):
raise BinderValidationError({'animal': {self.pk: {'caretaker': [{
'code': 'cant_unset',
'message': 'You can\'t unset zoo.',
}]}}})
class Binder:
history = True
|
<commit_before>from django.db import models
from binder.models import BinderModel
# From the api docs: an animal with a name. We don't use the
# CaseInsensitiveCharField because it's so much simpler to use
# memory-backed sqlite than Postgres in the tests. Eventually we
# might switch and require Postgres for tests, if we need many
# Postgres-specific things.
class Animal(BinderModel):
name = models.TextField(max_length=64)
zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
deleted = models.BooleanField(default=False) # Softdelete
def __str__(self):
return 'animal %d: %s' % (self.pk or 0, self.name)
class Binder:
history = True
<commit_msg>Add overridden behaviour to testapp.<commit_after>from django.db import models
from binder.models import BinderModel
from binder.exceptions import BinderValidationError
# From the api docs: an animal with a name. We don't use the
# CaseInsensitiveCharField because it's so much simpler to use
# memory-backed sqlite than Postgres in the tests. Eventually we
# might switch and require Postgres for tests, if we need many
# Postgres-specific things.
class Animal(BinderModel):
name = models.TextField(max_length=64)
zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True)
deleted = models.BooleanField(default=False) # Softdelete
def __str__(self):
return 'animal %d: %s' % (self.pk or 0, self.name)
def _binder_unset_relation_caretaker(self):
raise BinderValidationError({'animal': {self.pk: {'caretaker': [{
'code': 'cant_unset',
'message': 'You can\'t unset zoo.',
}]}}})
class Binder:
history = True
|
fbdfb3de379af44880b928b6779a2edb578fb987
|
changes/api/serializer/models/plan.py
|
changes/api/serializer/models/plan.py
|
import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data)),
'dateCreated': instance.date_created,
}
|
import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data or {})),
'dateCreated': instance.date_created,
}
|
Handle optional value in step.data
|
Handle optional value in step.data
|
Python
|
apache-2.0
|
dropbox/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,dropbox/changes
|
import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data)),
'dateCreated': instance.date_created,
}
Handle optional value in step.data
|
import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data or {})),
'dateCreated': instance.date_created,
}
|
<commit_before>import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data)),
'dateCreated': instance.date_created,
}
<commit_msg>Handle optional value in step.data<commit_after>
|
import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data or {})),
'dateCreated': instance.date_created,
}
|
import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data)),
'dateCreated': instance.date_created,
}
Handle optional value in step.dataimport json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data or {})),
'dateCreated': instance.date_created,
}
|
<commit_before>import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data)),
'dateCreated': instance.date_created,
}
<commit_msg>Handle optional value in step.data<commit_after>import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data or {})),
'dateCreated': instance.date_created,
}
|
06ef0b92b1c8e6cc2916f4d68ec3b4ae513c9085
|
july/people/views.py
|
july/people/views.py
|
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
from forms import EditUserForm
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
|
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
from forms import EditUserForm
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
|
Fix typo and move missing import into edit view
|
Fix typo and move missing import into edit view
|
Python
|
mit
|
julython/julython.org,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober
|
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
from forms import EditUserForm
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
Fix typo and move missing import into edit view
|
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
from forms import EditUserForm
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
|
<commit_before>from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
from forms import EditUserForm
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
<commit_msg>Fix typo and move missing import into edit view<commit_after>
|
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
from forms import EditUserForm
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
|
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
from forms import EditUserForm
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
Fix typo and move missing import into edit viewfrom django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
from forms import EditUserForm
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
|
<commit_before>from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
from forms import EditUserForm
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
<commit_msg>Fix typo and move missing import into edit view<commit_after>from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
#from google.appengine.ext import db
from july.people.models import Commit
from gae_django.auth.models import User
from django.http import Http404
def user_profile(request, username):
user = User.all().filter("username", username).get()
if user == None:
raise Http404("User not found")
commits = Commit.all().ancestor(request.user.key())
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request))
@login_required
def edit_profile(request, username, template_name='people/edit.html'):
from forms import EditUserForm
user = request.user
#CONSIDER FILES with no POST? Can that happen?
form = EditUserForm(request.POST or None, request.FILES or None)
if form.is_valid():
for key in form.cleaned_data:
setattr(user,key,form.cleaned_data.get(key))
user.put()
if user == None:
raise Http404("User not found")
expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()])
return render_to_response(template_name, {'form':form, }, RequestContext(request))
|
5b4ba4e6cbb6cae1793c699a540aecb64236ca34
|
riot/app.py
|
riot/app.py
|
# -*- coding: utf-8 -*-
import urwid
def run_tag(tag, *args, **kwargs):
loop = urwid.MainLoop(tag, *args, **kwargs)
loop.run()
def quit_app():
raise urwid.ExitMainLoop()
|
# -*- coding: utf-8 -*-
import urwid
def run_tag(tag, *args, **kwargs):
loop = urwid.MainLoop(tag, *args, **kwargs)
loop.screen.set_terminal_properties(colors=256)
loop.run()
def quit_app():
raise urwid.ExitMainLoop()
|
Set default property screen 256 colors.
|
Set default property screen 256 colors.
|
Python
|
mit
|
soasme/riotpy
|
# -*- coding: utf-8 -*-
import urwid
def run_tag(tag, *args, **kwargs):
loop = urwid.MainLoop(tag, *args, **kwargs)
loop.run()
def quit_app():
raise urwid.ExitMainLoop()
Set default property screen 256 colors.
|
# -*- coding: utf-8 -*-
import urwid
def run_tag(tag, *args, **kwargs):
loop = urwid.MainLoop(tag, *args, **kwargs)
loop.screen.set_terminal_properties(colors=256)
loop.run()
def quit_app():
raise urwid.ExitMainLoop()
|
<commit_before># -*- coding: utf-8 -*-
import urwid
def run_tag(tag, *args, **kwargs):
loop = urwid.MainLoop(tag, *args, **kwargs)
loop.run()
def quit_app():
raise urwid.ExitMainLoop()
<commit_msg>Set default property screen 256 colors.<commit_after>
|
# -*- coding: utf-8 -*-
import urwid
def run_tag(tag, *args, **kwargs):
loop = urwid.MainLoop(tag, *args, **kwargs)
loop.screen.set_terminal_properties(colors=256)
loop.run()
def quit_app():
raise urwid.ExitMainLoop()
|
# -*- coding: utf-8 -*-
import urwid
def run_tag(tag, *args, **kwargs):
loop = urwid.MainLoop(tag, *args, **kwargs)
loop.run()
def quit_app():
raise urwid.ExitMainLoop()
Set default property screen 256 colors.# -*- coding: utf-8 -*-
import urwid
def run_tag(tag, *args, **kwargs):
loop = urwid.MainLoop(tag, *args, **kwargs)
loop.screen.set_terminal_properties(colors=256)
loop.run()
def quit_app():
raise urwid.ExitMainLoop()
|
<commit_before># -*- coding: utf-8 -*-
import urwid
def run_tag(tag, *args, **kwargs):
loop = urwid.MainLoop(tag, *args, **kwargs)
loop.run()
def quit_app():
raise urwid.ExitMainLoop()
<commit_msg>Set default property screen 256 colors.<commit_after># -*- coding: utf-8 -*-
import urwid
def run_tag(tag, *args, **kwargs):
loop = urwid.MainLoop(tag, *args, **kwargs)
loop.screen.set_terminal_properties(colors=256)
loop.run()
def quit_app():
raise urwid.ExitMainLoop()
|
ab8141cee63379495837c15d0fb433f941a3c27b
|
tools/reviews.py
|
tools/reviews.py
|
#!/usr/bin/python
import json
import utils
def component_reviews(component, reviewer=None):
cmd = ('ssh review.openstack.org gerrit query --format json '
'--current-patch-set project:%s status:open '
'limit:10000'
% component)
if reviewer:
cmd += ' reviewer:%s' % reviewer
else:
cmd += ' --all-approvals'
stdout = utils.runcmd(cmd)
reviews = []
for line in stdout.split('\n'):
if not line:
continue
try:
packet = json.loads(line)
if packet.get('project') == component:
reviews.append(packet)
except ValueError as e:
print 'Could not decode:'
print ' %s' % line
print ' Error: %s' % e
return reviews
if __name__ == '__main__':
reviews = component_reviews('openstack/nova', reviewer='mikal@stillhq.com')
print '%s reviews found' % len(reviews)
for review in reviews:
print
for key in sorted(review.keys()):
if key == 'patchSets':
print '%s:' % key
for ps in review[key]:
print ' %s' % ps
else:
print '%s: %s' %(key, review[key])
|
#!/usr/bin/python
import argparse
import json
import utils
def component_reviews(component, reviewer=None):
cmd = ('ssh review.openstack.org gerrit query --format json '
'--current-patch-set project:%s status:open '
'limit:10000'
% component)
if reviewer:
cmd += ' reviewer:%s' % reviewer
else:
cmd += ' --all-approvals'
stdout = utils.runcmd(cmd)
reviews = []
for line in stdout.split('\n'):
if not line:
continue
try:
packet = json.loads(line)
if packet.get('project') == component:
reviews.append(packet)
except ValueError as e:
print 'Could not decode:'
print ' %s' % line
print ' Error: %s' % e
return reviews
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--username', default='mikalstill',
help='The username (if any) to filter by')
ARGS = parser.parse_args()
reviews = component_reviews('openstack/nova', reviewer=ARGS.username)
print '%s reviews found' % len(reviews)
for review in reviews:
print
for key in sorted(review.keys()):
if key == 'patchSets':
print '%s:' % key
for ps in review[key]:
print ' %s' % ps
else:
print '%s: %s' %(key, review[key])
|
Handle args in the review helper.
|
Handle args in the review helper.
|
Python
|
apache-2.0
|
rcbau/hacks,rcbau/hacks,rcbau/hacks
|
#!/usr/bin/python
import json
import utils
def component_reviews(component, reviewer=None):
cmd = ('ssh review.openstack.org gerrit query --format json '
'--current-patch-set project:%s status:open '
'limit:10000'
% component)
if reviewer:
cmd += ' reviewer:%s' % reviewer
else:
cmd += ' --all-approvals'
stdout = utils.runcmd(cmd)
reviews = []
for line in stdout.split('\n'):
if not line:
continue
try:
packet = json.loads(line)
if packet.get('project') == component:
reviews.append(packet)
except ValueError as e:
print 'Could not decode:'
print ' %s' % line
print ' Error: %s' % e
return reviews
if __name__ == '__main__':
reviews = component_reviews('openstack/nova', reviewer='mikal@stillhq.com')
print '%s reviews found' % len(reviews)
for review in reviews:
print
for key in sorted(review.keys()):
if key == 'patchSets':
print '%s:' % key
for ps in review[key]:
print ' %s' % ps
else:
print '%s: %s' %(key, review[key])
Handle args in the review helper.
|
#!/usr/bin/python
import argparse
import json
import utils
def component_reviews(component, reviewer=None):
cmd = ('ssh review.openstack.org gerrit query --format json '
'--current-patch-set project:%s status:open '
'limit:10000'
% component)
if reviewer:
cmd += ' reviewer:%s' % reviewer
else:
cmd += ' --all-approvals'
stdout = utils.runcmd(cmd)
reviews = []
for line in stdout.split('\n'):
if not line:
continue
try:
packet = json.loads(line)
if packet.get('project') == component:
reviews.append(packet)
except ValueError as e:
print 'Could not decode:'
print ' %s' % line
print ' Error: %s' % e
return reviews
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--username', default='mikalstill',
help='The username (if any) to filter by')
ARGS = parser.parse_args()
reviews = component_reviews('openstack/nova', reviewer=ARGS.username)
print '%s reviews found' % len(reviews)
for review in reviews:
print
for key in sorted(review.keys()):
if key == 'patchSets':
print '%s:' % key
for ps in review[key]:
print ' %s' % ps
else:
print '%s: %s' %(key, review[key])
|
<commit_before>#!/usr/bin/python
import json
import utils
def component_reviews(component, reviewer=None):
cmd = ('ssh review.openstack.org gerrit query --format json '
'--current-patch-set project:%s status:open '
'limit:10000'
% component)
if reviewer:
cmd += ' reviewer:%s' % reviewer
else:
cmd += ' --all-approvals'
stdout = utils.runcmd(cmd)
reviews = []
for line in stdout.split('\n'):
if not line:
continue
try:
packet = json.loads(line)
if packet.get('project') == component:
reviews.append(packet)
except ValueError as e:
print 'Could not decode:'
print ' %s' % line
print ' Error: %s' % e
return reviews
if __name__ == '__main__':
reviews = component_reviews('openstack/nova', reviewer='mikal@stillhq.com')
print '%s reviews found' % len(reviews)
for review in reviews:
print
for key in sorted(review.keys()):
if key == 'patchSets':
print '%s:' % key
for ps in review[key]:
print ' %s' % ps
else:
print '%s: %s' %(key, review[key])
<commit_msg>Handle args in the review helper.<commit_after>
|
#!/usr/bin/python
import argparse
import json
import utils
def component_reviews(component, reviewer=None):
cmd = ('ssh review.openstack.org gerrit query --format json '
'--current-patch-set project:%s status:open '
'limit:10000'
% component)
if reviewer:
cmd += ' reviewer:%s' % reviewer
else:
cmd += ' --all-approvals'
stdout = utils.runcmd(cmd)
reviews = []
for line in stdout.split('\n'):
if not line:
continue
try:
packet = json.loads(line)
if packet.get('project') == component:
reviews.append(packet)
except ValueError as e:
print 'Could not decode:'
print ' %s' % line
print ' Error: %s' % e
return reviews
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--username', default='mikalstill',
help='The username (if any) to filter by')
ARGS = parser.parse_args()
reviews = component_reviews('openstack/nova', reviewer=ARGS.username)
print '%s reviews found' % len(reviews)
for review in reviews:
print
for key in sorted(review.keys()):
if key == 'patchSets':
print '%s:' % key
for ps in review[key]:
print ' %s' % ps
else:
print '%s: %s' %(key, review[key])
|
#!/usr/bin/python
import json
import utils
def component_reviews(component, reviewer=None):
cmd = ('ssh review.openstack.org gerrit query --format json '
'--current-patch-set project:%s status:open '
'limit:10000'
% component)
if reviewer:
cmd += ' reviewer:%s' % reviewer
else:
cmd += ' --all-approvals'
stdout = utils.runcmd(cmd)
reviews = []
for line in stdout.split('\n'):
if not line:
continue
try:
packet = json.loads(line)
if packet.get('project') == component:
reviews.append(packet)
except ValueError as e:
print 'Could not decode:'
print ' %s' % line
print ' Error: %s' % e
return reviews
if __name__ == '__main__':
reviews = component_reviews('openstack/nova', reviewer='mikal@stillhq.com')
print '%s reviews found' % len(reviews)
for review in reviews:
print
for key in sorted(review.keys()):
if key == 'patchSets':
print '%s:' % key
for ps in review[key]:
print ' %s' % ps
else:
print '%s: %s' %(key, review[key])
Handle args in the review helper.#!/usr/bin/python
import argparse
import json
import utils
def component_reviews(component, reviewer=None):
cmd = ('ssh review.openstack.org gerrit query --format json '
'--current-patch-set project:%s status:open '
'limit:10000'
% component)
if reviewer:
cmd += ' reviewer:%s' % reviewer
else:
cmd += ' --all-approvals'
stdout = utils.runcmd(cmd)
reviews = []
for line in stdout.split('\n'):
if not line:
continue
try:
packet = json.loads(line)
if packet.get('project') == component:
reviews.append(packet)
except ValueError as e:
print 'Could not decode:'
print ' %s' % line
print ' Error: %s' % e
return reviews
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--username', default='mikalstill',
help='The username (if any) to filter by')
ARGS = parser.parse_args()
reviews = component_reviews('openstack/nova', reviewer=ARGS.username)
print '%s reviews found' % len(reviews)
for review in reviews:
print
for key in sorted(review.keys()):
if key == 'patchSets':
print '%s:' % key
for ps in review[key]:
print ' %s' % ps
else:
print '%s: %s' %(key, review[key])
|
<commit_before>#!/usr/bin/python
import json
import utils
def component_reviews(component, reviewer=None):
cmd = ('ssh review.openstack.org gerrit query --format json '
'--current-patch-set project:%s status:open '
'limit:10000'
% component)
if reviewer:
cmd += ' reviewer:%s' % reviewer
else:
cmd += ' --all-approvals'
stdout = utils.runcmd(cmd)
reviews = []
for line in stdout.split('\n'):
if not line:
continue
try:
packet = json.loads(line)
if packet.get('project') == component:
reviews.append(packet)
except ValueError as e:
print 'Could not decode:'
print ' %s' % line
print ' Error: %s' % e
return reviews
if __name__ == '__main__':
reviews = component_reviews('openstack/nova', reviewer='mikal@stillhq.com')
print '%s reviews found' % len(reviews)
for review in reviews:
print
for key in sorted(review.keys()):
if key == 'patchSets':
print '%s:' % key
for ps in review[key]:
print ' %s' % ps
else:
print '%s: %s' %(key, review[key])
<commit_msg>Handle args in the review helper.<commit_after>#!/usr/bin/python
import argparse
import json
import utils
def component_reviews(component, reviewer=None):
cmd = ('ssh review.openstack.org gerrit query --format json '
'--current-patch-set project:%s status:open '
'limit:10000'
% component)
if reviewer:
cmd += ' reviewer:%s' % reviewer
else:
cmd += ' --all-approvals'
stdout = utils.runcmd(cmd)
reviews = []
for line in stdout.split('\n'):
if not line:
continue
try:
packet = json.loads(line)
if packet.get('project') == component:
reviews.append(packet)
except ValueError as e:
print 'Could not decode:'
print ' %s' % line
print ' Error: %s' % e
return reviews
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--username', default='mikalstill',
help='The username (if any) to filter by')
ARGS = parser.parse_args()
reviews = component_reviews('openstack/nova', reviewer=ARGS.username)
print '%s reviews found' % len(reviews)
for review in reviews:
print
for key in sorted(review.keys()):
if key == 'patchSets':
print '%s:' % key
for ps in review[key]:
print ' %s' % ps
else:
print '%s: %s' %(key, review[key])
|
f765b9c7911a53bf248ea49ef57bdbb4847bf5e1
|
corehq/apps/export/esaccessors.py
|
corehq/apps/export/esaccessors.py
|
from corehq.apps.es import CaseES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, xmlns):
# TODO: This probably needs app_id too
return (FormES().
domain(domain)
.xmlns(xmlns)
.sort("received_on"))
def get_case_export_base_query(domain, case_type):
return (CaseES()
.domain(domain)
.case_type(case_type)
.sort("modified_on"))
|
from corehq.apps.es import CaseES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, xmlns):
# TODO: This probably needs app_id too
return (FormES().
domain(domain)
.xmlns(xmlns)
.sort("received_on"))
def get_case_export_base_query(domain, case_type):
return (CaseES()
.domain(domain)
.case_type(case_type)
.sort("opened_on"))
|
Sort cases by opened_on, not modified_on
|
Sort cases by opened_on, not modified_on
Addresses
https://github.com/dimagi/commcare-hq/pull/10187/files#r51863935
|
Python
|
bsd-3-clause
|
qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq
|
from corehq.apps.es import CaseES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, xmlns):
# TODO: This probably needs app_id too
return (FormES().
domain(domain)
.xmlns(xmlns)
.sort("received_on"))
def get_case_export_base_query(domain, case_type):
return (CaseES()
.domain(domain)
.case_type(case_type)
.sort("modified_on"))
Sort cases by opened_on, not modified_on
Addresses
https://github.com/dimagi/commcare-hq/pull/10187/files#r51863935
|
from corehq.apps.es import CaseES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, xmlns):
# TODO: This probably needs app_id too
return (FormES().
domain(domain)
.xmlns(xmlns)
.sort("received_on"))
def get_case_export_base_query(domain, case_type):
return (CaseES()
.domain(domain)
.case_type(case_type)
.sort("opened_on"))
|
<commit_before>from corehq.apps.es import CaseES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, xmlns):
# TODO: This probably needs app_id too
return (FormES().
domain(domain)
.xmlns(xmlns)
.sort("received_on"))
def get_case_export_base_query(domain, case_type):
return (CaseES()
.domain(domain)
.case_type(case_type)
.sort("modified_on"))
<commit_msg>Sort cases by opened_on, not modified_on
Addresses
https://github.com/dimagi/commcare-hq/pull/10187/files#r51863935<commit_after>
|
from corehq.apps.es import CaseES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, xmlns):
# TODO: This probably needs app_id too
return (FormES().
domain(domain)
.xmlns(xmlns)
.sort("received_on"))
def get_case_export_base_query(domain, case_type):
return (CaseES()
.domain(domain)
.case_type(case_type)
.sort("opened_on"))
|
from corehq.apps.es import CaseES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, xmlns):
# TODO: This probably needs app_id too
return (FormES().
domain(domain)
.xmlns(xmlns)
.sort("received_on"))
def get_case_export_base_query(domain, case_type):
return (CaseES()
.domain(domain)
.case_type(case_type)
.sort("modified_on"))
Sort cases by opened_on, not modified_on
Addresses
https://github.com/dimagi/commcare-hq/pull/10187/files#r51863935from corehq.apps.es import CaseES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, xmlns):
# TODO: This probably needs app_id too
return (FormES().
domain(domain)
.xmlns(xmlns)
.sort("received_on"))
def get_case_export_base_query(domain, case_type):
return (CaseES()
.domain(domain)
.case_type(case_type)
.sort("opened_on"))
|
<commit_before>from corehq.apps.es import CaseES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, xmlns):
# TODO: This probably needs app_id too
return (FormES().
domain(domain)
.xmlns(xmlns)
.sort("received_on"))
def get_case_export_base_query(domain, case_type):
return (CaseES()
.domain(domain)
.case_type(case_type)
.sort("modified_on"))
<commit_msg>Sort cases by opened_on, not modified_on
Addresses
https://github.com/dimagi/commcare-hq/pull/10187/files#r51863935<commit_after>from corehq.apps.es import CaseES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, xmlns):
# TODO: This probably needs app_id too
return (FormES().
domain(domain)
.xmlns(xmlns)
.sort("received_on"))
def get_case_export_base_query(domain, case_type):
return (CaseES()
.domain(domain)
.case_type(case_type)
.sort("opened_on"))
|
aae994402b1b16a2bca4a486dad4bb452770eb26
|
tests/pipeline/test_provider_healthcheck.py
|
tests/pipeline/test_provider_healthcheck.py
|
"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck
TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}
def test_provider_healthcheck():
"""Make sure default Provider Health Check works."""
provider_healthcheck, has_provider_healthcheck = check_provider_healthcheck(settings=TEST_SETTINGS)
assert provider_healthcheck == []
assert has_provider_healthcheck == False
|
"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck
TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}
def test_provider_healthcheck():
"""Make sure default Provider Health Check works."""
health_checks = check_provider_healthcheck(settings=TEST_SETTINGS)
assert health_checks.providers == []
assert health_checks.has_healthcheck == False
|
Update Provider Health Check sanity
|
test: Update Provider Health Check sanity
See also: PSOBAT-2465
|
Python
|
apache-2.0
|
gogoair/foremast,gogoair/foremast
|
"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck
TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}
def test_provider_healthcheck():
"""Make sure default Provider Health Check works."""
provider_healthcheck, has_provider_healthcheck = check_provider_healthcheck(settings=TEST_SETTINGS)
assert provider_healthcheck == []
assert has_provider_healthcheck == False
test: Update Provider Health Check sanity
See also: PSOBAT-2465
|
"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck
TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}
def test_provider_healthcheck():
"""Make sure default Provider Health Check works."""
health_checks = check_provider_healthcheck(settings=TEST_SETTINGS)
assert health_checks.providers == []
assert health_checks.has_healthcheck == False
|
<commit_before>"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck
TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}
def test_provider_healthcheck():
"""Make sure default Provider Health Check works."""
provider_healthcheck, has_provider_healthcheck = check_provider_healthcheck(settings=TEST_SETTINGS)
assert provider_healthcheck == []
assert has_provider_healthcheck == False
<commit_msg>test: Update Provider Health Check sanity
See also: PSOBAT-2465<commit_after>
|
"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck
TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}
def test_provider_healthcheck():
"""Make sure default Provider Health Check works."""
health_checks = check_provider_healthcheck(settings=TEST_SETTINGS)
assert health_checks.providers == []
assert health_checks.has_healthcheck == False
|
"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck
TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}
def test_provider_healthcheck():
"""Make sure default Provider Health Check works."""
provider_healthcheck, has_provider_healthcheck = check_provider_healthcheck(settings=TEST_SETTINGS)
assert provider_healthcheck == []
assert has_provider_healthcheck == False
test: Update Provider Health Check sanity
See also: PSOBAT-2465"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck
TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}
def test_provider_healthcheck():
"""Make sure default Provider Health Check works."""
health_checks = check_provider_healthcheck(settings=TEST_SETTINGS)
assert health_checks.providers == []
assert health_checks.has_healthcheck == False
|
<commit_before>"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck
TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}
def test_provider_healthcheck():
"""Make sure default Provider Health Check works."""
provider_healthcheck, has_provider_healthcheck = check_provider_healthcheck(settings=TEST_SETTINGS)
assert provider_healthcheck == []
assert has_provider_healthcheck == False
<commit_msg>test: Update Provider Health Check sanity
See also: PSOBAT-2465<commit_after>"""Test Provider Health Check setting."""
from foremast.pipeline.construct_pipeline_block import check_provider_healthcheck
TEST_SETTINGS = {'app': {'eureka_enabled': False}, 'asg': {'provider_healthcheck': {}}}
def test_provider_healthcheck():
"""Make sure default Provider Health Check works."""
health_checks = check_provider_healthcheck(settings=TEST_SETTINGS)
assert health_checks.providers == []
assert health_checks.has_healthcheck == False
|
976ca1d7f02a0aab7397a6eb1784436593e6c644
|
watchman/management/commands/watchman.py
|
watchman/management/commands/watchman.py
|
from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity == '2' or verbosity == '3'
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
self.stdout.write(resp)
|
from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity in ['2', '3', ]
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
self.stdout.write(resp)
|
Swap equality checks for `in`
|
Swap equality checks for `in`
|
Python
|
bsd-3-clause
|
mwarkentin/django-watchman,mwarkentin/django-watchman,JBKahn/django-watchman,JBKahn/django-watchman
|
from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity == '2' or verbosity == '3'
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
self.stdout.write(resp)
Swap equality checks for `in`
|
from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity in ['2', '3', ]
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
self.stdout.write(resp)
|
<commit_before>from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity == '2' or verbosity == '3'
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
self.stdout.write(resp)
<commit_msg>Swap equality checks for `in`<commit_after>
|
from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity in ['2', '3', ]
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
self.stdout.write(resp)
|
from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity == '2' or verbosity == '3'
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
self.stdout.write(resp)
Swap equality checks for `in`from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity in ['2', '3', ]
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
self.stdout.write(resp)
|
<commit_before>from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity == '2' or verbosity == '3'
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
self.stdout.write(resp)
<commit_msg>Swap equality checks for `in`<commit_after>from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (
make_option(
'-c',
'--checks',
dest='checks',
help='A comma-separated list of watchman checks to run (full python dotted paths)'
),
make_option(
'-s',
'--skips',
dest='skips',
help='A comma-separated list of watchman checks to skip (full python dotted paths)'
),
)
def handle(self, *args, **options):
check_list = None
skip_list = None
verbosity = options['verbosity']
print_all_checks = verbosity in ['2', '3', ]
checks = options['checks']
skips = options['skips']
if checks is not None:
check_list = checks.split(',')
if skips is not None:
skip_list = skips.split(',')
for check in get_checks(check_list=check_list, skip_list=skip_list):
if callable(check):
resp = json.dumps(check())
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
self.stdout.write(resp)
|
dfa92db8ba32a2209dacab04d9b14279f5f37f3d
|
core/scraper.py
|
core/scraper.py
|
from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
if 'LEC' in component_and_section or 'LAB' in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
return blocks
|
from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
for ctype in ['LEC', 'LAB', 'SEM']:
if ctype in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
break
return blocks
|
Support seminars in addition to lectures and labs
|
Support seminars in addition to lectures and labs
|
Python
|
mit
|
tuzhucheng/uw-course-alerter,tuzhucheng/uw-course-alerter,tuzhucheng/uw-course-alerter,tuzhucheng/uw-course-alerter
|
from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
if 'LEC' in component_and_section or 'LAB' in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
return blocks
Support seminars in addition to lectures and labs
|
from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
for ctype in ['LEC', 'LAB', 'SEM']:
if ctype in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
break
return blocks
|
<commit_before>from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
if 'LEC' in component_and_section or 'LAB' in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
return blocks
<commit_msg>Support seminars in addition to lectures and labs<commit_after>
|
from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
for ctype in ['LEC', 'LAB', 'SEM']:
if ctype in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
break
return blocks
|
from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
if 'LEC' in component_and_section or 'LAB' in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
return blocks
Support seminars in addition to lectures and labsfrom bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
for ctype in ['LEC', 'LAB', 'SEM']:
if ctype in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
break
return blocks
|
<commit_before>from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
if 'LEC' in component_and_section or 'LAB' in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
return blocks
<commit_msg>Support seminars in addition to lectures and labs<commit_after>from bs4 import BeautifulSoup
def extract_blocks(page):
soup = BeautifulSoup(page)
table_rows = soup.find_all('tr')
blocks = []
for i, row in enumerate(table_rows[4:-2]):
table_cells = row.find_all('td')
if table_cells:
component_and_section = table_cells[1].get_text().rstrip()
for ctype in ['LEC', 'LAB', 'SEM']:
if ctype in component_and_section:
component, section = component_and_section.split(' ')
block = {'component': component,
'section': section,
'enroll_cap': int(table_cells[6].get_text().rstrip()),
'enroll_total': int(table_cells[7].get_text().rstrip()),
'time': table_cells[10].get_text().rstrip(),
'room': table_cells[11].get_text().rstrip(),
'prof': table_cells[12].get_text().rstrip() if len(table_cells) > 12 else ''}
blocks.append(block)
break
return blocks
|
8f9d03ebf253ccf7b1aa5786c31c872b79076b81
|
PyOpenWorm/experiment.py
|
PyOpenWorm/experiment.py
|
from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
|
from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
if not hasattr(self, 'conditions'):
raise NotImplementedError(
'"Conditions" attribute must be overridden'
)
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
|
Raise error if conditions attribute unimplemented.
|
Raise error if conditions attribute unimplemented.
|
Python
|
mit
|
gsarma/PyOpenWorm,openworm/PyOpenWorm,gsarma/PyOpenWorm,openworm/PyOpenWorm
|
from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
Raise error if conditions attribute unimplemented.
|
from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
if not hasattr(self, 'conditions'):
raise NotImplementedError(
'"Conditions" attribute must be overridden'
)
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
|
<commit_before>from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
<commit_msg>Raise error if conditions attribute unimplemented.<commit_after>
|
from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
if not hasattr(self, 'conditions'):
raise NotImplementedError(
'"Conditions" attribute must be overridden'
)
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
|
from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
Raise error if conditions attribute unimplemented.from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
if not hasattr(self, 'conditions'):
raise NotImplementedError(
'"Conditions" attribute must be overridden'
)
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
|
<commit_before>from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
<commit_msg>Raise error if conditions attribute unimplemented.<commit_after>from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
if not hasattr(self, 'conditions'):
raise NotImplementedError(
'"Conditions" attribute must be overridden'
)
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
|
8b3c438b3f5fb9b2538a30182dd4f5d306aa098b
|
ankieta/contact/forms.py
|
ankieta/contact/forms.py
|
from django import forms
from django.core.mail import mail_managers
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Contact
class ContactForm(forms.Form):
personsList = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
mail_managers(self.cleaned_data['topic'], self.get_text())
|
from django import forms
from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.conf import settings
from .models import Contact
def my_mail_send(subject, recipient, message):
subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
from_email = settings.SERVER_EMAIL
return send_mail(subject, message, from_email, [recipient])
class ContactForm(forms.Form):
recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
my_mail_send(subject=self.cleaned_data['topic'],
recipient=self.cleaned_data['recipient'].email,
message=self.get_text())
|
Fix contact form - send to recipient, not managers
|
Fix contact form - send to recipient, not managers
|
Python
|
bsd-3-clause
|
watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl
|
from django import forms
from django.core.mail import mail_managers
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Contact
class ContactForm(forms.Form):
personsList = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
mail_managers(self.cleaned_data['topic'], self.get_text())
Fix contact form - send to recipient, not managers
|
from django import forms
from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.conf import settings
from .models import Contact
def my_mail_send(subject, recipient, message):
subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
from_email = settings.SERVER_EMAIL
return send_mail(subject, message, from_email, [recipient])
class ContactForm(forms.Form):
recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
my_mail_send(subject=self.cleaned_data['topic'],
recipient=self.cleaned_data['recipient'].email,
message=self.get_text())
|
<commit_before>from django import forms
from django.core.mail import mail_managers
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Contact
class ContactForm(forms.Form):
personsList = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
mail_managers(self.cleaned_data['topic'], self.get_text())
<commit_msg>Fix contact form - send to recipient, not managers<commit_after>
|
from django import forms
from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.conf import settings
from .models import Contact
def my_mail_send(subject, recipient, message):
subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
from_email = settings.SERVER_EMAIL
return send_mail(subject, message, from_email, [recipient])
class ContactForm(forms.Form):
recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
my_mail_send(subject=self.cleaned_data['topic'],
recipient=self.cleaned_data['recipient'].email,
message=self.get_text())
|
from django import forms
from django.core.mail import mail_managers
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Contact
class ContactForm(forms.Form):
personsList = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
mail_managers(self.cleaned_data['topic'], self.get_text())
Fix contact form - send to recipient, not managersfrom django import forms
from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.conf import settings
from .models import Contact
def my_mail_send(subject, recipient, message):
subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
from_email = settings.SERVER_EMAIL
return send_mail(subject, message, from_email, [recipient])
class ContactForm(forms.Form):
recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
my_mail_send(subject=self.cleaned_data['topic'],
recipient=self.cleaned_data['recipient'].email,
message=self.get_text())
|
<commit_before>from django import forms
from django.core.mail import mail_managers
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Contact
class ContactForm(forms.Form):
personsList = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
mail_managers(self.cleaned_data['topic'], self.get_text())
<commit_msg>Fix contact form - send to recipient, not managers<commit_after>from django import forms
from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.conf import settings
from .models import Contact
def my_mail_send(subject, recipient, message):
subject = '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
from_email = settings.SERVER_EMAIL
return send_mail(subject, message, from_email, [recipient])
class ContactForm(forms.Form):
recipient = forms.ModelChoiceField(required=True, label=_("Contact person"),
queryset=Contact.objects.all())
topic = forms.CharField(required=True, max_length=150,
label=_("Topic of messages"))
body = forms.CharField(required=True, widget=forms.Textarea(), label=_("Content"))
email = forms.EmailField(required=True, label=_("E-mail"))
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('contact:form')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Send'), css_class="btn-lg btn-block"))
def get_text(self):
return "%(body)s \n\nE-mail: %(email)s" % self.cleaned_data
def send(self):
my_mail_send(subject=self.cleaned_data['topic'],
recipient=self.cleaned_data['recipient'].email,
message=self.get_text())
|
aa6da3aa2b7d4781ec0c3d94ea68c11d75b76506
|
bonobo/structs/graphs.py
|
bonobo/structs/graphs.py
|
from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
def __len__(self):
return len(self.nodes)
|
from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN, _output=None):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
if _output:
if not _output in self.nodes:
raise ValueError('Output not found.')
self.outputs_of(_input, create=True).add(self.nodes.index(_output))
return self
def __len__(self):
return len(self.nodes)
|
Allow to specify output of a chain in the Graph class.
|
Allow to specify output of a chain in the Graph class.
|
Python
|
apache-2.0
|
hartym/bonobo,hartym/bonobo,hartym/bonobo,python-bonobo/bonobo,python-bonobo/bonobo,python-bonobo/bonobo
|
from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
def __len__(self):
return len(self.nodes)
Allow to specify output of a chain in the Graph class.
|
from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN, _output=None):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
if _output:
if not _output in self.nodes:
raise ValueError('Output not found.')
self.outputs_of(_input, create=True).add(self.nodes.index(_output))
return self
def __len__(self):
return len(self.nodes)
|
<commit_before>from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
def __len__(self):
return len(self.nodes)
<commit_msg>Allow to specify output of a chain in the Graph class.<commit_after>
|
from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN, _output=None):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
if _output:
if not _output in self.nodes:
raise ValueError('Output not found.')
self.outputs_of(_input, create=True).add(self.nodes.index(_output))
return self
def __len__(self):
return len(self.nodes)
|
from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
def __len__(self):
return len(self.nodes)
Allow to specify output of a chain in the Graph class.from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN, _output=None):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
if _output:
if not _output in self.nodes:
raise ValueError('Output not found.')
self.outputs_of(_input, create=True).add(self.nodes.index(_output))
return self
def __len__(self):
return len(self.nodes)
|
<commit_before>from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
def __len__(self):
return len(self.nodes)
<commit_msg>Allow to specify output of a chain in the Graph class.<commit_after>from bonobo.constants import BEGIN
class Graph:
"""
Represents a coherent directed acyclic graph of components.
"""
def __init__(self, *chain):
self.nodes = []
self.graph = {BEGIN: set()}
self.add_chain(*chain)
def outputs_of(self, idx, create=False):
if create and not idx in self.graph:
self.graph[idx] = set()
return self.graph[idx]
def add_node(self, c):
i = len(self.nodes)
self.nodes.append(c)
return i
def add_chain(self, *nodes, _input=BEGIN, _output=None):
for node in nodes:
_next = self.add_node(node)
self.outputs_of(_input, create=True).add(_next)
_input = _next
if _output:
if not _output in self.nodes:
raise ValueError('Output not found.')
self.outputs_of(_input, create=True).add(self.nodes.index(_output))
return self
def __len__(self):
return len(self.nodes)
|
58eaaeca980d8ec92d77c201aa01d5c46cf761dd
|
neuroshare/NeuralEntity.py
|
neuroshare/NeuralEntity.py
|
from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[**Optional**] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``inde`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
|
from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[*Optional*] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
"""[*Optional*] unit id used in the source entity
(cf. :func:`source_entity_id`)"""
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``index`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
|
Update Neural Entity (now complete)
|
doc: Update Neural Entity (now complete)
|
Python
|
lgpl-2.1
|
abhay447/python-neuroshare,G-Node/python-neuroshare,G-Node/python-neuroshare,abhay447/python-neuroshare
|
from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[**Optional**] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``inde`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
doc: Update Neural Entity (now complete)
|
from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[*Optional*] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
"""[*Optional*] unit id used in the source entity
(cf. :func:`source_entity_id`)"""
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``index`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
|
<commit_before>from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[**Optional**] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``inde`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
<commit_msg>doc: Update Neural Entity (now complete)<commit_after>
|
from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[*Optional*] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
"""[*Optional*] unit id used in the source entity
(cf. :func:`source_entity_id`)"""
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``index`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
|
from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[**Optional**] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``inde`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
doc: Update Neural Entity (now complete)from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[*Optional*] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
"""[*Optional*] unit id used in the source entity
(cf. :func:`source_entity_id`)"""
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``index`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
|
<commit_before>from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[**Optional**] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``inde`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
<commit_msg>doc: Update Neural Entity (now complete)<commit_after>from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[*Optional*] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
"""[*Optional*] unit id used in the source entity
(cf. :func:`source_entity_id`)"""
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``index`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
|
cef45980266463a49a76466d858a3eaab99fc377
|
flexget/plugins/module_change_warn.py
|
flexget/plugins/module_change_warn.py
|
import logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_database(self, feed, reason=''):
log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason)
feed.manager.disable_feeds()
feed.abort()
def on_process_start(self, feed):
config = feed.manager.config
# prevent useless keywords in root level
allow = ['feeds', 'presets']
for key in config.iterkeys():
if key not in allow:
log.critical('Keyword \'%s\' is not allowed in the root level!' % key)
session = Session()
# database changes
from flexget.utils.sqlalchemy_utils import table_columns, table_exists
columns = table_columns('imdb_movies', session)
if not 'photo' in columns:
self.old_database(feed, '(photo missing from imdb_movies table)')
columns = table_columns('make_rss', session)
if not 'rsslink' in columns:
self.old_database(feed, '(rsslink missing from make_rss table)')
if table_exists('episode_qualities', session):
self.old_database(feed, '(old series format)')
session.close()
register_plugin(ChangeWarn, 'change_warn', builtin=True)
|
import logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_database(self, feed, reason=''):
log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason)
feed.manager.disable_feeds()
feed.abort()
def on_process_start(self, feed):
config = feed.manager.config
# prevent useless keywords in root level
allow = ['feeds', 'presets', 'variables']
for key in config.iterkeys():
if key not in allow:
log.critical('Keyword \'%s\' is not allowed in the root level!' % key)
session = Session()
# database changes
from flexget.utils.sqlalchemy_utils import table_columns, table_exists
columns = table_columns('imdb_movies', session)
if not 'photo' in columns:
self.old_database(feed, '(photo missing from imdb_movies table)')
columns = table_columns('make_rss', session)
if not 'rsslink' in columns:
self.old_database(feed, '(rsslink missing from make_rss table)')
if table_exists('episode_qualities', session):
self.old_database(feed, '(old series format)')
session.close()
register_plugin(ChangeWarn, 'change_warn', builtin=True)
|
Allow variables at root level for yaml definitions.
|
Allow variables at root level for yaml definitions.
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1062 3942dd89-8c5d-46d7-aeed-044bccf3e60c
|
Python
|
mit
|
jacobmetrick/Flexget,Danfocus/Flexget,X-dark/Flexget,X-dark/Flexget,offbyone/Flexget,poulpito/Flexget,gazpachoking/Flexget,lildadou/Flexget,malkavi/Flexget,v17al/Flexget,ZefQ/Flexget,crawln45/Flexget,ratoaq2/Flexget,malkavi/Flexget,antivirtel/Flexget,camon/Flexget,Pretagonist/Flexget,Pretagonist/Flexget,crawln45/Flexget,spencerjanssen/Flexget,voriux/Flexget,patsissons/Flexget,spencerjanssen/Flexget,qk4l/Flexget,jacobmetrick/Flexget,oxc/Flexget,cvium/Flexget,dsemi/Flexget,jawilson/Flexget,ianstalk/Flexget,drwyrm/Flexget,thalamus/Flexget,gazpachoking/Flexget,Danfocus/Flexget,ibrahimkarahan/Flexget,qk4l/Flexget,antivirtel/Flexget,camon/Flexget,sean797/Flexget,malkavi/Flexget,lildadou/Flexget,tobinjt/Flexget,jacobmetrick/Flexget,vfrc2/Flexget,drwyrm/Flexget,sean797/Flexget,malkavi/Flexget,tarzasai/Flexget,tvcsantos/Flexget,crawln45/Flexget,drwyrm/Flexget,oxc/Flexget,asm0dey/Flexget,spencerjanssen/Flexget,patsissons/Flexget,grrr2/Flexget,Pretagonist/Flexget,thalamus/Flexget,asm0dey/Flexget,tsnoam/Flexget,antivirtel/Flexget,jawilson/Flexget,sean797/Flexget,ratoaq2/Flexget,dsemi/Flexget,Flexget/Flexget,tarzasai/Flexget,jawilson/Flexget,patsissons/Flexget,oxc/Flexget,Flexget/Flexget,xfouloux/Flexget,offbyone/Flexget,LynxyssCZ/Flexget,ibrahimkarahan/Flexget,v17al/Flexget,poulpito/Flexget,qvazzler/Flexget,ibrahimkarahan/Flexget,thalamus/Flexget,vfrc2/Flexget,LynxyssCZ/Flexget,cvium/Flexget,Danfocus/Flexget,Danfocus/Flexget,crawln45/Flexget,v17al/Flexget,Flexget/Flexget,grrr2/Flexget,OmgOhnoes/Flexget,JorisDeRieck/Flexget,xfouloux/Flexget,tobinjt/Flexget,xfouloux/Flexget,LynxyssCZ/Flexget,tvcsantos/Flexget,qvazzler/Flexget,tsnoam/Flexget,ratoaq2/Flexget,LynxyssCZ/Flexget,JorisDeRieck/Flexget,tobinjt/Flexget,tarzasai/Flexget,qk4l/Flexget,cvium/Flexget,qvazzler/Flexget,OmgOhnoes/Flexget,tsnoam/Flexget,ianstalk/Flexget,poulpito/Flexget,lildadou/Flexget,JorisDeRieck/Flexget,vfrc2/Flexget,OmgOhnoes/Flexget,grrr2/Flexget,ianstalk/Flexget,offbyone/Flexget,voriux/Flexget,Flexget/Flexget,dsemi/Flexget,JorisDeRieck/Flexget,ZefQ/Flexget,jawilson/Flexget,X-dark/Flexget,tobinjt/Flexget,asm0dey/Flexget,ZefQ/Flexget
|
import logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_database(self, feed, reason=''):
log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason)
feed.manager.disable_feeds()
feed.abort()
def on_process_start(self, feed):
config = feed.manager.config
# prevent useless keywords in root level
allow = ['feeds', 'presets']
for key in config.iterkeys():
if key not in allow:
log.critical('Keyword \'%s\' is not allowed in the root level!' % key)
session = Session()
# database changes
from flexget.utils.sqlalchemy_utils import table_columns, table_exists
columns = table_columns('imdb_movies', session)
if not 'photo' in columns:
self.old_database(feed, '(photo missing from imdb_movies table)')
columns = table_columns('make_rss', session)
if not 'rsslink' in columns:
self.old_database(feed, '(rsslink missing from make_rss table)')
if table_exists('episode_qualities', session):
self.old_database(feed, '(old series format)')
session.close()
register_plugin(ChangeWarn, 'change_warn', builtin=True)
Allow variables at root level for yaml definitions.
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1062 3942dd89-8c5d-46d7-aeed-044bccf3e60c
|
import logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_database(self, feed, reason=''):
log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason)
feed.manager.disable_feeds()
feed.abort()
def on_process_start(self, feed):
config = feed.manager.config
# prevent useless keywords in root level
allow = ['feeds', 'presets', 'variables']
for key in config.iterkeys():
if key not in allow:
log.critical('Keyword \'%s\' is not allowed in the root level!' % key)
session = Session()
# database changes
from flexget.utils.sqlalchemy_utils import table_columns, table_exists
columns = table_columns('imdb_movies', session)
if not 'photo' in columns:
self.old_database(feed, '(photo missing from imdb_movies table)')
columns = table_columns('make_rss', session)
if not 'rsslink' in columns:
self.old_database(feed, '(rsslink missing from make_rss table)')
if table_exists('episode_qualities', session):
self.old_database(feed, '(old series format)')
session.close()
register_plugin(ChangeWarn, 'change_warn', builtin=True)
|
<commit_before>import logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_database(self, feed, reason=''):
log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason)
feed.manager.disable_feeds()
feed.abort()
def on_process_start(self, feed):
config = feed.manager.config
# prevent useless keywords in root level
allow = ['feeds', 'presets']
for key in config.iterkeys():
if key not in allow:
log.critical('Keyword \'%s\' is not allowed in the root level!' % key)
session = Session()
# database changes
from flexget.utils.sqlalchemy_utils import table_columns, table_exists
columns = table_columns('imdb_movies', session)
if not 'photo' in columns:
self.old_database(feed, '(photo missing from imdb_movies table)')
columns = table_columns('make_rss', session)
if not 'rsslink' in columns:
self.old_database(feed, '(rsslink missing from make_rss table)')
if table_exists('episode_qualities', session):
self.old_database(feed, '(old series format)')
session.close()
register_plugin(ChangeWarn, 'change_warn', builtin=True)
<commit_msg>Allow variables at root level for yaml definitions.
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1062 3942dd89-8c5d-46d7-aeed-044bccf3e60c<commit_after>
|
import logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_database(self, feed, reason=''):
log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason)
feed.manager.disable_feeds()
feed.abort()
def on_process_start(self, feed):
config = feed.manager.config
# prevent useless keywords in root level
allow = ['feeds', 'presets', 'variables']
for key in config.iterkeys():
if key not in allow:
log.critical('Keyword \'%s\' is not allowed in the root level!' % key)
session = Session()
# database changes
from flexget.utils.sqlalchemy_utils import table_columns, table_exists
columns = table_columns('imdb_movies', session)
if not 'photo' in columns:
self.old_database(feed, '(photo missing from imdb_movies table)')
columns = table_columns('make_rss', session)
if not 'rsslink' in columns:
self.old_database(feed, '(rsslink missing from make_rss table)')
if table_exists('episode_qualities', session):
self.old_database(feed, '(old series format)')
session.close()
register_plugin(ChangeWarn, 'change_warn', builtin=True)
|
import logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_database(self, feed, reason=''):
log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason)
feed.manager.disable_feeds()
feed.abort()
def on_process_start(self, feed):
config = feed.manager.config
# prevent useless keywords in root level
allow = ['feeds', 'presets']
for key in config.iterkeys():
if key not in allow:
log.critical('Keyword \'%s\' is not allowed in the root level!' % key)
session = Session()
# database changes
from flexget.utils.sqlalchemy_utils import table_columns, table_exists
columns = table_columns('imdb_movies', session)
if not 'photo' in columns:
self.old_database(feed, '(photo missing from imdb_movies table)')
columns = table_columns('make_rss', session)
if not 'rsslink' in columns:
self.old_database(feed, '(rsslink missing from make_rss table)')
if table_exists('episode_qualities', session):
self.old_database(feed, '(old series format)')
session.close()
register_plugin(ChangeWarn, 'change_warn', builtin=True)
Allow variables at root level for yaml definitions.
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1062 3942dd89-8c5d-46d7-aeed-044bccf3e60cimport logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_database(self, feed, reason=''):
log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason)
feed.manager.disable_feeds()
feed.abort()
def on_process_start(self, feed):
config = feed.manager.config
# prevent useless keywords in root level
allow = ['feeds', 'presets', 'variables']
for key in config.iterkeys():
if key not in allow:
log.critical('Keyword \'%s\' is not allowed in the root level!' % key)
session = Session()
# database changes
from flexget.utils.sqlalchemy_utils import table_columns, table_exists
columns = table_columns('imdb_movies', session)
if not 'photo' in columns:
self.old_database(feed, '(photo missing from imdb_movies table)')
columns = table_columns('make_rss', session)
if not 'rsslink' in columns:
self.old_database(feed, '(rsslink missing from make_rss table)')
if table_exists('episode_qualities', session):
self.old_database(feed, '(old series format)')
session.close()
register_plugin(ChangeWarn, 'change_warn', builtin=True)
|
<commit_before>import logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_database(self, feed, reason=''):
log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason)
feed.manager.disable_feeds()
feed.abort()
def on_process_start(self, feed):
config = feed.manager.config
# prevent useless keywords in root level
allow = ['feeds', 'presets']
for key in config.iterkeys():
if key not in allow:
log.critical('Keyword \'%s\' is not allowed in the root level!' % key)
session = Session()
# database changes
from flexget.utils.sqlalchemy_utils import table_columns, table_exists
columns = table_columns('imdb_movies', session)
if not 'photo' in columns:
self.old_database(feed, '(photo missing from imdb_movies table)')
columns = table_columns('make_rss', session)
if not 'rsslink' in columns:
self.old_database(feed, '(rsslink missing from make_rss table)')
if table_exists('episode_qualities', session):
self.old_database(feed, '(old series format)')
session.close()
register_plugin(ChangeWarn, 'change_warn', builtin=True)
<commit_msg>Allow variables at root level for yaml definitions.
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1062 3942dd89-8c5d-46d7-aeed-044bccf3e60c<commit_after>import logging
from flexget.manager import Session
from flexget.plugin import *
log = logging.getLogger('change')
class ChangeWarn:
"""
Gives warning if user has deprecated / changed configuration in the root level.
Will be replaced by root level validation in the future!
"""
def old_database(self, feed, reason=''):
log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason)
feed.manager.disable_feeds()
feed.abort()
def on_process_start(self, feed):
config = feed.manager.config
# prevent useless keywords in root level
allow = ['feeds', 'presets', 'variables']
for key in config.iterkeys():
if key not in allow:
log.critical('Keyword \'%s\' is not allowed in the root level!' % key)
session = Session()
# database changes
from flexget.utils.sqlalchemy_utils import table_columns, table_exists
columns = table_columns('imdb_movies', session)
if not 'photo' in columns:
self.old_database(feed, '(photo missing from imdb_movies table)')
columns = table_columns('make_rss', session)
if not 'rsslink' in columns:
self.old_database(feed, '(rsslink missing from make_rss table)')
if table_exists('episode_qualities', session):
self.old_database(feed, '(old series format)')
session.close()
register_plugin(ChangeWarn, 'change_warn', builtin=True)
|
d8fa29ee920984d0ae7ae94bc2fd09cde20b2b25
|
HOME/bin/lib/setup/__init__.py
|
HOME/bin/lib/setup/__init__.py
|
from pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
HOME_DIR = 'HOME'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
# this file is under HOME_DIR, which is directly under the repo root
path = Path(__file__).resolve() # resolve symlinks (~/bin=setup/HOME/bin)
return path.parents[path.parts[::-1].index(HOME_DIR)]
def home():
return root() / HOME_DIR
def home_path(path):
"""Get the path within setup's HOME for the given path
Note: no valid setup path for anything outside of $HOME, so throws exception
"""
return home() / Path(path).resolve().relative_to(Path.home())
|
from pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
HOME_DIR = 'HOME'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
"""Return the path of the root of this setup repository."""
# this file is under HOME_DIR. HOME_DIR's parent is the root.
# So search backwards for HOME_DIR and get its parent.
path = Path(__file__).resolve() # resolve symlinks (~/bin=setup/HOME/bin)
return path.parents[path.parts[::-1].index(HOME_DIR)]
def home():
return root() / HOME_DIR
def home_path(path):
"""Get the path within setup's HOME for the given path
Note: no valid setup path for anything outside of $HOME, so throws exception
"""
return home() / Path(path).resolve().relative_to(Path.home())
|
Improve comment in setup module
|
Improve comment in setup module
|
Python
|
mit
|
kbd/setup,kbd/setup,kbd/setup,kbd/setup,kbd/setup
|
from pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
HOME_DIR = 'HOME'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
# this file is under HOME_DIR, which is directly under the repo root
path = Path(__file__).resolve() # resolve symlinks (~/bin=setup/HOME/bin)
return path.parents[path.parts[::-1].index(HOME_DIR)]
def home():
return root() / HOME_DIR
def home_path(path):
"""Get the path within setup's HOME for the given path
Note: no valid setup path for anything outside of $HOME, so throws exception
"""
return home() / Path(path).resolve().relative_to(Path.home())
Improve comment in setup module
|
from pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
HOME_DIR = 'HOME'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
"""Return the path of the root of this setup repository."""
# this file is under HOME_DIR. HOME_DIR's parent is the root.
# So search backwards for HOME_DIR and get its parent.
path = Path(__file__).resolve() # resolve symlinks (~/bin=setup/HOME/bin)
return path.parents[path.parts[::-1].index(HOME_DIR)]
def home():
return root() / HOME_DIR
def home_path(path):
"""Get the path within setup's HOME for the given path
Note: no valid setup path for anything outside of $HOME, so throws exception
"""
return home() / Path(path).resolve().relative_to(Path.home())
|
<commit_before>from pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
HOME_DIR = 'HOME'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
# this file is under HOME_DIR, which is directly under the repo root
path = Path(__file__).resolve() # resolve symlinks (~/bin=setup/HOME/bin)
return path.parents[path.parts[::-1].index(HOME_DIR)]
def home():
return root() / HOME_DIR
def home_path(path):
"""Get the path within setup's HOME for the given path
Note: no valid setup path for anything outside of $HOME, so throws exception
"""
return home() / Path(path).resolve().relative_to(Path.home())
<commit_msg>Improve comment in setup module<commit_after>
|
from pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
HOME_DIR = 'HOME'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
"""Return the path of the root of this setup repository."""
# this file is under HOME_DIR. HOME_DIR's parent is the root.
# So search backwards for HOME_DIR and get its parent.
path = Path(__file__).resolve() # resolve symlinks (~/bin=setup/HOME/bin)
return path.parents[path.parts[::-1].index(HOME_DIR)]
def home():
return root() / HOME_DIR
def home_path(path):
"""Get the path within setup's HOME for the given path
Note: no valid setup path for anything outside of $HOME, so throws exception
"""
return home() / Path(path).resolve().relative_to(Path.home())
|
from pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
HOME_DIR = 'HOME'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
# this file is under HOME_DIR, which is directly under the repo root
path = Path(__file__).resolve() # resolve symlinks (~/bin=setup/HOME/bin)
return path.parents[path.parts[::-1].index(HOME_DIR)]
def home():
return root() / HOME_DIR
def home_path(path):
"""Get the path within setup's HOME for the given path
Note: no valid setup path for anything outside of $HOME, so throws exception
"""
return home() / Path(path).resolve().relative_to(Path.home())
Improve comment in setup modulefrom pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
HOME_DIR = 'HOME'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
"""Return the path of the root of this setup repository."""
# this file is under HOME_DIR. HOME_DIR's parent is the root.
# So search backwards for HOME_DIR and get its parent.
path = Path(__file__).resolve() # resolve symlinks (~/bin=setup/HOME/bin)
return path.parents[path.parts[::-1].index(HOME_DIR)]
def home():
return root() / HOME_DIR
def home_path(path):
"""Get the path within setup's HOME for the given path
Note: no valid setup path for anything outside of $HOME, so throws exception
"""
return home() / Path(path).resolve().relative_to(Path.home())
|
<commit_before>from pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
HOME_DIR = 'HOME'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
# this file is under HOME_DIR, which is directly under the repo root
path = Path(__file__).resolve() # resolve symlinks (~/bin=setup/HOME/bin)
return path.parents[path.parts[::-1].index(HOME_DIR)]
def home():
return root() / HOME_DIR
def home_path(path):
"""Get the path within setup's HOME for the given path
Note: no valid setup path for anything outside of $HOME, so throws exception
"""
return home() / Path(path).resolve().relative_to(Path.home())
<commit_msg>Improve comment in setup module<commit_after>from pathlib import Path
SETTINGS_PATH = 'conf/settings.py'
PARTIALS_PATH = 'conf/partials.txt'
HOME_DIR = 'HOME'
def load_config(path=SETTINGS_PATH):
settings = eval(open(path).read())
return settings
def root():
"""Return the path of the root of this setup repository."""
# this file is under HOME_DIR. HOME_DIR's parent is the root.
# So search backwards for HOME_DIR and get its parent.
path = Path(__file__).resolve() # resolve symlinks (~/bin=setup/HOME/bin)
return path.parents[path.parts[::-1].index(HOME_DIR)]
def home():
return root() / HOME_DIR
def home_path(path):
"""Get the path within setup's HOME for the given path
Note: no valid setup path for anything outside of $HOME, so throws exception
"""
return home() / Path(path).resolve().relative_to(Path.home())
|
931758154d44c9b0e0cf5d049367ffddfdae28b1
|
external_tools/src/main/python/images/PropertiesParser.py
|
external_tools/src/main/python/images/PropertiesParser.py
|
# -*- coding: utf-8 -*-
import ConfigParser
import logging
class PropertiesParser(object):
"""Parse a java like properties file
Parser wrapping around ConfigParser allowing reading of java like
properties file. Based on stackoverflow example:
https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788
Example usage
-------------
>>> pp = PropertiesParser()
>>> props = pp.parse('/home/kola/configfiles/dev/application.properties')
>>> print props
"""
def __init__(self):
self.secheadname = 'fakeSectionHead'
self.sechead = '[' + self.secheadname + ']\n'
self.logger = logging.getLogger(__name__)
def readline(self):
if self.sechead:
try:
return self.sechead
finally:
self.sechead = None
else:
return self.fp.readline()
def parse(self, filepath):
"""Parse file containing java like properties."""
try:
self.fp = open(filepath)
cp = ConfigParser.SafeConfigParser()
cp.readfp(self)
self.fp.close()
# reset the section head incase the parser will be used again
self.sechead = '[' + self.secheadname + ']\n'
return cp.items(self.secheadname)
except Exception as e:
self.logger.error("Problem parsing " + filepath + ". Error message: " + str(e))
return {}
|
# -*- coding: utf-8 -*-
import ConfigParser
import logging
class PropertiesParser(object):
"""Parse a java like properties file
Parser wrapping around ConfigParser allowing reading of java like
properties file. Based on stackoverflow example:
https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788
Example usage
-------------
>>> pp = PropertiesParser()
>>> props = pp.parse('/home/kola/configfiles/dev/application.properties')
>>> print props
"""
def __init__(self):
self.secheadname = 'fakeSectionHead'
self.sechead = '[' + self.secheadname + ']\n'
#self.logger = logging.getLogger(__name__)
def readline(self):
if self.sechead:
try:
return self.sechead
finally:
self.sechead = None
else:
return self.fp.readline()
def parse(self, filepath):
"""Parse file containing java like properties."""
try:
self.fp = open(filepath)
cp = ConfigParser.SafeConfigParser()
cp.readfp(self)
self.fp.close()
# reset the section head incase the parser will be used again
self.sechead = '[' + self.secheadname + ']\n'
return cp.items(self.secheadname)
except Exception as e:
#self.logger.error("Problem parsing " + filepath + ". Error message: " + str(e))
print "Problem parsing " + filepath + ". Error message: " + str(e)
return {}
|
Change logging to use print because of logger configuration error
|
Change logging to use print because of logger configuration error
|
Python
|
apache-2.0
|
mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData
|
# -*- coding: utf-8 -*-
import ConfigParser
import logging
class PropertiesParser(object):
"""Parse a java like properties file
Parser wrapping around ConfigParser allowing reading of java like
properties file. Based on stackoverflow example:
https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788
Example usage
-------------
>>> pp = PropertiesParser()
>>> props = pp.parse('/home/kola/configfiles/dev/application.properties')
>>> print props
"""
def __init__(self):
self.secheadname = 'fakeSectionHead'
self.sechead = '[' + self.secheadname + ']\n'
self.logger = logging.getLogger(__name__)
def readline(self):
if self.sechead:
try:
return self.sechead
finally:
self.sechead = None
else:
return self.fp.readline()
def parse(self, filepath):
"""Parse file containing java like properties."""
try:
self.fp = open(filepath)
cp = ConfigParser.SafeConfigParser()
cp.readfp(self)
self.fp.close()
# reset the section head incase the parser will be used again
self.sechead = '[' + self.secheadname + ']\n'
return cp.items(self.secheadname)
except Exception as e:
self.logger.error("Problem parsing " + filepath + ". Error message: " + str(e))
return {}
Change logging to use print because of logger configuration error
|
# -*- coding: utf-8 -*-
import ConfigParser
import logging
class PropertiesParser(object):
"""Parse a java like properties file
Parser wrapping around ConfigParser allowing reading of java like
properties file. Based on stackoverflow example:
https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788
Example usage
-------------
>>> pp = PropertiesParser()
>>> props = pp.parse('/home/kola/configfiles/dev/application.properties')
>>> print props
"""
def __init__(self):
self.secheadname = 'fakeSectionHead'
self.sechead = '[' + self.secheadname + ']\n'
#self.logger = logging.getLogger(__name__)
def readline(self):
if self.sechead:
try:
return self.sechead
finally:
self.sechead = None
else:
return self.fp.readline()
def parse(self, filepath):
"""Parse file containing java like properties."""
try:
self.fp = open(filepath)
cp = ConfigParser.SafeConfigParser()
cp.readfp(self)
self.fp.close()
# reset the section head incase the parser will be used again
self.sechead = '[' + self.secheadname + ']\n'
return cp.items(self.secheadname)
except Exception as e:
#self.logger.error("Problem parsing " + filepath + ". Error message: " + str(e))
print "Problem parsing " + filepath + ". Error message: " + str(e)
return {}
|
<commit_before># -*- coding: utf-8 -*-
import ConfigParser
import logging
class PropertiesParser(object):
"""Parse a java like properties file
Parser wrapping around ConfigParser allowing reading of java like
properties file. Based on stackoverflow example:
https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788
Example usage
-------------
>>> pp = PropertiesParser()
>>> props = pp.parse('/home/kola/configfiles/dev/application.properties')
>>> print props
"""
def __init__(self):
self.secheadname = 'fakeSectionHead'
self.sechead = '[' + self.secheadname + ']\n'
self.logger = logging.getLogger(__name__)
def readline(self):
if self.sechead:
try:
return self.sechead
finally:
self.sechead = None
else:
return self.fp.readline()
def parse(self, filepath):
"""Parse file containing java like properties."""
try:
self.fp = open(filepath)
cp = ConfigParser.SafeConfigParser()
cp.readfp(self)
self.fp.close()
# reset the section head incase the parser will be used again
self.sechead = '[' + self.secheadname + ']\n'
return cp.items(self.secheadname)
except Exception as e:
self.logger.error("Problem parsing " + filepath + ". Error message: " + str(e))
return {}
<commit_msg>Change logging to use print because of logger configuration error<commit_after>
|
# -*- coding: utf-8 -*-
import ConfigParser
import logging
class PropertiesParser(object):
"""Parse a java like properties file
Parser wrapping around ConfigParser allowing reading of java like
properties file. Based on stackoverflow example:
https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788
Example usage
-------------
>>> pp = PropertiesParser()
>>> props = pp.parse('/home/kola/configfiles/dev/application.properties')
>>> print props
"""
def __init__(self):
self.secheadname = 'fakeSectionHead'
self.sechead = '[' + self.secheadname + ']\n'
#self.logger = logging.getLogger(__name__)
def readline(self):
if self.sechead:
try:
return self.sechead
finally:
self.sechead = None
else:
return self.fp.readline()
def parse(self, filepath):
"""Parse file containing java like properties."""
try:
self.fp = open(filepath)
cp = ConfigParser.SafeConfigParser()
cp.readfp(self)
self.fp.close()
# reset the section head incase the parser will be used again
self.sechead = '[' + self.secheadname + ']\n'
return cp.items(self.secheadname)
except Exception as e:
#self.logger.error("Problem parsing " + filepath + ". Error message: " + str(e))
print "Problem parsing " + filepath + ". Error message: " + str(e)
return {}
|
# -*- coding: utf-8 -*-
import ConfigParser
import logging
class PropertiesParser(object):
"""Parse a java like properties file
Parser wrapping around ConfigParser allowing reading of java like
properties file. Based on stackoverflow example:
https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788
Example usage
-------------
>>> pp = PropertiesParser()
>>> props = pp.parse('/home/kola/configfiles/dev/application.properties')
>>> print props
"""
def __init__(self):
self.secheadname = 'fakeSectionHead'
self.sechead = '[' + self.secheadname + ']\n'
self.logger = logging.getLogger(__name__)
def readline(self):
if self.sechead:
try:
return self.sechead
finally:
self.sechead = None
else:
return self.fp.readline()
def parse(self, filepath):
"""Parse file containing java like properties."""
try:
self.fp = open(filepath)
cp = ConfigParser.SafeConfigParser()
cp.readfp(self)
self.fp.close()
# reset the section head incase the parser will be used again
self.sechead = '[' + self.secheadname + ']\n'
return cp.items(self.secheadname)
except Exception as e:
self.logger.error("Problem parsing " + filepath + ". Error message: " + str(e))
return {}
Change logging to use print because of logger configuration error# -*- coding: utf-8 -*-
import ConfigParser
import logging
class PropertiesParser(object):
"""Parse a java like properties file
Parser wrapping around ConfigParser allowing reading of java like
properties file. Based on stackoverflow example:
https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788
Example usage
-------------
>>> pp = PropertiesParser()
>>> props = pp.parse('/home/kola/configfiles/dev/application.properties')
>>> print props
"""
def __init__(self):
self.secheadname = 'fakeSectionHead'
self.sechead = '[' + self.secheadname + ']\n'
#self.logger = logging.getLogger(__name__)
def readline(self):
if self.sechead:
try:
return self.sechead
finally:
self.sechead = None
else:
return self.fp.readline()
def parse(self, filepath):
"""Parse file containing java like properties."""
try:
self.fp = open(filepath)
cp = ConfigParser.SafeConfigParser()
cp.readfp(self)
self.fp.close()
# reset the section head incase the parser will be used again
self.sechead = '[' + self.secheadname + ']\n'
return cp.items(self.secheadname)
except Exception as e:
#self.logger.error("Problem parsing " + filepath + ". Error message: " + str(e))
print "Problem parsing " + filepath + ". Error message: " + str(e)
return {}
|
<commit_before># -*- coding: utf-8 -*-
import ConfigParser
import logging
class PropertiesParser(object):
"""Parse a java like properties file
Parser wrapping around ConfigParser allowing reading of java like
properties file. Based on stackoverflow example:
https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788
Example usage
-------------
>>> pp = PropertiesParser()
>>> props = pp.parse('/home/kola/configfiles/dev/application.properties')
>>> print props
"""
def __init__(self):
self.secheadname = 'fakeSectionHead'
self.sechead = '[' + self.secheadname + ']\n'
self.logger = logging.getLogger(__name__)
def readline(self):
if self.sechead:
try:
return self.sechead
finally:
self.sechead = None
else:
return self.fp.readline()
def parse(self, filepath):
"""Parse file containing java like properties."""
try:
self.fp = open(filepath)
cp = ConfigParser.SafeConfigParser()
cp.readfp(self)
self.fp.close()
# reset the section head incase the parser will be used again
self.sechead = '[' + self.secheadname + ']\n'
return cp.items(self.secheadname)
except Exception as e:
self.logger.error("Problem parsing " + filepath + ". Error message: " + str(e))
return {}
<commit_msg>Change logging to use print because of logger configuration error<commit_after># -*- coding: utf-8 -*-
import ConfigParser
import logging
class PropertiesParser(object):
"""Parse a java like properties file
Parser wrapping around ConfigParser allowing reading of java like
properties file. Based on stackoverflow example:
https://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788
Example usage
-------------
>>> pp = PropertiesParser()
>>> props = pp.parse('/home/kola/configfiles/dev/application.properties')
>>> print props
"""
def __init__(self):
self.secheadname = 'fakeSectionHead'
self.sechead = '[' + self.secheadname + ']\n'
#self.logger = logging.getLogger(__name__)
def readline(self):
if self.sechead:
try:
return self.sechead
finally:
self.sechead = None
else:
return self.fp.readline()
def parse(self, filepath):
"""Parse file containing java like properties."""
try:
self.fp = open(filepath)
cp = ConfigParser.SafeConfigParser()
cp.readfp(self)
self.fp.close()
# reset the section head incase the parser will be used again
self.sechead = '[' + self.secheadname + ']\n'
return cp.items(self.secheadname)
except Exception as e:
#self.logger.error("Problem parsing " + filepath + ". Error message: " + str(e))
print "Problem parsing " + filepath + ". Error message: " + str(e)
return {}
|
799ed61e049da558f2fd87db8ef3bf0ad888681c
|
monasca/common/messaging/message_formats/reference/metrics.py
|
monasca/common/messaging/message_formats/reference/metrics.py
|
# Copyright 2014 Hewlett-Packard
#
# 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_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(transformed_metric)
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric
|
# Copyright 2014 Hewlett-Packard
#
# 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.
import copy
from oslo_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(copy.deepcopy(transformed_metric))
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric
|
Correct the 'reference' format transform method
|
Correct the 'reference' format transform method
Currently, the 'reference' format transform method will traversal the
metrics list and reconstruct every item of the list to add tenant_id and
region info, but new transformed metrics list will use the reference
of the local dict variable "transformed_metric", that will lead that all
the items of the transformed metrics list be the same value.
Change-Id: Id7f4e18ca3ae0fa93cdafe0d63b7e90c96ce4b28
Closes-bug: #1439055
|
Python
|
apache-2.0
|
stackforge/monasca-api,hpcloud-mon/monasca-events-api,openstack/monasca-api,sapcc/monasca-api,stackforge/monasca-api,hpcloud-mon/monasca-events-api,stackforge/monasca-api,hpcloud-mon/monasca-events-api,oneilcin/monasca-events-api,oneilcin/monasca-events-api,hpcloud-mon/monasca-events-api,sapcc/monasca-api,oneilcin/monasca-events-api,oneilcin/monasca-events-api,sapcc/monasca-api,openstack/monasca-api,stackforge/monasca-api,openstack/monasca-api
|
# Copyright 2014 Hewlett-Packard
#
# 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_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(transformed_metric)
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metricCorrect the 'reference' format transform method
Currently, the 'reference' format transform method will traversal the
metrics list and reconstruct every item of the list to add tenant_id and
region info, but new transformed metrics list will use the reference
of the local dict variable "transformed_metric", that will lead that all
the items of the transformed metrics list be the same value.
Change-Id: Id7f4e18ca3ae0fa93cdafe0d63b7e90c96ce4b28
Closes-bug: #1439055
|
# Copyright 2014 Hewlett-Packard
#
# 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.
import copy
from oslo_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(copy.deepcopy(transformed_metric))
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric
|
<commit_before># Copyright 2014 Hewlett-Packard
#
# 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_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(transformed_metric)
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric<commit_msg>Correct the 'reference' format transform method
Currently, the 'reference' format transform method will traversal the
metrics list and reconstruct every item of the list to add tenant_id and
region info, but new transformed metrics list will use the reference
of the local dict variable "transformed_metric", that will lead that all
the items of the transformed metrics list be the same value.
Change-Id: Id7f4e18ca3ae0fa93cdafe0d63b7e90c96ce4b28
Closes-bug: #1439055<commit_after>
|
# Copyright 2014 Hewlett-Packard
#
# 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.
import copy
from oslo_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(copy.deepcopy(transformed_metric))
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric
|
# Copyright 2014 Hewlett-Packard
#
# 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_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(transformed_metric)
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metricCorrect the 'reference' format transform method
Currently, the 'reference' format transform method will traversal the
metrics list and reconstruct every item of the list to add tenant_id and
region info, but new transformed metrics list will use the reference
of the local dict variable "transformed_metric", that will lead that all
the items of the transformed metrics list be the same value.
Change-Id: Id7f4e18ca3ae0fa93cdafe0d63b7e90c96ce4b28
Closes-bug: #1439055# Copyright 2014 Hewlett-Packard
#
# 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.
import copy
from oslo_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(copy.deepcopy(transformed_metric))
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric
|
<commit_before># Copyright 2014 Hewlett-Packard
#
# 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_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(transformed_metric)
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric<commit_msg>Correct the 'reference' format transform method
Currently, the 'reference' format transform method will traversal the
metrics list and reconstruct every item of the list to add tenant_id and
region info, but new transformed metrics list will use the reference
of the local dict variable "transformed_metric", that will lead that all
the items of the transformed metrics list be the same value.
Change-Id: Id7f4e18ca3ae0fa93cdafe0d63b7e90c96ce4b28
Closes-bug: #1439055<commit_after># Copyright 2014 Hewlett-Packard
#
# 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.
import copy
from oslo_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(copy.deepcopy(transformed_metric))
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.