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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
509893fffd0d3df965f43035b5004e42b9d631c4 | ci/testsettings.py | ci/testsettings.py | # minimal django settings required to run tests
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "test.db",
}
}
SECRET_KEY = '' | # minimal django settings required to run tests
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "test.db",
}
}
# SECRET_KEY = ''
| Fix sample test settings for use with travis-ci | Fix sample test settings for use with travis-ci
| Python | apache-2.0 | Princeton-CDH/django-pucas,Princeton-CDH/django-pucas | # minimal django settings required to run tests
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "test.db",
}
}
SECRET_KEY = ''Fix sample test settings for use with travis-ci | # minimal django settings required to run tests
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "test.db",
}
}
# SECRET_KEY = ''
| <commit_before># minimal django settings required to run tests
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "test.db",
}
}
SECRET_KEY = ''<commit_msg>Fix sample test settings for use with travis-ci<commit_after> | # minimal django settings required to run tests
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "test.db",
}
}
# SECRET_KEY = ''
| # minimal django settings required to run tests
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "test.db",
}
}
SECRET_KEY = ''Fix sample test settings for use with travis-ci# minimal django settings required to run tests
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "test.db",
}
}
# SECRET_KEY = ''
| <commit_before># minimal django settings required to run tests
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "test.db",
}
}
SECRET_KEY = ''<commit_msg>Fix sample test settings for use with travis-ci<commit_after># minimal django settings required to run tests
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "test.db",
}
}
# SECRET_KEY = ''
|
3e0b015da6a2c9ef648e54959e6f3aab1509a036 | kippt_reader/settings/production.py | kippt_reader/settings/production.py | from os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
| from os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_REDIRECT_EXEMPT = [
'^(?!hub/).*'
]
| Add SECURE_REDIRECT_EXEMPT to old HTTP callbacks | Add SECURE_REDIRECT_EXEMPT to old HTTP callbacks | Python | mit | jpadilla/feedleap,jpadilla/feedleap | from os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
Add SECURE_REDIRECT_EXEMPT to old HTTP callbacks | from os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_REDIRECT_EXEMPT = [
'^(?!hub/).*'
]
| <commit_before>from os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
<commit_msg>Add SECURE_REDIRECT_EXEMPT to old HTTP callbacks<commit_after> | from os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_REDIRECT_EXEMPT = [
'^(?!hub/).*'
]
| from os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
Add SECURE_REDIRECT_EXEMPT to old HTTP callbacksfrom os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_REDIRECT_EXEMPT = [
'^(?!hub/).*'
]
| <commit_before>from os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
<commit_msg>Add SECURE_REDIRECT_EXEMPT to old HTTP callbacks<commit_after>from os import environ
import dj_database_url
from .base import *
INSTALLED_APPS += (
'djangosecure',
)
PRODUCTION_MIDDLEWARE_CLASSES = (
'djangosecure.middleware.SecurityMiddleware',
)
MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES
DATABASES = {'default': dj_database_url.config()}
SECRET_KEY = environ.get('SECRET_KEY')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = [DOMAIN]
# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_REDIRECT_EXEMPT = [
'^(?!hub/).*'
]
|
0319ff5049da2c53d8b6507d7fc625ce00a421af | compare.py | compare.py | """The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
"""
class Expr(object):
"""Encapsulates a python expression, primitive value or callable
that is to be evaluated and compared to another value.
Serves as the basic construct for describing an expectation.
Generally you would not use this class directly, instead it is
available through the "expect" alias which allows for a more
pythonic syntax.
It initializes with primitives, native types and expressions
>>> e = Expr("Foo")
>>> e.value == "Foo"
True
>>> e = Expr(['a', 'b'])
>>> e.value == ['a', 'b']
True
>>> Expr(4 + 7).value == 11
True
>>> Expr(4 == 7).value == False
True
"""
def __init__(self, value):
self.value = value
| """The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
The expect starter is simply an alias to the Expr class so
you may use it like so:
>>> expect(5 + 10).value == 15
True
"""
class Expr(object):
"""Encapsulates a python expression, primitive value or callable
that is to be evaluated and compared to another value.
Serves as the basic construct for describing an expectation.
Generally you would not use this class directly, instead it is
available through the "expect" alias which allows for a more
pythonic syntax.
It initializes with primitives, native types and expressions:
>>> e = Expr("Foo")
>>> e.value == "Foo"
True
>>> e = Expr(['a', 'b'])
>>> e.value == ['a', 'b']
True
>>> Expr(4 + 7).value == 11
True
>>> Expr(4 == 7).value == False
True
"""
def __init__(self, value):
self.value = value
# provide a usable alias for the Expr class
expect = Expr
"""Alias for the Expect class that starts an expectation contruct."""
def matcher(func):
"""Decorator to register a function as a matcher. It attaches the
decorated function to the Expr class so that it is available through
the "expect" starter.
The matcher being registered is expected to accept at least a single parameter
"self", which is the Expr object it is attached to.
Here is a trivial example showing how to create and register a matcher:
>>> def to_equal_foo(self):
... assert self.value == "foo"
>>> matcher(to_equal_foo)
Now you may use the matcher with the expect syntax:
>>> expect("foo").to_equal_foo()
"""
setattr(expect, func.__name__, func)
| Implement @matcher decorator to register matchers. | Implement @matcher decorator to register matchers.
| Python | bsd-3-clause | rudylattae/compare,rudylattae/compare | """The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
"""
class Expr(object):
"""Encapsulates a python expression, primitive value or callable
that is to be evaluated and compared to another value.
Serves as the basic construct for describing an expectation.
Generally you would not use this class directly, instead it is
available through the "expect" alias which allows for a more
pythonic syntax.
It initializes with primitives, native types and expressions
>>> e = Expr("Foo")
>>> e.value == "Foo"
True
>>> e = Expr(['a', 'b'])
>>> e.value == ['a', 'b']
True
>>> Expr(4 + 7).value == 11
True
>>> Expr(4 == 7).value == False
True
"""
def __init__(self, value):
self.value = value
Implement @matcher decorator to register matchers. | """The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
The expect starter is simply an alias to the Expr class so
you may use it like so:
>>> expect(5 + 10).value == 15
True
"""
class Expr(object):
"""Encapsulates a python expression, primitive value or callable
that is to be evaluated and compared to another value.
Serves as the basic construct for describing an expectation.
Generally you would not use this class directly, instead it is
available through the "expect" alias which allows for a more
pythonic syntax.
It initializes with primitives, native types and expressions:
>>> e = Expr("Foo")
>>> e.value == "Foo"
True
>>> e = Expr(['a', 'b'])
>>> e.value == ['a', 'b']
True
>>> Expr(4 + 7).value == 11
True
>>> Expr(4 == 7).value == False
True
"""
def __init__(self, value):
self.value = value
# provide a usable alias for the Expr class
expect = Expr
"""Alias for the Expect class that starts an expectation contruct."""
def matcher(func):
"""Decorator to register a function as a matcher. It attaches the
decorated function to the Expr class so that it is available through
the "expect" starter.
The matcher being registered is expected to accept at least a single parameter
"self", which is the Expr object it is attached to.
Here is a trivial example showing how to create and register a matcher:
>>> def to_equal_foo(self):
... assert self.value == "foo"
>>> matcher(to_equal_foo)
Now you may use the matcher with the expect syntax:
>>> expect("foo").to_equal_foo()
"""
setattr(expect, func.__name__, func)
| <commit_before>"""The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
"""
class Expr(object):
"""Encapsulates a python expression, primitive value or callable
that is to be evaluated and compared to another value.
Serves as the basic construct for describing an expectation.
Generally you would not use this class directly, instead it is
available through the "expect" alias which allows for a more
pythonic syntax.
It initializes with primitives, native types and expressions
>>> e = Expr("Foo")
>>> e.value == "Foo"
True
>>> e = Expr(['a', 'b'])
>>> e.value == ['a', 'b']
True
>>> Expr(4 + 7).value == 11
True
>>> Expr(4 == 7).value == False
True
"""
def __init__(self, value):
self.value = value
<commit_msg>Implement @matcher decorator to register matchers.<commit_after> | """The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
The expect starter is simply an alias to the Expr class so
you may use it like so:
>>> expect(5 + 10).value == 15
True
"""
class Expr(object):
"""Encapsulates a python expression, primitive value or callable
that is to be evaluated and compared to another value.
Serves as the basic construct for describing an expectation.
Generally you would not use this class directly, instead it is
available through the "expect" alias which allows for a more
pythonic syntax.
It initializes with primitives, native types and expressions:
>>> e = Expr("Foo")
>>> e.value == "Foo"
True
>>> e = Expr(['a', 'b'])
>>> e.value == ['a', 'b']
True
>>> Expr(4 + 7).value == 11
True
>>> Expr(4 == 7).value == False
True
"""
def __init__(self, value):
self.value = value
# provide a usable alias for the Expr class
expect = Expr
"""Alias for the Expect class that starts an expectation contruct."""
def matcher(func):
"""Decorator to register a function as a matcher. It attaches the
decorated function to the Expr class so that it is available through
the "expect" starter.
The matcher being registered is expected to accept at least a single parameter
"self", which is the Expr object it is attached to.
Here is a trivial example showing how to create and register a matcher:
>>> def to_equal_foo(self):
... assert self.value == "foo"
>>> matcher(to_equal_foo)
Now you may use the matcher with the expect syntax:
>>> expect("foo").to_equal_foo()
"""
setattr(expect, func.__name__, func)
| """The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
"""
class Expr(object):
"""Encapsulates a python expression, primitive value or callable
that is to be evaluated and compared to another value.
Serves as the basic construct for describing an expectation.
Generally you would not use this class directly, instead it is
available through the "expect" alias which allows for a more
pythonic syntax.
It initializes with primitives, native types and expressions
>>> e = Expr("Foo")
>>> e.value == "Foo"
True
>>> e = Expr(['a', 'b'])
>>> e.value == ['a', 'b']
True
>>> Expr(4 + 7).value == 11
True
>>> Expr(4 == 7).value == False
True
"""
def __init__(self, value):
self.value = value
Implement @matcher decorator to register matchers."""The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
The expect starter is simply an alias to the Expr class so
you may use it like so:
>>> expect(5 + 10).value == 15
True
"""
class Expr(object):
"""Encapsulates a python expression, primitive value or callable
that is to be evaluated and compared to another value.
Serves as the basic construct for describing an expectation.
Generally you would not use this class directly, instead it is
available through the "expect" alias which allows for a more
pythonic syntax.
It initializes with primitives, native types and expressions:
>>> e = Expr("Foo")
>>> e.value == "Foo"
True
>>> e = Expr(['a', 'b'])
>>> e.value == ['a', 'b']
True
>>> Expr(4 + 7).value == 11
True
>>> Expr(4 == 7).value == False
True
"""
def __init__(self, value):
self.value = value
# provide a usable alias for the Expr class
expect = Expr
"""Alias for the Expect class that starts an expectation contruct."""
def matcher(func):
"""Decorator to register a function as a matcher. It attaches the
decorated function to the Expr class so that it is available through
the "expect" starter.
The matcher being registered is expected to accept at least a single parameter
"self", which is the Expr object it is attached to.
Here is a trivial example showing how to create and register a matcher:
>>> def to_equal_foo(self):
... assert self.value == "foo"
>>> matcher(to_equal_foo)
Now you may use the matcher with the expect syntax:
>>> expect("foo").to_equal_foo()
"""
setattr(expect, func.__name__, func)
| <commit_before>"""The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
"""
class Expr(object):
"""Encapsulates a python expression, primitive value or callable
that is to be evaluated and compared to another value.
Serves as the basic construct for describing an expectation.
Generally you would not use this class directly, instead it is
available through the "expect" alias which allows for a more
pythonic syntax.
It initializes with primitives, native types and expressions
>>> e = Expr("Foo")
>>> e.value == "Foo"
True
>>> e = Expr(['a', 'b'])
>>> e.value == ['a', 'b']
True
>>> Expr(4 + 7).value == 11
True
>>> Expr(4 == 7).value == False
True
"""
def __init__(self, value):
self.value = value
<commit_msg>Implement @matcher decorator to register matchers.<commit_after>"""The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
The expect starter is simply an alias to the Expr class so
you may use it like so:
>>> expect(5 + 10).value == 15
True
"""
class Expr(object):
"""Encapsulates a python expression, primitive value or callable
that is to be evaluated and compared to another value.
Serves as the basic construct for describing an expectation.
Generally you would not use this class directly, instead it is
available through the "expect" alias which allows for a more
pythonic syntax.
It initializes with primitives, native types and expressions:
>>> e = Expr("Foo")
>>> e.value == "Foo"
True
>>> e = Expr(['a', 'b'])
>>> e.value == ['a', 'b']
True
>>> Expr(4 + 7).value == 11
True
>>> Expr(4 == 7).value == False
True
"""
def __init__(self, value):
self.value = value
# provide a usable alias for the Expr class
expect = Expr
"""Alias for the Expect class that starts an expectation contruct."""
def matcher(func):
"""Decorator to register a function as a matcher. It attaches the
decorated function to the Expr class so that it is available through
the "expect" starter.
The matcher being registered is expected to accept at least a single parameter
"self", which is the Expr object it is attached to.
Here is a trivial example showing how to create and register a matcher:
>>> def to_equal_foo(self):
... assert self.value == "foo"
>>> matcher(to_equal_foo)
Now you may use the matcher with the expect syntax:
>>> expect("foo").to_equal_foo()
"""
setattr(expect, func.__name__, func)
|
52c8ee184cc0071187c1915c4f3e6f287f3faa81 | config/__init__.py | config/__init__.py | import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
| import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
# Make sure use_testing() is not detected as a unit test by nose
use_testing.__test__ = False
| Make sure use_testing() is not detected as a unit test by nose | config: Make sure use_testing() is not detected as a unit test by nose
| Python | agpl-3.0 | shadowoneau/skylines,kerel-fs/skylines,Turbo87/skylines,kerel-fs/skylines,snip/skylines,Harry-R/skylines,snip/skylines,RBE-Avionik/skylines,Harry-R/skylines,Turbo87/skylines,RBE-Avionik/skylines,TobiasLohner/SkyLines,skylines-project/skylines,Turbo87/skylines,Harry-R/skylines,skylines-project/skylines,skylines-project/skylines,Harry-R/skylines,TobiasLohner/SkyLines,shadowoneau/skylines,kerel-fs/skylines,RBE-Avionik/skylines,TobiasLohner/SkyLines,shadowoneau/skylines,RBE-Avionik/skylines,shadowoneau/skylines,skylines-project/skylines,Turbo87/skylines,snip/skylines | import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
config: Make sure use_testing() is not detected as a unit test by nose | import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
# Make sure use_testing() is not detected as a unit test by nose
use_testing.__test__ = False
| <commit_before>import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
<commit_msg>config: Make sure use_testing() is not detected as a unit test by nose<commit_after> | import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
# Make sure use_testing() is not detected as a unit test by nose
use_testing.__test__ = False
| import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
config: Make sure use_testing() is not detected as a unit test by noseimport os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
# Make sure use_testing() is not detected as a unit test by nose
use_testing.__test__ = False
| <commit_before>import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
<commit_msg>config: Make sure use_testing() is not detected as a unit test by nose<commit_after>import os
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
PRO_CONF_PATH = '/etc/skylines/production.py'
DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py')
TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py')
def to_envvar(path=None):
"""
Loads the application configuration from a file.
Returns the configuration or None if no configuration could be found.
"""
if path:
path = os.path.abspath(path)
if not os.path.exists(path):
return
elif os.path.exists(PRO_CONF_PATH):
path = PRO_CONF_PATH
elif os.path.exists(DEV_CONF_PATH):
path = DEV_CONF_PATH
else:
return
os.environ['SKYLINES_CONFIG'] = path
return True
def use_testing():
os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
# Make sure use_testing() is not detected as a unit test by nose
use_testing.__test__ = False
|
14803816c50bc1557c633f5d11f2c7a6d339429a | karspexet/ticket/urls.py | karspexet/ticket/urls.py | from django.conf.urls import url
from karspexet.ticket import views
urlpatterns = [
url(r"^show/(?P<show_id>\d+)/select_seats$", views.select_seats, name="select_seats"),
url(r"^reservation/(?P<reservation_id>\d+)/process_payment$", views.process_payment, name="process_payment"),
url(r"^booking_overview/?$", views.booking_overview, name="booking_overview"),
url(r"^reservation/(?P<reservation_code>[A-Z0-9]+)/?$", views.reservation_detail, name="reservation_detail"),
url(r"^$", views.home),
]
| from django.conf.urls import url
from karspexet.ticket import views
urlpatterns = [
url(r"^show/(?P<show_id>\d+)/select_seats/?$", views.select_seats, name="select_seats"),
url(r"^reservation/(?P<reservation_id>\d+)/process_payment$", views.process_payment, name="process_payment"),
url(r"^booking_overview/?$", views.booking_overview, name="booking_overview"),
url(r"^reservation/(?P<reservation_code>[A-Z0-9]+)/?$", views.reservation_detail, name="reservation_detail"),
url(r"^$", views.home),
]
| Allow trailing slash on select_seats url | Allow trailing slash on select_seats url
| Python | mit | Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet | from django.conf.urls import url
from karspexet.ticket import views
urlpatterns = [
url(r"^show/(?P<show_id>\d+)/select_seats$", views.select_seats, name="select_seats"),
url(r"^reservation/(?P<reservation_id>\d+)/process_payment$", views.process_payment, name="process_payment"),
url(r"^booking_overview/?$", views.booking_overview, name="booking_overview"),
url(r"^reservation/(?P<reservation_code>[A-Z0-9]+)/?$", views.reservation_detail, name="reservation_detail"),
url(r"^$", views.home),
]
Allow trailing slash on select_seats url | from django.conf.urls import url
from karspexet.ticket import views
urlpatterns = [
url(r"^show/(?P<show_id>\d+)/select_seats/?$", views.select_seats, name="select_seats"),
url(r"^reservation/(?P<reservation_id>\d+)/process_payment$", views.process_payment, name="process_payment"),
url(r"^booking_overview/?$", views.booking_overview, name="booking_overview"),
url(r"^reservation/(?P<reservation_code>[A-Z0-9]+)/?$", views.reservation_detail, name="reservation_detail"),
url(r"^$", views.home),
]
| <commit_before>from django.conf.urls import url
from karspexet.ticket import views
urlpatterns = [
url(r"^show/(?P<show_id>\d+)/select_seats$", views.select_seats, name="select_seats"),
url(r"^reservation/(?P<reservation_id>\d+)/process_payment$", views.process_payment, name="process_payment"),
url(r"^booking_overview/?$", views.booking_overview, name="booking_overview"),
url(r"^reservation/(?P<reservation_code>[A-Z0-9]+)/?$", views.reservation_detail, name="reservation_detail"),
url(r"^$", views.home),
]
<commit_msg>Allow trailing slash on select_seats url<commit_after> | from django.conf.urls import url
from karspexet.ticket import views
urlpatterns = [
url(r"^show/(?P<show_id>\d+)/select_seats/?$", views.select_seats, name="select_seats"),
url(r"^reservation/(?P<reservation_id>\d+)/process_payment$", views.process_payment, name="process_payment"),
url(r"^booking_overview/?$", views.booking_overview, name="booking_overview"),
url(r"^reservation/(?P<reservation_code>[A-Z0-9]+)/?$", views.reservation_detail, name="reservation_detail"),
url(r"^$", views.home),
]
| from django.conf.urls import url
from karspexet.ticket import views
urlpatterns = [
url(r"^show/(?P<show_id>\d+)/select_seats$", views.select_seats, name="select_seats"),
url(r"^reservation/(?P<reservation_id>\d+)/process_payment$", views.process_payment, name="process_payment"),
url(r"^booking_overview/?$", views.booking_overview, name="booking_overview"),
url(r"^reservation/(?P<reservation_code>[A-Z0-9]+)/?$", views.reservation_detail, name="reservation_detail"),
url(r"^$", views.home),
]
Allow trailing slash on select_seats urlfrom django.conf.urls import url
from karspexet.ticket import views
urlpatterns = [
url(r"^show/(?P<show_id>\d+)/select_seats/?$", views.select_seats, name="select_seats"),
url(r"^reservation/(?P<reservation_id>\d+)/process_payment$", views.process_payment, name="process_payment"),
url(r"^booking_overview/?$", views.booking_overview, name="booking_overview"),
url(r"^reservation/(?P<reservation_code>[A-Z0-9]+)/?$", views.reservation_detail, name="reservation_detail"),
url(r"^$", views.home),
]
| <commit_before>from django.conf.urls import url
from karspexet.ticket import views
urlpatterns = [
url(r"^show/(?P<show_id>\d+)/select_seats$", views.select_seats, name="select_seats"),
url(r"^reservation/(?P<reservation_id>\d+)/process_payment$", views.process_payment, name="process_payment"),
url(r"^booking_overview/?$", views.booking_overview, name="booking_overview"),
url(r"^reservation/(?P<reservation_code>[A-Z0-9]+)/?$", views.reservation_detail, name="reservation_detail"),
url(r"^$", views.home),
]
<commit_msg>Allow trailing slash on select_seats url<commit_after>from django.conf.urls import url
from karspexet.ticket import views
urlpatterns = [
url(r"^show/(?P<show_id>\d+)/select_seats/?$", views.select_seats, name="select_seats"),
url(r"^reservation/(?P<reservation_id>\d+)/process_payment$", views.process_payment, name="process_payment"),
url(r"^booking_overview/?$", views.booking_overview, name="booking_overview"),
url(r"^reservation/(?P<reservation_code>[A-Z0-9]+)/?$", views.reservation_detail, name="reservation_detail"),
url(r"^$", views.home),
]
|
0a2285ac398a237a746fed11abca78fcb8c75252 | nest/settings/heroku.py | nest/settings/heroku.py | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.config()
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
try:
DATABASES['default'] = dj_database_url.config()
except ImproperlyConfigured:
DATABASES = {
'default': {
'ENGINE': 'postgresql_psycopg2',
'NAME': 'quailcomics',
'USER': 'quailcomics',
'PASSWORD': 'quailcomics',
'HOST': '192.241.228.250',
'PORT': '49158',
}
}
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) | Add db settings for angel. | Add db settings for angel.
| Python | mit | ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.config()
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
)Add db settings for angel. | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
try:
DATABASES['default'] = dj_database_url.config()
except ImproperlyConfigured:
DATABASES = {
'default': {
'ENGINE': 'postgresql_psycopg2',
'NAME': 'quailcomics',
'USER': 'quailcomics',
'PASSWORD': 'quailcomics',
'HOST': '192.241.228.250',
'PORT': '49158',
}
}
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) | <commit_before>from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.config()
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
)<commit_msg>Add db settings for angel.<commit_after> | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
try:
DATABASES['default'] = dj_database_url.config()
except ImproperlyConfigured:
DATABASES = {
'default': {
'ENGINE': 'postgresql_psycopg2',
'NAME': 'quailcomics',
'USER': 'quailcomics',
'PASSWORD': 'quailcomics',
'HOST': '192.241.228.250',
'PORT': '49158',
}
}
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.config()
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
)Add db settings for angel.from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
try:
DATABASES['default'] = dj_database_url.config()
except ImproperlyConfigured:
DATABASES = {
'default': {
'ENGINE': 'postgresql_psycopg2',
'NAME': 'quailcomics',
'USER': 'quailcomics',
'PASSWORD': 'quailcomics',
'HOST': '192.241.228.250',
'PORT': '49158',
}
}
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) | <commit_before>from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.config()
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
)<commit_msg>Add db settings for angel.<commit_after>from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
try:
DATABASES['default'] = dj_database_url.config()
except ImproperlyConfigured:
DATABASES = {
'default': {
'ENGINE': 'postgresql_psycopg2',
'NAME': 'quailcomics',
'USER': 'quailcomics',
'PASSWORD': 'quailcomics',
'HOST': '192.241.228.250',
'PORT': '49158',
}
}
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) |
900b45c49573ee4fbaacf65fd9c02adef87639b1 | nest/settings/heroku.py | nest/settings/heroku.py | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
try:
DATABASES['default'] = dj_database_url.config()
except ImproperlyConfigured:
DATABASES = {
'default': {
'ENGINE': 'postgresql_psycopg2',
'NAME': 'quailcomics',
'USER': 'quailcomics',
'PASSWORD': 'quailcomics',
'HOST': '192.241.228.250',
'PORT': '49158',
}
}
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.config()
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) | Undo that which was done. | Undo that which was done.
| Python | mit | ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
try:
DATABASES['default'] = dj_database_url.config()
except ImproperlyConfigured:
DATABASES = {
'default': {
'ENGINE': 'postgresql_psycopg2',
'NAME': 'quailcomics',
'USER': 'quailcomics',
'PASSWORD': 'quailcomics',
'HOST': '192.241.228.250',
'PORT': '49158',
}
}
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
)Undo that which was done. | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.config()
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) | <commit_before>from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
try:
DATABASES['default'] = dj_database_url.config()
except ImproperlyConfigured:
DATABASES = {
'default': {
'ENGINE': 'postgresql_psycopg2',
'NAME': 'quailcomics',
'USER': 'quailcomics',
'PASSWORD': 'quailcomics',
'HOST': '192.241.228.250',
'PORT': '49158',
}
}
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
)<commit_msg>Undo that which was done.<commit_after> | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.config()
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) | from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
try:
DATABASES['default'] = dj_database_url.config()
except ImproperlyConfigured:
DATABASES = {
'default': {
'ENGINE': 'postgresql_psycopg2',
'NAME': 'quailcomics',
'USER': 'quailcomics',
'PASSWORD': 'quailcomics',
'HOST': '192.241.228.250',
'PORT': '49158',
}
}
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
)Undo that which was done.from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.config()
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) | <commit_before>from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
try:
DATABASES['default'] = dj_database_url.config()
except ImproperlyConfigured:
DATABASES = {
'default': {
'ENGINE': 'postgresql_psycopg2',
'NAME': 'quailcomics',
'USER': 'quailcomics',
'PASSWORD': 'quailcomics',
'HOST': '192.241.228.250',
'PORT': '49158',
}
}
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
)<commit_msg>Undo that which was done.<commit_after>from .base import *
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES['default'] = dj_database_url.config()
ALLOWED_HOSTS = [
'.captainquail.com',
'.quailcomics.com',
'.herokuapp.com',
'localhost',
'127.0.0.1'
]
STATIC_URL = 'http://media.quailcomics.com/assets/'
INSTALLED_APPS += (
'gunicorn',
) |
7db4a5a365c0d96d65b38b3fd33872080179cf93 | benchexec/tools/kissat.py | benchexec/tools/kissat.py | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + list(task.input_files_or_identifier)
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = "SAT"
elif "s UNSATISFIABLE" in line:
status = "UNSAT"
if (not status or status == result.RESULT_UNKNOWN) and run.was_timeout:
status = "TIMEOUT"
if not status:
status = result.RESULT_ERROR
return status
| # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = result.RESULT_TRUE_PROP
elif "s UNSATISFIABLE" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
| Modify the tool-info module according to Philipp's reviews | Modify the tool-info module according to Philipp's reviews
| Python | apache-2.0 | ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + list(task.input_files_or_identifier)
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = "SAT"
elif "s UNSATISFIABLE" in line:
status = "UNSAT"
if (not status or status == result.RESULT_UNKNOWN) and run.was_timeout:
status = "TIMEOUT"
if not status:
status = result.RESULT_ERROR
return status
Modify the tool-info module according to Philipp's reviews | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = result.RESULT_TRUE_PROP
elif "s UNSATISFIABLE" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
| <commit_before># This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + list(task.input_files_or_identifier)
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = "SAT"
elif "s UNSATISFIABLE" in line:
status = "UNSAT"
if (not status or status == result.RESULT_UNKNOWN) and run.was_timeout:
status = "TIMEOUT"
if not status:
status = result.RESULT_ERROR
return status
<commit_msg>Modify the tool-info module according to Philipp's reviews<commit_after> | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = result.RESULT_TRUE_PROP
elif "s UNSATISFIABLE" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
| # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + list(task.input_files_or_identifier)
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = "SAT"
elif "s UNSATISFIABLE" in line:
status = "UNSAT"
if (not status or status == result.RESULT_UNKNOWN) and run.was_timeout:
status = "TIMEOUT"
if not status:
status = result.RESULT_ERROR
return status
Modify the tool-info module according to Philipp's reviews# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = result.RESULT_TRUE_PROP
elif "s UNSATISFIABLE" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
| <commit_before># This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + list(task.input_files_or_identifier)
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = "SAT"
elif "s UNSATISFIABLE" in line:
status = "UNSAT"
if (not status or status == result.RESULT_UNKNOWN) and run.was_timeout:
status = "TIMEOUT"
if not status:
status = result.RESULT_ERROR
return status
<commit_msg>Modify the tool-info module according to Philipp's reviews<commit_after># This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = result.RESULT_TRUE_PROP
elif "s UNSATISFIABLE" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
|
c6dcb3cb3dd0a7ab4101275a1e96c629e5d7ba28 | tools/misc/python/test-data-in-out3.py | tools/misc/python/test-data-in-out3.py | # TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
import shutil
shutil.copyfile('input', 'output')
| # TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
# RUNTIME python3
import shutil
shutil.copyfile('input', 'output')
| Move python3 custom runtime to sadl | Move python3 custom runtime to sadl | Python | mit | chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools | # TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
import shutil
shutil.copyfile('input', 'output')
Move python3 custom runtime to sadl | # TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
# RUNTIME python3
import shutil
shutil.copyfile('input', 'output')
| <commit_before># TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
import shutil
shutil.copyfile('input', 'output')
<commit_msg>Move python3 custom runtime to sadl<commit_after> | # TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
# RUNTIME python3
import shutil
shutil.copyfile('input', 'output')
| # TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
import shutil
shutil.copyfile('input', 'output')
Move python3 custom runtime to sadl# TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
# RUNTIME python3
import shutil
shutil.copyfile('input', 'output')
| <commit_before># TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
import shutil
shutil.copyfile('input', 'output')
<commit_msg>Move python3 custom runtime to sadl<commit_after># TOOL test-data-in-out3.py: "Test data input and output in Python3" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
# RUNTIME python3
import shutil
shutil.copyfile('input', 'output')
|
24582fa0e031ad8c964a094912a6fb5a02bc2ace | tests/unit/fixture/test_logging.py | tests/unit/fixture/test_logging.py | # 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.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.info,
'pid of first child is %(foo)s',
1)
| # 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.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.error,
'pid of first child is %(foo)s',
1)
| Test formatting errors with log level being emitted | Test formatting errors with log level being emitted
The test to ensure that formatting errors are handled properly was being
run using info level logging, but the default log configuration for
tests does not emit messages at that level, so switch to error.
Change-Id: Ie11a51deea65627b45a11d7dfca36d16c1b5949e
| Python | apache-2.0 | akash1808/oslo.log,meganjbaker/oslo.log,magic0704/oslo.log,JioCloud/oslo.log,zzicewind/oslo.log,varunarya10/oslo.log,openstack/oslo.log | # 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.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.info,
'pid of first child is %(foo)s',
1)
Test formatting errors with log level being emitted
The test to ensure that formatting errors are handled properly was being
run using info level logging, but the default log configuration for
tests does not emit messages at that level, so switch to error.
Change-Id: Ie11a51deea65627b45a11d7dfca36d16c1b5949e | # 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.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.error,
'pid of first child is %(foo)s',
1)
| <commit_before># 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.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.info,
'pid of first child is %(foo)s',
1)
<commit_msg>Test formatting errors with log level being emitted
The test to ensure that formatting errors are handled properly was being
run using info level logging, but the default log configuration for
tests does not emit messages at that level, so switch to error.
Change-Id: Ie11a51deea65627b45a11d7dfca36d16c1b5949e<commit_after> | # 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.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.error,
'pid of first child is %(foo)s',
1)
| # 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.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.info,
'pid of first child is %(foo)s',
1)
Test formatting errors with log level being emitted
The test to ensure that formatting errors are handled properly was being
run using info level logging, but the default log configuration for
tests does not emit messages at that level, so switch to error.
Change-Id: Ie11a51deea65627b45a11d7dfca36d16c1b5949e# 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.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.error,
'pid of first child is %(foo)s',
1)
| <commit_before># 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.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.info,
'pid of first child is %(foo)s',
1)
<commit_msg>Test formatting errors with log level being emitted
The test to ensure that formatting errors are handled properly was being
run using info level logging, but the default log configuration for
tests does not emit messages at that level, so switch to error.
Change-Id: Ie11a51deea65627b45a11d7dfca36d16c1b5949e<commit_after># 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.log.fixture import logging as logging_fixture
from oslo.log import log as logging
from oslotest import base as test_base
LOG = logging.getLogger(__name__)
class TestLoggingFixture(test_base.BaseTestCase):
def test_logging_handle_error(self):
LOG.info('pid of first child is %(foo)s', 1)
self.useFixture(logging_fixture.get_logging_handle_error_fixture())
self.assertRaises(TypeError,
LOG.error,
'pid of first child is %(foo)s',
1)
|
ab4983e577b9831b91290976be00917edb9fad6f | mlox/modules/resources.py | mlox/modules/resources.py | """Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://sourceforge.net/projects/mlox/files/mlox/' + UPDATE_BASE
| """Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://svn.code.sf.net/p/mlox/code/trunk/downloads/' + UPDATE_BASE
| Switch back to using the old SVN update location. | Switch back to using the old SVN update location.
While changing the download location would be nice, this keeps the option of putting a final data file that would force users to update.
| Python | mit | EmperorArthur/mlox,EmperorArthur/mlox,EmperorArthur/mlox | """Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://sourceforge.net/projects/mlox/files/mlox/' + UPDATE_BASE
Switch back to using the old SVN update location.
While changing the download location would be nice, this keeps the option of putting a final data file that would force users to update. | """Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://svn.code.sf.net/p/mlox/code/trunk/downloads/' + UPDATE_BASE
| <commit_before>"""Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://sourceforge.net/projects/mlox/files/mlox/' + UPDATE_BASE
<commit_msg>Switch back to using the old SVN update location.
While changing the download location would be nice, this keeps the option of putting a final data file that would force users to update.<commit_after> | """Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://svn.code.sf.net/p/mlox/code/trunk/downloads/' + UPDATE_BASE
| """Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://sourceforge.net/projects/mlox/files/mlox/' + UPDATE_BASE
Switch back to using the old SVN update location.
While changing the download location would be nice, this keeps the option of putting a final data file that would force users to update."""Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://svn.code.sf.net/p/mlox/code/trunk/downloads/' + UPDATE_BASE
| <commit_before>"""Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://sourceforge.net/projects/mlox/files/mlox/' + UPDATE_BASE
<commit_msg>Switch back to using the old SVN update location.
While changing the download location would be nice, this keeps the option of putting a final data file that would force users to update.<commit_after>"""Handle program wide resources (files, images, etc...)"""
import os
import sys
import base64
import tempfile
def unpack_resource(data):
"""Convert base64 encoded data into a file handle, and a temporary file name to access the data"""
file_handle = tempfile.NamedTemporaryFile()
file_handle.write(base64.b64decode(data))
file_handle.seek(0)
return (file_handle,file_handle.name)
#Paths to resource files
program_path = os.path.realpath(sys.path[0])
resources_path = os.path.join(program_path,"Resources")
translation_file = os.path.join(resources_path,"mlox.msg")
gif_file = os.path.join(resources_path,"mlox.gif")
base_file = os.path.join(program_path,"mlox_base.txt")
user_file = os.path.join(program_path,"mlox_user.txt")
#For the updater
UPDATE_BASE = "mlox-data.7z"
update_file = os.path.join(program_path,UPDATE_BASE)
UPDATE_URL = 'https://svn.code.sf.net/p/mlox/code/trunk/downloads/' + UPDATE_BASE
|
2b2696dde438a46a7b831867111cc767a88bf77e | lib/DjangoLibrary.py | lib/DjangoLibrary.py | from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
| # -*- coding: utf-8 -*-
__version__ = '0.1'
from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
"""Start the Django server."""
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
"""Stop Django server."""
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
| Add version, utf-8 and some comments. | Add version, utf-8 and some comments.
| Python | apache-2.0 | kitconcept/robotframework-djangolibrary | from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
Add version, utf-8 and some comments. | # -*- coding: utf-8 -*-
__version__ = '0.1'
from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
"""Start the Django server."""
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
"""Stop Django server."""
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
| <commit_before>from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
<commit_msg>Add version, utf-8 and some comments.<commit_after> | # -*- coding: utf-8 -*-
__version__ = '0.1'
from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
"""Start the Django server."""
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
"""Stop Django server."""
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
| from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
Add version, utf-8 and some comments.# -*- coding: utf-8 -*-
__version__ = '0.1'
from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
"""Start the Django server."""
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
"""Stop Django server."""
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
| <commit_before>from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
<commit_msg>Add version, utf-8 and some comments.<commit_after># -*- coding: utf-8 -*-
__version__ = '0.1'
from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
"""Start the Django server."""
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
"""Stop Django server."""
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
|
ac7902ad4d4c4df94fa6b13ae9ef18623d63b900 | tests/_utils.py | tests/_utils.py | import os, sys
support = os.path.join(os.path.dirname(__file__), '_support')
def load(name):
sys.path.insert(0, support)
mod = __import__(name)
sys.path.pop(0)
return mod
| import os, sys
from contextlib import contextmanager
support = os.path.join(os.path.dirname(__file__), '_support')
@contextmanager
def support_path():
sys.path.insert(0, support)
yield
sys.path.pop(0)
def load(name):
with support_path():
return __import__(name)
| Tweak support load path jazz | Tweak support load path jazz
| Python | bsd-2-clause | mkusz/invoke,sophacles/invoke,singingwolfboy/invoke,pfmoore/invoke,kejbaly2/invoke,alex/invoke,pfmoore/invoke,pyinvoke/invoke,kejbaly2/invoke,frol/invoke,mkusz/invoke,mattrobenolt/invoke,mattrobenolt/invoke,frol/invoke,pyinvoke/invoke,tyewang/invoke | import os, sys
support = os.path.join(os.path.dirname(__file__), '_support')
def load(name):
sys.path.insert(0, support)
mod = __import__(name)
sys.path.pop(0)
return mod
Tweak support load path jazz | import os, sys
from contextlib import contextmanager
support = os.path.join(os.path.dirname(__file__), '_support')
@contextmanager
def support_path():
sys.path.insert(0, support)
yield
sys.path.pop(0)
def load(name):
with support_path():
return __import__(name)
| <commit_before>import os, sys
support = os.path.join(os.path.dirname(__file__), '_support')
def load(name):
sys.path.insert(0, support)
mod = __import__(name)
sys.path.pop(0)
return mod
<commit_msg>Tweak support load path jazz<commit_after> | import os, sys
from contextlib import contextmanager
support = os.path.join(os.path.dirname(__file__), '_support')
@contextmanager
def support_path():
sys.path.insert(0, support)
yield
sys.path.pop(0)
def load(name):
with support_path():
return __import__(name)
| import os, sys
support = os.path.join(os.path.dirname(__file__), '_support')
def load(name):
sys.path.insert(0, support)
mod = __import__(name)
sys.path.pop(0)
return mod
Tweak support load path jazzimport os, sys
from contextlib import contextmanager
support = os.path.join(os.path.dirname(__file__), '_support')
@contextmanager
def support_path():
sys.path.insert(0, support)
yield
sys.path.pop(0)
def load(name):
with support_path():
return __import__(name)
| <commit_before>import os, sys
support = os.path.join(os.path.dirname(__file__), '_support')
def load(name):
sys.path.insert(0, support)
mod = __import__(name)
sys.path.pop(0)
return mod
<commit_msg>Tweak support load path jazz<commit_after>import os, sys
from contextlib import contextmanager
support = os.path.join(os.path.dirname(__file__), '_support')
@contextmanager
def support_path():
sys.path.insert(0, support)
yield
sys.path.pop(0)
def load(name):
with support_path():
return __import__(name)
|
9660fb734ecf2ad2c181eba790cdd2ddc9ed423e | cyder/core/system/forms.py | cyder/core/system/forms.py | from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
interface_type = forms.ChoiceField(
widget=forms.RadioSelect, choices=(
('Static', 'Static Interface'),
('Dynamic', 'Dynamic Interface')))
class Meta:
model = System
SystemAVForm = get_eav_form(SystemAV, System)
| from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
interface_type = forms.ChoiceField(
widget=forms.RadioSelect, choices=(
('static_interface', 'Static Interface'),
('dynamic_interface', 'Dynamic Interface')))
class Meta:
model = System
SystemAVForm = get_eav_form(SystemAV, System)
| Fix system form interface_type choices | Fix system form interface_type choices
| Python | bsd-3-clause | murrown/cyder,drkitty/cyder,OSU-Net/cyder,akeym/cyder,murrown/cyder,OSU-Net/cyder,murrown/cyder,akeym/cyder,murrown/cyder,drkitty/cyder,zeeman/cyder,zeeman/cyder,OSU-Net/cyder,akeym/cyder,zeeman/cyder,OSU-Net/cyder,drkitty/cyder,akeym/cyder,drkitty/cyder,zeeman/cyder | from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
interface_type = forms.ChoiceField(
widget=forms.RadioSelect, choices=(
('Static', 'Static Interface'),
('Dynamic', 'Dynamic Interface')))
class Meta:
model = System
SystemAVForm = get_eav_form(SystemAV, System)
Fix system form interface_type choices | from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
interface_type = forms.ChoiceField(
widget=forms.RadioSelect, choices=(
('static_interface', 'Static Interface'),
('dynamic_interface', 'Dynamic Interface')))
class Meta:
model = System
SystemAVForm = get_eav_form(SystemAV, System)
| <commit_before>from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
interface_type = forms.ChoiceField(
widget=forms.RadioSelect, choices=(
('Static', 'Static Interface'),
('Dynamic', 'Dynamic Interface')))
class Meta:
model = System
SystemAVForm = get_eav_form(SystemAV, System)
<commit_msg>Fix system form interface_type choices<commit_after> | from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
interface_type = forms.ChoiceField(
widget=forms.RadioSelect, choices=(
('static_interface', 'Static Interface'),
('dynamic_interface', 'Dynamic Interface')))
class Meta:
model = System
SystemAVForm = get_eav_form(SystemAV, System)
| from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
interface_type = forms.ChoiceField(
widget=forms.RadioSelect, choices=(
('Static', 'Static Interface'),
('Dynamic', 'Dynamic Interface')))
class Meta:
model = System
SystemAVForm = get_eav_form(SystemAV, System)
Fix system form interface_type choicesfrom django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
interface_type = forms.ChoiceField(
widget=forms.RadioSelect, choices=(
('static_interface', 'Static Interface'),
('dynamic_interface', 'Dynamic Interface')))
class Meta:
model = System
SystemAVForm = get_eav_form(SystemAV, System)
| <commit_before>from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
interface_type = forms.ChoiceField(
widget=forms.RadioSelect, choices=(
('Static', 'Static Interface'),
('Dynamic', 'Dynamic Interface')))
class Meta:
model = System
SystemAVForm = get_eav_form(SystemAV, System)
<commit_msg>Fix system form interface_type choices<commit_after>from django import forms
from cyder.base.eav.forms import get_eav_form
from cyder.base.mixins import UsabilityFormMixin
from cyder.core.system.models import System, SystemAV
class SystemForm(forms.ModelForm):
class Meta:
model = System
class ExtendedSystemForm(forms.ModelForm, UsabilityFormMixin):
interface_type = forms.ChoiceField(
widget=forms.RadioSelect, choices=(
('static_interface', 'Static Interface'),
('dynamic_interface', 'Dynamic Interface')))
class Meta:
model = System
SystemAVForm = get_eav_form(SystemAV, System)
|
8f6ee9e2f39803ba2d47a96f795d36655d18edfb | contentpages/tests.py | contentpages/tests.py | from django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
| from django.test import TestCase
from django.urls import reverse
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
| Remove unused import from contentpages test | Remove unused import from contentpages test
| Python | mit | bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject | from django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
Remove unused import from contentpages test | from django.test import TestCase
from django.urls import reverse
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
| <commit_before>from django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
<commit_msg>Remove unused import from contentpages test<commit_after> | from django.test import TestCase
from django.urls import reverse
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
| from django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
Remove unused import from contentpages testfrom django.test import TestCase
from django.urls import reverse
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
| <commit_before>from django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
<commit_msg>Remove unused import from contentpages test<commit_after>from django.test import TestCase
from django.urls import reverse
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
|
41e29433da8f7db803ddd76ac7c7d543c69ad41c | account_journal_period_close/tests/__init__.py | account_journal_period_close/tests/__init__.py | # -*- coding: utf-8 -*-
#
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contact a Free Software
# Service Company.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from . import test_account_journal_period_close
| # -*- coding: utf-8 -*-
#
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contact a Free Software
# Service Company.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from . import test_account_journal_period_close
checks = [
test_account_journal_period_close,
]
| Add checks list on tests init file | [ADD] Add checks list on tests init file
| Python | agpl-3.0 | open-synergy/account-financial-tools,factorlibre/account-financial-tools,damdam-s/account-financial-tools,VitalPet/account-financial-tools,credativUK/account-financial-tools,open-synergy/account-financial-tools,abstract-open-solutions/account-financial-tools,taktik/account-financial-tools,nagyv/account-financial-tools,acsone/account-financial-tools,adhoc-dev/oca-account-financial-tools,andrius-preimantas/account-financial-tools,Domatix/account-financial-tools,ClearCorp-dev/account-financial-tools,bringsvor/account-financial-tools,xpansa/account-financial-tools,Antiun/account-financial-tools,acsone/account-financial-tools,Endika/account-financial-tools,xpansa/account-financial-tools,OpenPymeMx/account-financial-tools,syci/account-financial-tools,vauxoo-dev/account-financial-tools,akretion/account-financial-tools,luc-demeyer/account-financial-tools,syci/account-financial-tools,damdam-s/account-financial-tools,alhashash/account-financial-tools,raycarnes/account-financial-tools,dvitme/account-financial-tools,rschnapka/account-financial-tools,adhoc-dev/oca-account-financial-tools,open-synergy/account-financial-tools,VitalPet/account-financial-tools,lepistone/account-financial-tools,yelizariev/account-financial-tools,andhit-r/account-financial-tools,amoya-dx/account-financial-tools,pedrobaeza/account-financial-tools,charbeljc/account-financial-tools,OpenPymeMx/account-financial-tools,factorlibre/account-financial-tools,credativUK/account-financial-tools,Antiun/account-financial-tools,nagyv/account-financial-tools,bringsvor/account-financial-tools,cysnake4713/account-financial-tools,pedrobaeza/account-financial-tools,dvitme/account-financial-tools,iDTLabssl/account-financial-tools,vauxoo-dev/account-financial-tools,iDTLabssl/account-financial-tools,Endika/account-financial-tools,amoya-dx/account-financial-tools,VitalPet/account-financial-tools,cysnake4713/account-financial-tools,yelizariev/account-financial-tools,Domatix/account-financial-tools,abstract-open-solutions/account-financial-tools,diagramsoftware/account-financial-tools,ClearCorp-dev/account-financial-tools,raycarnes/account-financial-tools,rschnapka/account-financial-tools,luc-demeyer/account-financial-tools,lepistone/account-financial-tools,DarkoNikolovski/account-financial-tools,Pexego/account-financial-tools,alhashash/account-financial-tools,andhit-r/account-financial-tools,Nowheresly/account-financial-tools,Domatix/account-financial-tools,acsone/account-financial-tools,OpenPymeMx/account-financial-tools,Pexego/account-financial-tools,akretion/account-financial-tools,DarkoNikolovski/account-financial-tools,diagramsoftware/account-financial-tools,taktik/account-financial-tools,Nowheresly/account-financial-tools,charbeljc/account-financial-tools,andrius-preimantas/account-financial-tools | # -*- coding: utf-8 -*-
#
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contact a Free Software
# Service Company.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from . import test_account_journal_period_close
[ADD] Add checks list on tests init file | # -*- coding: utf-8 -*-
#
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contact a Free Software
# Service Company.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from . import test_account_journal_period_close
checks = [
test_account_journal_period_close,
]
| <commit_before># -*- coding: utf-8 -*-
#
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contact a Free Software
# Service Company.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from . import test_account_journal_period_close
<commit_msg>[ADD] Add checks list on tests init file<commit_after> | # -*- coding: utf-8 -*-
#
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contact a Free Software
# Service Company.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from . import test_account_journal_period_close
checks = [
test_account_journal_period_close,
]
| # -*- coding: utf-8 -*-
#
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contact a Free Software
# Service Company.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from . import test_account_journal_period_close
[ADD] Add checks list on tests init file# -*- coding: utf-8 -*-
#
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contact a Free Software
# Service Company.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from . import test_account_journal_period_close
checks = [
test_account_journal_period_close,
]
| <commit_before># -*- coding: utf-8 -*-
#
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contact a Free Software
# Service Company.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from . import test_account_journal_period_close
<commit_msg>[ADD] Add checks list on tests init file<commit_after># -*- coding: utf-8 -*-
#
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contact a Free Software
# Service Company.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from . import test_account_journal_period_close
checks = [
test_account_journal_period_close,
]
|
0b0d26373f8f2f0cf869bce430eaaf6a84407f2c | src/nodeconductor_assembly_waldur/invoices/filters.py | src/nodeconductor_assembly_waldur/invoices/filters.py | import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.MultipleChoiceFilter(choices=models.Invoice.States.CHOICES)
class Meta(object):
model = models.Invoice
fields = ('customer_uuid', 'state', 'year', 'month')
class PaymentDetailsFilter(django_filters.FilterSet):
customer = UUIDFilter(name='customer__uuid')
customer_url = URLFilter(
view_name='customer-detail',
name='customer__uuid',
)
class Meta(object):
model = models.PaymentDetails
fields = [
'customer',
'customer_url',
]
| import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer = URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.MultipleChoiceFilter(choices=models.Invoice.States.CHOICES)
class Meta(object):
model = models.Invoice
fields = ('year', 'month')
class PaymentDetailsFilter(django_filters.FilterSet):
customer = URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = UUIDFilter(name='customer__uuid')
class Meta(object):
model = models.PaymentDetails
| Make filtering invoices and payment details by customer consistent with serializer (WAL-231) | Make filtering invoices and payment details by customer consistent with serializer (WAL-231)
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind | import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.MultipleChoiceFilter(choices=models.Invoice.States.CHOICES)
class Meta(object):
model = models.Invoice
fields = ('customer_uuid', 'state', 'year', 'month')
class PaymentDetailsFilter(django_filters.FilterSet):
customer = UUIDFilter(name='customer__uuid')
customer_url = URLFilter(
view_name='customer-detail',
name='customer__uuid',
)
class Meta(object):
model = models.PaymentDetails
fields = [
'customer',
'customer_url',
]
Make filtering invoices and payment details by customer consistent with serializer (WAL-231) | import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer = URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.MultipleChoiceFilter(choices=models.Invoice.States.CHOICES)
class Meta(object):
model = models.Invoice
fields = ('year', 'month')
class PaymentDetailsFilter(django_filters.FilterSet):
customer = URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = UUIDFilter(name='customer__uuid')
class Meta(object):
model = models.PaymentDetails
| <commit_before>import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.MultipleChoiceFilter(choices=models.Invoice.States.CHOICES)
class Meta(object):
model = models.Invoice
fields = ('customer_uuid', 'state', 'year', 'month')
class PaymentDetailsFilter(django_filters.FilterSet):
customer = UUIDFilter(name='customer__uuid')
customer_url = URLFilter(
view_name='customer-detail',
name='customer__uuid',
)
class Meta(object):
model = models.PaymentDetails
fields = [
'customer',
'customer_url',
]
<commit_msg>Make filtering invoices and payment details by customer consistent with serializer (WAL-231)<commit_after> | import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer = URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.MultipleChoiceFilter(choices=models.Invoice.States.CHOICES)
class Meta(object):
model = models.Invoice
fields = ('year', 'month')
class PaymentDetailsFilter(django_filters.FilterSet):
customer = URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = UUIDFilter(name='customer__uuid')
class Meta(object):
model = models.PaymentDetails
| import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.MultipleChoiceFilter(choices=models.Invoice.States.CHOICES)
class Meta(object):
model = models.Invoice
fields = ('customer_uuid', 'state', 'year', 'month')
class PaymentDetailsFilter(django_filters.FilterSet):
customer = UUIDFilter(name='customer__uuid')
customer_url = URLFilter(
view_name='customer-detail',
name='customer__uuid',
)
class Meta(object):
model = models.PaymentDetails
fields = [
'customer',
'customer_url',
]
Make filtering invoices and payment details by customer consistent with serializer (WAL-231)import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer = URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.MultipleChoiceFilter(choices=models.Invoice.States.CHOICES)
class Meta(object):
model = models.Invoice
fields = ('year', 'month')
class PaymentDetailsFilter(django_filters.FilterSet):
customer = URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = UUIDFilter(name='customer__uuid')
class Meta(object):
model = models.PaymentDetails
| <commit_before>import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.MultipleChoiceFilter(choices=models.Invoice.States.CHOICES)
class Meta(object):
model = models.Invoice
fields = ('customer_uuid', 'state', 'year', 'month')
class PaymentDetailsFilter(django_filters.FilterSet):
customer = UUIDFilter(name='customer__uuid')
customer_url = URLFilter(
view_name='customer-detail',
name='customer__uuid',
)
class Meta(object):
model = models.PaymentDetails
fields = [
'customer',
'customer_url',
]
<commit_msg>Make filtering invoices and payment details by customer consistent with serializer (WAL-231)<commit_after>import django_filters
from nodeconductor.core.filters import UUIDFilter, URLFilter
from . import models
class InvoiceFilter(django_filters.FilterSet):
customer = URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = UUIDFilter(name='customer__uuid')
state = django_filters.MultipleChoiceFilter(choices=models.Invoice.States.CHOICES)
class Meta(object):
model = models.Invoice
fields = ('year', 'month')
class PaymentDetailsFilter(django_filters.FilterSet):
customer = URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = UUIDFilter(name='customer__uuid')
class Meta(object):
model = models.PaymentDetails
|
3cb07a7f547b4187c918e7340d15c172cb9a7231 | fabfile.py | fabfile.py | #!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True
fab_api.env.hosts = settings.ENV_HOSTS
fab_api.env.warn_only = True
def update_remotes():
try:
fab_api.run('~/bin/src-git-pull')
except fab_ex.NetworkError as ex:
print(ex)
| #!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True
fab_api.env.hosts = settings.ENV_HOSTS
fab_api.env.warn_only = True
def update_remotes():
if not fab_api.env.hosts:
print('Empty tuple of remote hosts. Exiting...')
return
try:
fab_api.run('~/bin/src-git-pull')
except fab_ex.NetworkError as ex:
print(ex)
| Exit if tuple of remote hosts is empty. | Exit if tuple of remote hosts is empty.
| Python | apache-2.0 | gasull/src-git-pull | #!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True
fab_api.env.hosts = settings.ENV_HOSTS
fab_api.env.warn_only = True
def update_remotes():
try:
fab_api.run('~/bin/src-git-pull')
except fab_ex.NetworkError as ex:
print(ex)
Exit if tuple of remote hosts is empty. | #!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True
fab_api.env.hosts = settings.ENV_HOSTS
fab_api.env.warn_only = True
def update_remotes():
if not fab_api.env.hosts:
print('Empty tuple of remote hosts. Exiting...')
return
try:
fab_api.run('~/bin/src-git-pull')
except fab_ex.NetworkError as ex:
print(ex)
| <commit_before>#!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True
fab_api.env.hosts = settings.ENV_HOSTS
fab_api.env.warn_only = True
def update_remotes():
try:
fab_api.run('~/bin/src-git-pull')
except fab_ex.NetworkError as ex:
print(ex)
<commit_msg>Exit if tuple of remote hosts is empty.<commit_after> | #!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True
fab_api.env.hosts = settings.ENV_HOSTS
fab_api.env.warn_only = True
def update_remotes():
if not fab_api.env.hosts:
print('Empty tuple of remote hosts. Exiting...')
return
try:
fab_api.run('~/bin/src-git-pull')
except fab_ex.NetworkError as ex:
print(ex)
| #!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True
fab_api.env.hosts = settings.ENV_HOSTS
fab_api.env.warn_only = True
def update_remotes():
try:
fab_api.run('~/bin/src-git-pull')
except fab_ex.NetworkError as ex:
print(ex)
Exit if tuple of remote hosts is empty.#!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True
fab_api.env.hosts = settings.ENV_HOSTS
fab_api.env.warn_only = True
def update_remotes():
if not fab_api.env.hosts:
print('Empty tuple of remote hosts. Exiting...')
return
try:
fab_api.run('~/bin/src-git-pull')
except fab_ex.NetworkError as ex:
print(ex)
| <commit_before>#!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True
fab_api.env.hosts = settings.ENV_HOSTS
fab_api.env.warn_only = True
def update_remotes():
try:
fab_api.run('~/bin/src-git-pull')
except fab_ex.NetworkError as ex:
print(ex)
<commit_msg>Exit if tuple of remote hosts is empty.<commit_after>#!/usr/bin/env python
# update_remotes
# Updates all my remote machines
#
# Author: Daniel Gonzalez Gasull
import sys
from fabric import api as fab_api
from fabric import exceptions as fab_ex
try:
import settings
except ImportError:
print('No settings file')
sys.exit()
fab_api.env.use_ssh_config = True
fab_api.env.hosts = settings.ENV_HOSTS
fab_api.env.warn_only = True
def update_remotes():
if not fab_api.env.hosts:
print('Empty tuple of remote hosts. Exiting...')
return
try:
fab_api.run('~/bin/src-git-pull')
except fab_ex.NetworkError as ex:
print(ex)
|
a75dc02612fd2159731d8fdc04e85a2fbc0138d0 | bvspca/core/templatetags/utility_tags.py | bvspca/core/templatetags/utility_tags.py | from django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.assignment_tag
def get_google_maps_key():
return getattr(settings, 'GOOGLE_MAPS_KEY', "")
@register.assignment_tag
def get_google_analytics_id():
return getattr(settings, 'GOOGLE_ANALYTICS_ID', "")
| from django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.simple_tag
def get_google_maps_key():
return getattr(settings, 'GOOGLE_MAPS_KEY', "")
@register.simple_tag
def get_google_analytics_id():
return getattr(settings, 'GOOGLE_ANALYTICS_ID', "")
| Switch from deprecated assignment tags to simple tags | Switch from deprecated assignment tags to simple tags
| Python | mit | nfletton/bvspca,nfletton/bvspca,nfletton/bvspca,nfletton/bvspca | from django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.assignment_tag
def get_google_maps_key():
return getattr(settings, 'GOOGLE_MAPS_KEY', "")
@register.assignment_tag
def get_google_analytics_id():
return getattr(settings, 'GOOGLE_ANALYTICS_ID', "")
Switch from deprecated assignment tags to simple tags | from django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.simple_tag
def get_google_maps_key():
return getattr(settings, 'GOOGLE_MAPS_KEY', "")
@register.simple_tag
def get_google_analytics_id():
return getattr(settings, 'GOOGLE_ANALYTICS_ID', "")
| <commit_before>from django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.assignment_tag
def get_google_maps_key():
return getattr(settings, 'GOOGLE_MAPS_KEY', "")
@register.assignment_tag
def get_google_analytics_id():
return getattr(settings, 'GOOGLE_ANALYTICS_ID', "")
<commit_msg>Switch from deprecated assignment tags to simple tags<commit_after> | from django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.simple_tag
def get_google_maps_key():
return getattr(settings, 'GOOGLE_MAPS_KEY', "")
@register.simple_tag
def get_google_analytics_id():
return getattr(settings, 'GOOGLE_ANALYTICS_ID', "")
| from django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.assignment_tag
def get_google_maps_key():
return getattr(settings, 'GOOGLE_MAPS_KEY', "")
@register.assignment_tag
def get_google_analytics_id():
return getattr(settings, 'GOOGLE_ANALYTICS_ID', "")
Switch from deprecated assignment tags to simple tagsfrom django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.simple_tag
def get_google_maps_key():
return getattr(settings, 'GOOGLE_MAPS_KEY', "")
@register.simple_tag
def get_google_analytics_id():
return getattr(settings, 'GOOGLE_ANALYTICS_ID', "")
| <commit_before>from django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.assignment_tag
def get_google_maps_key():
return getattr(settings, 'GOOGLE_MAPS_KEY', "")
@register.assignment_tag
def get_google_analytics_id():
return getattr(settings, 'GOOGLE_ANALYTICS_ID', "")
<commit_msg>Switch from deprecated assignment tags to simple tags<commit_after>from django import template
from django.conf import settings
register = template.Library()
@register.filter
def to_css_name(value):
return value.lower().replace(' ', '-')
@register.filter
def get_property(instance, key):
return getattr(instance, key)
@register.simple_tag
def get_google_maps_key():
return getattr(settings, 'GOOGLE_MAPS_KEY', "")
@register.simple_tag
def get_google_analytics_id():
return getattr(settings, 'GOOGLE_ANALYTICS_ID', "")
|
c37269b8e1ea62773a2af1a04676d6d74aac0850 | apps/chats/urls.py | apps/chats/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns('chats.views',
url('^chats/$', 'index', name='chats_index'),
url('^chats/new/$', 'new', name='chats_new'),
url('^chats/(?P<id>\d+)/$', 'show', name='chats_show'),
)
| from django.conf.urls.defaults import *
urlpatterns = patterns('chats.views',
url('^chats/$', 'index', name='chats-index'),
url('^chats/new/$', 'new', name='chats-new'),
url('^chats/(?P<id>\d+)/$', 'show', name='chats-show'),
)
| Use dashes in url names | Use dashes in url names
| Python | mit | tofumatt/quotes,tofumatt/quotes | from django.conf.urls.defaults import *
urlpatterns = patterns('chats.views',
url('^chats/$', 'index', name='chats_index'),
url('^chats/new/$', 'new', name='chats_new'),
url('^chats/(?P<id>\d+)/$', 'show', name='chats_show'),
)
Use dashes in url names | from django.conf.urls.defaults import *
urlpatterns = patterns('chats.views',
url('^chats/$', 'index', name='chats-index'),
url('^chats/new/$', 'new', name='chats-new'),
url('^chats/(?P<id>\d+)/$', 'show', name='chats-show'),
)
| <commit_before>from django.conf.urls.defaults import *
urlpatterns = patterns('chats.views',
url('^chats/$', 'index', name='chats_index'),
url('^chats/new/$', 'new', name='chats_new'),
url('^chats/(?P<id>\d+)/$', 'show', name='chats_show'),
)
<commit_msg>Use dashes in url names<commit_after> | from django.conf.urls.defaults import *
urlpatterns = patterns('chats.views',
url('^chats/$', 'index', name='chats-index'),
url('^chats/new/$', 'new', name='chats-new'),
url('^chats/(?P<id>\d+)/$', 'show', name='chats-show'),
)
| from django.conf.urls.defaults import *
urlpatterns = patterns('chats.views',
url('^chats/$', 'index', name='chats_index'),
url('^chats/new/$', 'new', name='chats_new'),
url('^chats/(?P<id>\d+)/$', 'show', name='chats_show'),
)
Use dashes in url namesfrom django.conf.urls.defaults import *
urlpatterns = patterns('chats.views',
url('^chats/$', 'index', name='chats-index'),
url('^chats/new/$', 'new', name='chats-new'),
url('^chats/(?P<id>\d+)/$', 'show', name='chats-show'),
)
| <commit_before>from django.conf.urls.defaults import *
urlpatterns = patterns('chats.views',
url('^chats/$', 'index', name='chats_index'),
url('^chats/new/$', 'new', name='chats_new'),
url('^chats/(?P<id>\d+)/$', 'show', name='chats_show'),
)
<commit_msg>Use dashes in url names<commit_after>from django.conf.urls.defaults import *
urlpatterns = patterns('chats.views',
url('^chats/$', 'index', name='chats-index'),
url('^chats/new/$', 'new', name='chats-new'),
url('^chats/(?P<id>\d+)/$', 'show', name='chats-show'),
)
|
d314bb50e5769c6f6d46383e12397b27cca633ca | appstats/config.py | appstats/config.py | REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format=None, visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
| REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format='count', visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
| Change NUMBER field format: None -> count | Change NUMBER field format: None -> count
| Python | mit | uvNikita/appstats,uvNikita/appstats,uvNikita/appstats | REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format=None, visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
Change NUMBER field format: None -> count | REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format='count', visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
| <commit_before>REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format=None, visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
<commit_msg>Change NUMBER field format: None -> count<commit_after> | REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format='count', visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
| REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format=None, visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
Change NUMBER field format: None -> countREDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format='count', visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
| <commit_before>REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format=None, visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
<commit_msg>Change NUMBER field format: None -> count<commit_after>REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format='count', visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
|
1caccbc11a17c1f01d802ec0dc3d52d5de9d5049 | coda/coda_replication/tests/test_urls.py | coda/coda_replication/tests/test_urls.py | import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
def test_queue_recent():
assert resolve('/queue/').func == views.queue_recent
def test_queue_html():
assert resolve('/queue/ark:/00001/codajom1/').func == views.queue_html
def test_queue_search():
assert resolve('/queue/search/').func == views.queue_search
def test_queue_stats():
assert resolve('/queue/stats/').func == views.queue_stats
| import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
def test_queue_recent():
assert resolve('/queue/').func == views.queue_recent
def test_queue_html():
assert resolve('/queue/ark:/00001/codajom1/').func == views.queue_html
def test_queue_search():
assert resolve('/queue/search/').func == views.queue_search
def test_queue_search_JSON():
assert resolve('/queue/search.json').func == views.queue_search_JSON
def test_queue_stats():
assert resolve('/queue/stats/').func == views.queue_stats
| Add a test for queue_search_JSON. | Add a test for queue_search_JSON.
| Python | bsd-3-clause | unt-libraries/coda,unt-libraries/coda,unt-libraries/coda,unt-libraries/coda | import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
def test_queue_recent():
assert resolve('/queue/').func == views.queue_recent
def test_queue_html():
assert resolve('/queue/ark:/00001/codajom1/').func == views.queue_html
def test_queue_search():
assert resolve('/queue/search/').func == views.queue_search
def test_queue_stats():
assert resolve('/queue/stats/').func == views.queue_stats
Add a test for queue_search_JSON. | import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
def test_queue_recent():
assert resolve('/queue/').func == views.queue_recent
def test_queue_html():
assert resolve('/queue/ark:/00001/codajom1/').func == views.queue_html
def test_queue_search():
assert resolve('/queue/search/').func == views.queue_search
def test_queue_search_JSON():
assert resolve('/queue/search.json').func == views.queue_search_JSON
def test_queue_stats():
assert resolve('/queue/stats/').func == views.queue_stats
| <commit_before>import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
def test_queue_recent():
assert resolve('/queue/').func == views.queue_recent
def test_queue_html():
assert resolve('/queue/ark:/00001/codajom1/').func == views.queue_html
def test_queue_search():
assert resolve('/queue/search/').func == views.queue_search
def test_queue_stats():
assert resolve('/queue/stats/').func == views.queue_stats
<commit_msg>Add a test for queue_search_JSON.<commit_after> | import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
def test_queue_recent():
assert resolve('/queue/').func == views.queue_recent
def test_queue_html():
assert resolve('/queue/ark:/00001/codajom1/').func == views.queue_html
def test_queue_search():
assert resolve('/queue/search/').func == views.queue_search
def test_queue_search_JSON():
assert resolve('/queue/search.json').func == views.queue_search_JSON
def test_queue_stats():
assert resolve('/queue/stats/').func == views.queue_stats
| import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
def test_queue_recent():
assert resolve('/queue/').func == views.queue_recent
def test_queue_html():
assert resolve('/queue/ark:/00001/codajom1/').func == views.queue_html
def test_queue_search():
assert resolve('/queue/search/').func == views.queue_search
def test_queue_stats():
assert resolve('/queue/stats/').func == views.queue_stats
Add a test for queue_search_JSON.import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
def test_queue_recent():
assert resolve('/queue/').func == views.queue_recent
def test_queue_html():
assert resolve('/queue/ark:/00001/codajom1/').func == views.queue_html
def test_queue_search():
assert resolve('/queue/search/').func == views.queue_search
def test_queue_search_JSON():
assert resolve('/queue/search.json').func == views.queue_search_JSON
def test_queue_stats():
assert resolve('/queue/stats/').func == views.queue_stats
| <commit_before>import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
def test_queue_recent():
assert resolve('/queue/').func == views.queue_recent
def test_queue_html():
assert resolve('/queue/ark:/00001/codajom1/').func == views.queue_html
def test_queue_search():
assert resolve('/queue/search/').func == views.queue_search
def test_queue_stats():
assert resolve('/queue/stats/').func == views.queue_stats
<commit_msg>Add a test for queue_search_JSON.<commit_after>import pytest
from django.core.urlresolvers import resolve
from .. import views
pytestmark = pytest.mark.urls('coda_replication.urls')
def test_queue():
assert resolve('/APP/queue/ark:/00001/codajom1/').func == views.queue
def test_queue_collection():
assert resolve('/APP/queue/').func == views.queue
def test_queue_recent():
assert resolve('/queue/').func == views.queue_recent
def test_queue_html():
assert resolve('/queue/ark:/00001/codajom1/').func == views.queue_html
def test_queue_search():
assert resolve('/queue/search/').func == views.queue_search
def test_queue_search_JSON():
assert resolve('/queue/search.json').func == views.queue_search_JSON
def test_queue_stats():
assert resolve('/queue/stats/').func == views.queue_stats
|
5d2649fc005e514452c8d83f103b4fd2c5b03519 | tailor/output/printer.py | tailor/output/printer.py | import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Location(1, 1)):
self.__print('error', err_msg, ctx, loc)
def __print(self, classification, msg, ctx, loc):
if ctx is not None:
print(self.__filepath + ':' + str(ctx.start.line) + ':' +
str(ctx.start.column) + ': ' + classification + ': ' + msg)
else:
print(self.__filepath + ':' + str(loc.line) + ':' +
str(loc.column) + ': ' + classification + ': ' + msg)
| import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Location(1, 1)):
self.__print('error', err_msg, ctx, loc)
def __print(self, classification, msg, ctx, loc):
if ctx is not None:
print(self.__filepath + ':' + str(ctx.start.line) + ':' +
str(ctx.start.column + 1) + ': ' +
classification + ': ' + msg)
else:
print(self.__filepath + ':' + str(loc.line) + ':' +
str(loc.column) + ': ' + classification + ': ' + msg)
| Increment column to be printed by 1 | Increment column to be printed by 1
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor | import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Location(1, 1)):
self.__print('error', err_msg, ctx, loc)
def __print(self, classification, msg, ctx, loc):
if ctx is not None:
print(self.__filepath + ':' + str(ctx.start.line) + ':' +
str(ctx.start.column) + ': ' + classification + ': ' + msg)
else:
print(self.__filepath + ':' + str(loc.line) + ':' +
str(loc.column) + ': ' + classification + ': ' + msg)
Increment column to be printed by 1 | import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Location(1, 1)):
self.__print('error', err_msg, ctx, loc)
def __print(self, classification, msg, ctx, loc):
if ctx is not None:
print(self.__filepath + ':' + str(ctx.start.line) + ':' +
str(ctx.start.column + 1) + ': ' +
classification + ': ' + msg)
else:
print(self.__filepath + ':' + str(loc.line) + ':' +
str(loc.column) + ': ' + classification + ': ' + msg)
| <commit_before>import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Location(1, 1)):
self.__print('error', err_msg, ctx, loc)
def __print(self, classification, msg, ctx, loc):
if ctx is not None:
print(self.__filepath + ':' + str(ctx.start.line) + ':' +
str(ctx.start.column) + ': ' + classification + ': ' + msg)
else:
print(self.__filepath + ':' + str(loc.line) + ':' +
str(loc.column) + ': ' + classification + ': ' + msg)
<commit_msg>Increment column to be printed by 1<commit_after> | import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Location(1, 1)):
self.__print('error', err_msg, ctx, loc)
def __print(self, classification, msg, ctx, loc):
if ctx is not None:
print(self.__filepath + ':' + str(ctx.start.line) + ':' +
str(ctx.start.column + 1) + ': ' +
classification + ': ' + msg)
else:
print(self.__filepath + ':' + str(loc.line) + ':' +
str(loc.column) + ': ' + classification + ': ' + msg)
| import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Location(1, 1)):
self.__print('error', err_msg, ctx, loc)
def __print(self, classification, msg, ctx, loc):
if ctx is not None:
print(self.__filepath + ':' + str(ctx.start.line) + ':' +
str(ctx.start.column) + ': ' + classification + ': ' + msg)
else:
print(self.__filepath + ':' + str(loc.line) + ':' +
str(loc.column) + ': ' + classification + ': ' + msg)
Increment column to be printed by 1import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Location(1, 1)):
self.__print('error', err_msg, ctx, loc)
def __print(self, classification, msg, ctx, loc):
if ctx is not None:
print(self.__filepath + ':' + str(ctx.start.line) + ':' +
str(ctx.start.column + 1) + ': ' +
classification + ': ' + msg)
else:
print(self.__filepath + ':' + str(loc.line) + ':' +
str(loc.column) + ': ' + classification + ': ' + msg)
| <commit_before>import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Location(1, 1)):
self.__print('error', err_msg, ctx, loc)
def __print(self, classification, msg, ctx, loc):
if ctx is not None:
print(self.__filepath + ':' + str(ctx.start.line) + ':' +
str(ctx.start.column) + ': ' + classification + ': ' + msg)
else:
print(self.__filepath + ':' + str(loc.line) + ':' +
str(loc.column) + ': ' + classification + ': ' + msg)
<commit_msg>Increment column to be printed by 1<commit_after>import os
from tailor.types.location import Location
class Printer:
def __init__(self, filepath):
self.__filepath = os.path.abspath(filepath)
def warn(self, warn_msg, ctx=None, loc=Location(1, 1)):
self.__print('warning', warn_msg, ctx, loc)
def error(self, err_msg, ctx=None, loc=Location(1, 1)):
self.__print('error', err_msg, ctx, loc)
def __print(self, classification, msg, ctx, loc):
if ctx is not None:
print(self.__filepath + ':' + str(ctx.start.line) + ':' +
str(ctx.start.column + 1) + ': ' +
classification + ': ' + msg)
else:
print(self.__filepath + ':' + str(loc.line) + ':' +
str(loc.column) + ': ' + classification + ': ' + msg)
|
b342ce094593f5921332140a9de69b0bdeba9ede | example.py | example.py | #!/usr/bin/env python
import logging
from ina219 import INA219
SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2
def read():
ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, log_level=logging.INFO)
ina.configure(ina.RANGE_16V, ina.GAIN_AUTO)
print ("Bus Voltage : %.3f V" % ina.voltage())
print ("Bus Current : %.3f mA" % ina.current())
print ("Supply Voltage : %.3f V" % ina.supply_voltage())
print ("Shunt voltage : %.3f mV" % ina.shunt_voltage())
print ("Power : %.3f mW" % ina.power())
if __name__ == "__main__":
read()
| #!/usr/bin/env python
import logging
from ina219 import INA219
SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2
def read():
ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, log_level=logging.INFO)
ina.configure(ina.RANGE_16V, ina.GAIN_AUTO)
print("Bus Voltage : %.3f V" % ina.voltage())
print("Bus Current : %.3f mA" % ina.current())
print("Supply Voltage : %.3f V" % ina.supply_voltage())
print("Shunt voltage : %.3f mV" % ina.shunt_voltage())
print("Power : %.3f mW" % ina.power())
if __name__ == "__main__":
read()
| Fix flake8 error in Python 3 build | Fix flake8 error in Python 3 build
| Python | mit | chrisb2/pi_ina219 | #!/usr/bin/env python
import logging
from ina219 import INA219
SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2
def read():
ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, log_level=logging.INFO)
ina.configure(ina.RANGE_16V, ina.GAIN_AUTO)
print ("Bus Voltage : %.3f V" % ina.voltage())
print ("Bus Current : %.3f mA" % ina.current())
print ("Supply Voltage : %.3f V" % ina.supply_voltage())
print ("Shunt voltage : %.3f mV" % ina.shunt_voltage())
print ("Power : %.3f mW" % ina.power())
if __name__ == "__main__":
read()
Fix flake8 error in Python 3 build | #!/usr/bin/env python
import logging
from ina219 import INA219
SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2
def read():
ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, log_level=logging.INFO)
ina.configure(ina.RANGE_16V, ina.GAIN_AUTO)
print("Bus Voltage : %.3f V" % ina.voltage())
print("Bus Current : %.3f mA" % ina.current())
print("Supply Voltage : %.3f V" % ina.supply_voltage())
print("Shunt voltage : %.3f mV" % ina.shunt_voltage())
print("Power : %.3f mW" % ina.power())
if __name__ == "__main__":
read()
| <commit_before>#!/usr/bin/env python
import logging
from ina219 import INA219
SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2
def read():
ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, log_level=logging.INFO)
ina.configure(ina.RANGE_16V, ina.GAIN_AUTO)
print ("Bus Voltage : %.3f V" % ina.voltage())
print ("Bus Current : %.3f mA" % ina.current())
print ("Supply Voltage : %.3f V" % ina.supply_voltage())
print ("Shunt voltage : %.3f mV" % ina.shunt_voltage())
print ("Power : %.3f mW" % ina.power())
if __name__ == "__main__":
read()
<commit_msg>Fix flake8 error in Python 3 build<commit_after> | #!/usr/bin/env python
import logging
from ina219 import INA219
SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2
def read():
ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, log_level=logging.INFO)
ina.configure(ina.RANGE_16V, ina.GAIN_AUTO)
print("Bus Voltage : %.3f V" % ina.voltage())
print("Bus Current : %.3f mA" % ina.current())
print("Supply Voltage : %.3f V" % ina.supply_voltage())
print("Shunt voltage : %.3f mV" % ina.shunt_voltage())
print("Power : %.3f mW" % ina.power())
if __name__ == "__main__":
read()
| #!/usr/bin/env python
import logging
from ina219 import INA219
SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2
def read():
ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, log_level=logging.INFO)
ina.configure(ina.RANGE_16V, ina.GAIN_AUTO)
print ("Bus Voltage : %.3f V" % ina.voltage())
print ("Bus Current : %.3f mA" % ina.current())
print ("Supply Voltage : %.3f V" % ina.supply_voltage())
print ("Shunt voltage : %.3f mV" % ina.shunt_voltage())
print ("Power : %.3f mW" % ina.power())
if __name__ == "__main__":
read()
Fix flake8 error in Python 3 build#!/usr/bin/env python
import logging
from ina219 import INA219
SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2
def read():
ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, log_level=logging.INFO)
ina.configure(ina.RANGE_16V, ina.GAIN_AUTO)
print("Bus Voltage : %.3f V" % ina.voltage())
print("Bus Current : %.3f mA" % ina.current())
print("Supply Voltage : %.3f V" % ina.supply_voltage())
print("Shunt voltage : %.3f mV" % ina.shunt_voltage())
print("Power : %.3f mW" % ina.power())
if __name__ == "__main__":
read()
| <commit_before>#!/usr/bin/env python
import logging
from ina219 import INA219
SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2
def read():
ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, log_level=logging.INFO)
ina.configure(ina.RANGE_16V, ina.GAIN_AUTO)
print ("Bus Voltage : %.3f V" % ina.voltage())
print ("Bus Current : %.3f mA" % ina.current())
print ("Supply Voltage : %.3f V" % ina.supply_voltage())
print ("Shunt voltage : %.3f mV" % ina.shunt_voltage())
print ("Power : %.3f mW" % ina.power())
if __name__ == "__main__":
read()
<commit_msg>Fix flake8 error in Python 3 build<commit_after>#!/usr/bin/env python
import logging
from ina219 import INA219
SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2
def read():
ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, log_level=logging.INFO)
ina.configure(ina.RANGE_16V, ina.GAIN_AUTO)
print("Bus Voltage : %.3f V" % ina.voltage())
print("Bus Current : %.3f mA" % ina.current())
print("Supply Voltage : %.3f V" % ina.supply_voltage())
print("Shunt voltage : %.3f mV" % ina.shunt_voltage())
print("Power : %.3f mW" % ina.power())
if __name__ == "__main__":
read()
|
617df13670573b858b6c23249f4287786807d8b6 | website/notifications/listeners.py | website/notifications/listeners.py | import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.institution_id or node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
| import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
| Remove incorrect check for institution_id | Remove incorrect check for institution_id
Fixes https://sentry.cos.io/sentry/osf-iy/issues/273424/
| Python | apache-2.0 | brianjgeiger/osf.io,adlius/osf.io,erinspace/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,cslzchen/osf.io,Nesiehr/osf.io,chennan47/osf.io,caneruguz/osf.io,acshi/osf.io,leb2dg/osf.io,chrisseto/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,laurenrevere/osf.io,acshi/osf.io,pattisdr/osf.io,aaxelb/osf.io,aaxelb/osf.io,acshi/osf.io,Johnetordoff/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,mattclark/osf.io,hmoco/osf.io,adlius/osf.io,mfraezz/osf.io,binoculars/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,binoculars/osf.io,crcresearch/osf.io,leb2dg/osf.io,cwisecarver/osf.io,felliott/osf.io,cwisecarver/osf.io,Nesiehr/osf.io,chrisseto/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,baylee-d/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,sloria/osf.io,icereval/osf.io,aaxelb/osf.io,felliott/osf.io,pattisdr/osf.io,hmoco/osf.io,caseyrollins/osf.io,adlius/osf.io,saradbowman/osf.io,cslzchen/osf.io,chrisseto/osf.io,hmoco/osf.io,felliott/osf.io,mfraezz/osf.io,laurenrevere/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,mattclark/osf.io,cslzchen/osf.io,laurenrevere/osf.io,cwisecarver/osf.io,brianjgeiger/osf.io,crcresearch/osf.io,chennan47/osf.io,acshi/osf.io,adlius/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,icereval/osf.io,mfraezz/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,hmoco/osf.io,caneruguz/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,Nesiehr/osf.io,acshi/osf.io,TomBaxter/osf.io,binoculars/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,felliott/osf.io,leb2dg/osf.io,caseyrollins/osf.io,Nesiehr/osf.io,mattclark/osf.io,baylee-d/osf.io,pattisdr/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,erinspace/osf.io,TomBaxter/osf.io,saradbowman/osf.io,icereval/osf.io,chennan47/osf.io,sloria/osf.io | import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.institution_id or node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
Remove incorrect check for institution_id
Fixes https://sentry.cos.io/sentry/osf-iy/issues/273424/ | import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
| <commit_before>import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.institution_id or node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
<commit_msg>Remove incorrect check for institution_id
Fixes https://sentry.cos.io/sentry/osf-iy/issues/273424/<commit_after> | import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
| import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.institution_id or node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
Remove incorrect check for institution_id
Fixes https://sentry.cos.io/sentry/osf-iy/issues/273424/import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
| <commit_before>import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.institution_id or node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
<commit_msg>Remove incorrect check for institution_id
Fixes https://sentry.cos.io/sentry/osf-iy/issues/273424/<commit_after>import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
|
95fe3ba491c539780f8876faf3504a366ec2ca56 | yowsup/layers/protocol_iq/layer.py | yowsup/layers/protocol_iq/layer.py | from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Iq Layer"
def sendIq(self, entity):
if entity.getXmlns() == "w:p":
self.toLower(entity.toProtocolTreeNode())
elif entity.getXmlns() in ("urn:xmpp:whatsapp:push", "w", "urn:xmpp:whatsapp:account", "encrypt"):
self.toLower(entity.toProtocolTreeNode())
def recvIq(self, node):
if node["xmlns"] == "urn:xmpp:ping":
entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"])
self.toLower(entity.toProtocolTreeNode())
elif node["type"] == "error":
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
elif node["type"] == "result" and not len(node.getAllChildren()):
#allowing only unidentifiable result (has no children) iq through this layer. (ex: ping result)
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(node)) | from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Iq Layer"
def onPong(self, protocolTreeNode, pingEntity):
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(protocolTreeNode))
def sendIq(self, entity):
if entity.getXmlns() == "w:p":
self._sendIq(entity, self.onPong)
elif entity.getXmlns() in ("urn:xmpp:whatsapp:push", "w", "urn:xmpp:whatsapp:account", "encrypt"):
self.toLower(entity.toProtocolTreeNode())
def recvIq(self, node):
if node["xmlns"] == "urn:xmpp:ping":
entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"])
self.toLower(entity.toProtocolTreeNode())
| Use _sendIq for handling pongs | Use _sendIq for handling pongs
| Python | mit | biji/yowsup,ongair/yowsup | from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Iq Layer"
def sendIq(self, entity):
if entity.getXmlns() == "w:p":
self.toLower(entity.toProtocolTreeNode())
elif entity.getXmlns() in ("urn:xmpp:whatsapp:push", "w", "urn:xmpp:whatsapp:account", "encrypt"):
self.toLower(entity.toProtocolTreeNode())
def recvIq(self, node):
if node["xmlns"] == "urn:xmpp:ping":
entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"])
self.toLower(entity.toProtocolTreeNode())
elif node["type"] == "error":
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
elif node["type"] == "result" and not len(node.getAllChildren()):
#allowing only unidentifiable result (has no children) iq through this layer. (ex: ping result)
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(node))Use _sendIq for handling pongs | from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Iq Layer"
def onPong(self, protocolTreeNode, pingEntity):
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(protocolTreeNode))
def sendIq(self, entity):
if entity.getXmlns() == "w:p":
self._sendIq(entity, self.onPong)
elif entity.getXmlns() in ("urn:xmpp:whatsapp:push", "w", "urn:xmpp:whatsapp:account", "encrypt"):
self.toLower(entity.toProtocolTreeNode())
def recvIq(self, node):
if node["xmlns"] == "urn:xmpp:ping":
entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"])
self.toLower(entity.toProtocolTreeNode())
| <commit_before>from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Iq Layer"
def sendIq(self, entity):
if entity.getXmlns() == "w:p":
self.toLower(entity.toProtocolTreeNode())
elif entity.getXmlns() in ("urn:xmpp:whatsapp:push", "w", "urn:xmpp:whatsapp:account", "encrypt"):
self.toLower(entity.toProtocolTreeNode())
def recvIq(self, node):
if node["xmlns"] == "urn:xmpp:ping":
entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"])
self.toLower(entity.toProtocolTreeNode())
elif node["type"] == "error":
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
elif node["type"] == "result" and not len(node.getAllChildren()):
#allowing only unidentifiable result (has no children) iq through this layer. (ex: ping result)
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(node))<commit_msg>Use _sendIq for handling pongs<commit_after> | from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Iq Layer"
def onPong(self, protocolTreeNode, pingEntity):
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(protocolTreeNode))
def sendIq(self, entity):
if entity.getXmlns() == "w:p":
self._sendIq(entity, self.onPong)
elif entity.getXmlns() in ("urn:xmpp:whatsapp:push", "w", "urn:xmpp:whatsapp:account", "encrypt"):
self.toLower(entity.toProtocolTreeNode())
def recvIq(self, node):
if node["xmlns"] == "urn:xmpp:ping":
entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"])
self.toLower(entity.toProtocolTreeNode())
| from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Iq Layer"
def sendIq(self, entity):
if entity.getXmlns() == "w:p":
self.toLower(entity.toProtocolTreeNode())
elif entity.getXmlns() in ("urn:xmpp:whatsapp:push", "w", "urn:xmpp:whatsapp:account", "encrypt"):
self.toLower(entity.toProtocolTreeNode())
def recvIq(self, node):
if node["xmlns"] == "urn:xmpp:ping":
entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"])
self.toLower(entity.toProtocolTreeNode())
elif node["type"] == "error":
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
elif node["type"] == "result" and not len(node.getAllChildren()):
#allowing only unidentifiable result (has no children) iq through this layer. (ex: ping result)
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(node))Use _sendIq for handling pongsfrom yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Iq Layer"
def onPong(self, protocolTreeNode, pingEntity):
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(protocolTreeNode))
def sendIq(self, entity):
if entity.getXmlns() == "w:p":
self._sendIq(entity, self.onPong)
elif entity.getXmlns() in ("urn:xmpp:whatsapp:push", "w", "urn:xmpp:whatsapp:account", "encrypt"):
self.toLower(entity.toProtocolTreeNode())
def recvIq(self, node):
if node["xmlns"] == "urn:xmpp:ping":
entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"])
self.toLower(entity.toProtocolTreeNode())
| <commit_before>from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Iq Layer"
def sendIq(self, entity):
if entity.getXmlns() == "w:p":
self.toLower(entity.toProtocolTreeNode())
elif entity.getXmlns() in ("urn:xmpp:whatsapp:push", "w", "urn:xmpp:whatsapp:account", "encrypt"):
self.toLower(entity.toProtocolTreeNode())
def recvIq(self, node):
if node["xmlns"] == "urn:xmpp:ping":
entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"])
self.toLower(entity.toProtocolTreeNode())
elif node["type"] == "error":
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
elif node["type"] == "result" and not len(node.getAllChildren()):
#allowing only unidentifiable result (has no children) iq through this layer. (ex: ping result)
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(node))<commit_msg>Use _sendIq for handling pongs<commit_after>from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
def __str__(self):
return "Iq Layer"
def onPong(self, protocolTreeNode, pingEntity):
self.toUpper(ResultIqProtocolEntity.fromProtocolTreeNode(protocolTreeNode))
def sendIq(self, entity):
if entity.getXmlns() == "w:p":
self._sendIq(entity, self.onPong)
elif entity.getXmlns() in ("urn:xmpp:whatsapp:push", "w", "urn:xmpp:whatsapp:account", "encrypt"):
self.toLower(entity.toProtocolTreeNode())
def recvIq(self, node):
if node["xmlns"] == "urn:xmpp:ping":
entity = PongResultIqProtocolEntity(YowConstants.DOMAIN, node["id"])
self.toLower(entity.toProtocolTreeNode())
|
9e148028300a46f9074b9f188dc04d87884c8905 | rsr/headerbar.py | rsr/headerbar.py | from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
btn = Gtk.Button()
icon = Gio.ThemedIcon(name="preferences-system-symbolic")
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
| from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
# btn = Gtk.Button()
# icon = Gio.ThemedIcon(name="preferences-system-symbolic")
# image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
# btn.add(image)
# self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
| Hide preferences button for now. | Hide preferences button for now.
| Python | mit | andialbrecht/runsqlrun | from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
btn = Gtk.Button()
icon = Gio.ThemedIcon(name="preferences-system-symbolic")
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
Hide preferences button for now. | from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
# btn = Gtk.Button()
# icon = Gio.ThemedIcon(name="preferences-system-symbolic")
# image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
# btn.add(image)
# self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
| <commit_before>from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
btn = Gtk.Button()
icon = Gio.ThemedIcon(name="preferences-system-symbolic")
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
<commit_msg>Hide preferences button for now.<commit_after> | from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
# btn = Gtk.Button()
# icon = Gio.ThemedIcon(name="preferences-system-symbolic")
# image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
# btn.add(image)
# self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
| from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
btn = Gtk.Button()
icon = Gio.ThemedIcon(name="preferences-system-symbolic")
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
Hide preferences button for now.from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
# btn = Gtk.Button()
# icon = Gio.ThemedIcon(name="preferences-system-symbolic")
# image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
# btn.add(image)
# self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
| <commit_before>from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
btn = Gtk.Button()
icon = Gio.ThemedIcon(name="preferences-system-symbolic")
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
<commit_msg>Hide preferences button for now.<commit_after>from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
# btn = Gtk.Button()
# icon = Gio.ThemedIcon(name="preferences-system-symbolic")
# image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
# btn.add(image)
# self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
|
c1d22d24e6c1d7aa1a70e07e39ee0196da86b26f | scripts/stock_price/white_noise.py | scripts/stock_price/white_noise.py | #!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import numpy as np
from PIL import Image
width = 128
height = 96
n_frames = 10
frame_duration = 100
center_value = 64
def create_image():
image = np.zeros(shape=(height, width, 3), dtype=int)
for y in range(0, height):
for x in range(0, width):
value = int(np.random.normal() * center_value) + center_value
image[y, x] = value
return Image.fromarray(np.uint8(np.clip(image, 0, 255)))
images = list(map(lambda _: create_image(), range(0, n_frames)))
images[0].save('out/white_noise.gif',
save_all=True, append_images=images[1:], optimize=False,
duration=frame_duration, loop=0)
| #!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import itertools
import random
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
width = 256
height = 192
max_value = 255 # brightness
value_center = 64 # mean
value_range = 16 # stddev
n_frames = 10
frame_duration = 100
def create_image():
image = np.zeros(shape=(height, width, 3), dtype=int)
for y in range(0, height):
for x in range(0, width):
image[y, x] = int(np.random.normal() * value_range + value_center)
pixels = np.uint8(np.clip(image, 0, max_value))
return Image.fromarray(pixels), pixels
images, pixels = map(list, zip(*map(lambda _: create_image(), range(0, n_frames))))
images[0].save('out/white_noise.gif',
save_all=True, append_images=images[1:], optimize=False,
duration=frame_duration, loop=0)
plt.hist(x=np.array(pixels).reshape(-1), bins=range(0, max_value + 1))
plt.xlabel('value (brightness)')
plt.ylabel('# of pixels')
xticks = list(itertools.takewhile(lambda x: x <= (max_value + 1), itertools.count(0, value_center)))
plt.xticks(xticks)
plt.yticks([])
plt.savefig('out/white_noise_hist.png', dpi=160)
| Fix distributions of the white noise sampler | Fix distributions of the white noise sampler
| Python | mit | zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend,zettsu-t/cPlusPlusFriend | #!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import numpy as np
from PIL import Image
width = 128
height = 96
n_frames = 10
frame_duration = 100
center_value = 64
def create_image():
image = np.zeros(shape=(height, width, 3), dtype=int)
for y in range(0, height):
for x in range(0, width):
value = int(np.random.normal() * center_value) + center_value
image[y, x] = value
return Image.fromarray(np.uint8(np.clip(image, 0, 255)))
images = list(map(lambda _: create_image(), range(0, n_frames)))
images[0].save('out/white_noise.gif',
save_all=True, append_images=images[1:], optimize=False,
duration=frame_duration, loop=0)
Fix distributions of the white noise sampler | #!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import itertools
import random
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
width = 256
height = 192
max_value = 255 # brightness
value_center = 64 # mean
value_range = 16 # stddev
n_frames = 10
frame_duration = 100
def create_image():
image = np.zeros(shape=(height, width, 3), dtype=int)
for y in range(0, height):
for x in range(0, width):
image[y, x] = int(np.random.normal() * value_range + value_center)
pixels = np.uint8(np.clip(image, 0, max_value))
return Image.fromarray(pixels), pixels
images, pixels = map(list, zip(*map(lambda _: create_image(), range(0, n_frames))))
images[0].save('out/white_noise.gif',
save_all=True, append_images=images[1:], optimize=False,
duration=frame_duration, loop=0)
plt.hist(x=np.array(pixels).reshape(-1), bins=range(0, max_value + 1))
plt.xlabel('value (brightness)')
plt.ylabel('# of pixels')
xticks = list(itertools.takewhile(lambda x: x <= (max_value + 1), itertools.count(0, value_center)))
plt.xticks(xticks)
plt.yticks([])
plt.savefig('out/white_noise_hist.png', dpi=160)
| <commit_before>#!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import numpy as np
from PIL import Image
width = 128
height = 96
n_frames = 10
frame_duration = 100
center_value = 64
def create_image():
image = np.zeros(shape=(height, width, 3), dtype=int)
for y in range(0, height):
for x in range(0, width):
value = int(np.random.normal() * center_value) + center_value
image[y, x] = value
return Image.fromarray(np.uint8(np.clip(image, 0, 255)))
images = list(map(lambda _: create_image(), range(0, n_frames)))
images[0].save('out/white_noise.gif',
save_all=True, append_images=images[1:], optimize=False,
duration=frame_duration, loop=0)
<commit_msg>Fix distributions of the white noise sampler<commit_after> | #!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import itertools
import random
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
width = 256
height = 192
max_value = 255 # brightness
value_center = 64 # mean
value_range = 16 # stddev
n_frames = 10
frame_duration = 100
def create_image():
image = np.zeros(shape=(height, width, 3), dtype=int)
for y in range(0, height):
for x in range(0, width):
image[y, x] = int(np.random.normal() * value_range + value_center)
pixels = np.uint8(np.clip(image, 0, max_value))
return Image.fromarray(pixels), pixels
images, pixels = map(list, zip(*map(lambda _: create_image(), range(0, n_frames))))
images[0].save('out/white_noise.gif',
save_all=True, append_images=images[1:], optimize=False,
duration=frame_duration, loop=0)
plt.hist(x=np.array(pixels).reshape(-1), bins=range(0, max_value + 1))
plt.xlabel('value (brightness)')
plt.ylabel('# of pixels')
xticks = list(itertools.takewhile(lambda x: x <= (max_value + 1), itertools.count(0, value_center)))
plt.xticks(xticks)
plt.yticks([])
plt.savefig('out/white_noise_hist.png', dpi=160)
| #!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import numpy as np
from PIL import Image
width = 128
height = 96
n_frames = 10
frame_duration = 100
center_value = 64
def create_image():
image = np.zeros(shape=(height, width, 3), dtype=int)
for y in range(0, height):
for x in range(0, width):
value = int(np.random.normal() * center_value) + center_value
image[y, x] = value
return Image.fromarray(np.uint8(np.clip(image, 0, 255)))
images = list(map(lambda _: create_image(), range(0, n_frames)))
images[0].save('out/white_noise.gif',
save_all=True, append_images=images[1:], optimize=False,
duration=frame_duration, loop=0)
Fix distributions of the white noise sampler#!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import itertools
import random
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
width = 256
height = 192
max_value = 255 # brightness
value_center = 64 # mean
value_range = 16 # stddev
n_frames = 10
frame_duration = 100
def create_image():
image = np.zeros(shape=(height, width, 3), dtype=int)
for y in range(0, height):
for x in range(0, width):
image[y, x] = int(np.random.normal() * value_range + value_center)
pixels = np.uint8(np.clip(image, 0, max_value))
return Image.fromarray(pixels), pixels
images, pixels = map(list, zip(*map(lambda _: create_image(), range(0, n_frames))))
images[0].save('out/white_noise.gif',
save_all=True, append_images=images[1:], optimize=False,
duration=frame_duration, loop=0)
plt.hist(x=np.array(pixels).reshape(-1), bins=range(0, max_value + 1))
plt.xlabel('value (brightness)')
plt.ylabel('# of pixels')
xticks = list(itertools.takewhile(lambda x: x <= (max_value + 1), itertools.count(0, value_center)))
plt.xticks(xticks)
plt.yticks([])
plt.savefig('out/white_noise_hist.png', dpi=160)
| <commit_before>#!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import numpy as np
from PIL import Image
width = 128
height = 96
n_frames = 10
frame_duration = 100
center_value = 64
def create_image():
image = np.zeros(shape=(height, width, 3), dtype=int)
for y in range(0, height):
for x in range(0, width):
value = int(np.random.normal() * center_value) + center_value
image[y, x] = value
return Image.fromarray(np.uint8(np.clip(image, 0, 255)))
images = list(map(lambda _: create_image(), range(0, n_frames)))
images[0].save('out/white_noise.gif',
save_all=True, append_images=images[1:], optimize=False,
duration=frame_duration, loop=0)
<commit_msg>Fix distributions of the white noise sampler<commit_after>#!/usr/bin/python3
# coding: utf-8
'''
Create a white noise animation like a TV screen
'''
import itertools
import random
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
width = 256
height = 192
max_value = 255 # brightness
value_center = 64 # mean
value_range = 16 # stddev
n_frames = 10
frame_duration = 100
def create_image():
image = np.zeros(shape=(height, width, 3), dtype=int)
for y in range(0, height):
for x in range(0, width):
image[y, x] = int(np.random.normal() * value_range + value_center)
pixels = np.uint8(np.clip(image, 0, max_value))
return Image.fromarray(pixels), pixels
images, pixels = map(list, zip(*map(lambda _: create_image(), range(0, n_frames))))
images[0].save('out/white_noise.gif',
save_all=True, append_images=images[1:], optimize=False,
duration=frame_duration, loop=0)
plt.hist(x=np.array(pixels).reshape(-1), bins=range(0, max_value + 1))
plt.xlabel('value (brightness)')
plt.ylabel('# of pixels')
xticks = list(itertools.takewhile(lambda x: x <= (max_value + 1), itertools.count(0, value_center)))
plt.xticks(xticks)
plt.yticks([])
plt.savefig('out/white_noise_hist.png', dpi=160)
|
d133a74913df1b86318b724f900b1f1c33cb7860 | scripts/slave/recipes/crashpad/continuous.py | scripts/slave/recipes/crashpad/continuous.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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if api.properties.get('clobber'):
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
| # 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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if 'clobber' in api.properties:
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
| Fix clobber on crashpad recipe | Fix clobber on crashpad recipe
Apparently (from looking at
https://build.chromium.org/p/client.crashpad/builders/crashpad_mac_dbg/builds/25/steps/steps/logs/stdio
)
buildbot only adds 'clobber' to the dict, but has a value of '', so just check for existence instead.
So much for having tests. :p
R=dpranke@chromium.org
Review URL: https://codereview.chromium.org/803653002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@293385 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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if api.properties.get('clobber'):
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
Fix clobber on crashpad recipe
Apparently (from looking at
https://build.chromium.org/p/client.crashpad/builders/crashpad_mac_dbg/builds/25/steps/steps/logs/stdio
)
buildbot only adds 'clobber' to the dict, but has a value of '', so just check for existence instead.
So much for having tests. :p
R=dpranke@chromium.org
Review URL: https://codereview.chromium.org/803653002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@293385 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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if 'clobber' in api.properties:
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
| <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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if api.properties.get('clobber'):
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
<commit_msg>Fix clobber on crashpad recipe
Apparently (from looking at
https://build.chromium.org/p/client.crashpad/builders/crashpad_mac_dbg/builds/25/steps/steps/logs/stdio
)
buildbot only adds 'clobber' to the dict, but has a value of '', so just check for existence instead.
So much for having tests. :p
R=dpranke@chromium.org
Review URL: https://codereview.chromium.org/803653002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@293385 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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if 'clobber' in api.properties:
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
| # 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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if api.properties.get('clobber'):
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
Fix clobber on crashpad recipe
Apparently (from looking at
https://build.chromium.org/p/client.crashpad/builders/crashpad_mac_dbg/builds/25/steps/steps/logs/stdio
)
buildbot only adds 'clobber' to the dict, but has a value of '', so just check for existence instead.
So much for having tests. :p
R=dpranke@chromium.org
Review URL: https://codereview.chromium.org/803653002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@293385 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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if 'clobber' in api.properties:
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
| <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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if api.properties.get('clobber'):
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
<commit_msg>Fix clobber on crashpad recipe
Apparently (from looking at
https://build.chromium.org/p/client.crashpad/builders/crashpad_mac_dbg/builds/25/steps/steps/logs/stdio
)
buildbot only adds 'clobber' to the dict, but has a value of '', so just check for existence instead.
So much for having tests. :p
R=dpranke@chromium.org
Review URL: https://codereview.chromium.org/803653002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@293385 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.
"""Buildbot recipe definition for the various Crashpad continuous builders.
"""
DEPS = [
'gclient',
'path',
'platform',
'properties',
'python',
'step',
]
def GenSteps(api):
"""Generates the sequence of steps that will be run by the slave."""
api.gclient.set_config('crashpad')
api.gclient.checkout()
if 'clobber' in api.properties:
api.path.rmtree('out', api.path['slave_build'].join('out'))
api.gclient.runhooks()
buildername = api.properties['buildername']
dirname = 'Debug' if '_dbg' in buildername else 'Release'
path = api.path['checkout'].join('out', dirname)
api.step('compile with ninja', ['ninja', '-C', path])
api.python('run tests',
api.path['checkout'].join('build', 'run_tests.py'),
args=[dirname])
def GenTests(api):
tests = [
'crashpad_mac_dbg',
'crashpad_mac_rel',
'crashpad_win_dbg',
'crashpad_win_rel',
]
for t in tests:
yield(api.test(t) + api.properties.generic(buildername=t))
yield(api.test(t + '_clobber') +
api.properties.generic(buildername=t, clobber=True))
|
1b47c9eb39a2c5bbdf05397c949619d5a044f2ae | fabfile.py | fabfile.py | from fabric.api import env, run, local, sudo, settings
from fabric.contrib.console import confirm
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
| import os
from fabric.api import env, run, local, sudo, settings
env.password = os.getenv('SUDO_PASSWORD', None)
assert env.password
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
| Set password in env var | Set password in env var
| Python | mit | exitcodezero/picloud,exitcodezero/pi-cloud-sockets | from fabric.api import env, run, local, sudo, settings
from fabric.contrib.console import confirm
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
Set password in env var | import os
from fabric.api import env, run, local, sudo, settings
env.password = os.getenv('SUDO_PASSWORD', None)
assert env.password
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
| <commit_before>from fabric.api import env, run, local, sudo, settings
from fabric.contrib.console import confirm
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
<commit_msg>Set password in env var<commit_after> | import os
from fabric.api import env, run, local, sudo, settings
env.password = os.getenv('SUDO_PASSWORD', None)
assert env.password
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
| from fabric.api import env, run, local, sudo, settings
from fabric.contrib.console import confirm
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
Set password in env varimport os
from fabric.api import env, run, local, sudo, settings
env.password = os.getenv('SUDO_PASSWORD', None)
assert env.password
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
| <commit_before>from fabric.api import env, run, local, sudo, settings
from fabric.contrib.console import confirm
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
<commit_msg>Set password in env var<commit_after>import os
from fabric.api import env, run, local, sudo, settings
env.password = os.getenv('SUDO_PASSWORD', None)
assert env.password
def build_local():
local('docker-compose run app go build -v')
local('mv app/app ./application')
def copy_app():
local('scp application {0}@{1}:/home/{0}'.format(env.user, env.hosts[0]))
def stop_service():
with settings(warn_only=True):
sudo('service pi-cloud stop')
def remove_old_app():
run('rm pi-cloud')
def rename_new_app():
run('mv application pi-cloud')
def start_service():
sudo('service pi-cloud start')
def deploy():
copy_app()
stop_service()
remove_old_app()
rename_new_app()
start_service()
def build_deploy():
build_local()
deploy()
|
43662a6417a9d589bac2ab49e5b9b5441adf1115 | atomic/__init__.py | atomic/__init__.py | from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
| import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__)))
from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
| Set path to find _xxdata.so files | Set path to find _xxdata.so files
| Python | mit | cfe316/atomic | from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
Set path to find _xxdata.so files | import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__)))
from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
| <commit_before>from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
<commit_msg>Set path to find _xxdata.so files<commit_after> | import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__)))
from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
| from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
Set path to find _xxdata.so filesimport os, sys
sys.path.append(os.path.join(os.path.dirname(__file__)))
from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
| <commit_before>from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
<commit_msg>Set path to find _xxdata.so files<commit_after>import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__)))
from .atomic_data import AtomicData
from .collisional_radiative import CollRadEquilibrium
from .time_dependent_rates import RateEquations, RateEquationsWithDiffusion
from .radiation import Radiation
from .electron_cooling import ElectronCooling
element = AtomicData.from_element
|
ad8600f94268adaa00b71a92adc601a87d2cef14 | test_echo.py | test_echo.py | from echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client(u'This is an é unicode test') == u'This is an é unicode test'
| from echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client('This string is larger than my current buffer size. It should return all of the characters. This is the last sentence of this test.') == 'This string is larger than my current buffer size. It should return all of the characters. This is the last sentence of this test.'
def test_3():
assert client('') == ''
| Add long and empty strings for testing | Add long and empty strings for testing
| Python | mit | jwarren116/network-tools,jwarren116/network-tools | from echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client(u'This is an é unicode test') == u'This is an é unicode test'
Add long and empty strings for testing | from echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client('This string is larger than my current buffer size. It should return all of the characters. This is the last sentence of this test.') == 'This string is larger than my current buffer size. It should return all of the characters. This is the last sentence of this test.'
def test_3():
assert client('') == ''
| <commit_before>from echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client(u'This is an é unicode test') == u'This is an é unicode test'
<commit_msg>Add long and empty strings for testing<commit_after> | from echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client('This string is larger than my current buffer size. It should return all of the characters. This is the last sentence of this test.') == 'This string is larger than my current buffer size. It should return all of the characters. This is the last sentence of this test.'
def test_3():
assert client('') == ''
| from echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client(u'This is an é unicode test') == u'This is an é unicode test'
Add long and empty strings for testingfrom echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client('This string is larger than my current buffer size. It should return all of the characters. This is the last sentence of this test.') == 'This string is larger than my current buffer size. It should return all of the characters. This is the last sentence of this test.'
def test_3():
assert client('') == ''
| <commit_before>from echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client(u'This is an é unicode test') == u'This is an é unicode test'
<commit_msg>Add long and empty strings for testing<commit_after>from echo_client import client
def test_1():
assert client('This is a unicode test') == 'This is a unicode test'
def test_2():
assert client('This string is larger than my current buffer size. It should return all of the characters. This is the last sentence of this test.') == 'This string is larger than my current buffer size. It should return all of the characters. This is the last sentence of this test.'
def test_3():
assert client('') == ''
|
eba712b9efced9cb8d2d6cd0683fb550e5f5b1ca | mininews/sitemaps.py | mininews/sitemaps.py | from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
# Let's assume that an article - once published - will not change.
changefreq = "never"
# Define the model class here to make it easier to customise this class.
model = None
def items(self):
return self.model.objects.live()
def lastmod(self, obj):
return obj.modified
| from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
def items(self):
return self.model.objects.live()
def lastmod(self, obj):
return obj.modified
| Remove defaults from the sitemap.py that should not be set in Mininews. | Remove defaults from the sitemap.py that should not be set in Mininews.
| Python | mit | richardbarran/django-minipub,richardbarran/django-minipub,richardbarran/django-mininews,richardbarran/django-mininews,richardbarran/django-mininews | from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
# Let's assume that an article - once published - will not change.
changefreq = "never"
# Define the model class here to make it easier to customise this class.
model = None
def items(self):
return self.model.objects.live()
def lastmod(self, obj):
return obj.modified
Remove defaults from the sitemap.py that should not be set in Mininews. | from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
def items(self):
return self.model.objects.live()
def lastmod(self, obj):
return obj.modified
| <commit_before>from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
# Let's assume that an article - once published - will not change.
changefreq = "never"
# Define the model class here to make it easier to customise this class.
model = None
def items(self):
return self.model.objects.live()
def lastmod(self, obj):
return obj.modified
<commit_msg>Remove defaults from the sitemap.py that should not be set in Mininews.<commit_after> | from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
def items(self):
return self.model.objects.live()
def lastmod(self, obj):
return obj.modified
| from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
# Let's assume that an article - once published - will not change.
changefreq = "never"
# Define the model class here to make it easier to customise this class.
model = None
def items(self):
return self.model.objects.live()
def lastmod(self, obj):
return obj.modified
Remove defaults from the sitemap.py that should not be set in Mininews.from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
def items(self):
return self.model.objects.live()
def lastmod(self, obj):
return obj.modified
| <commit_before>from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
# Let's assume that an article - once published - will not change.
changefreq = "never"
# Define the model class here to make it easier to customise this class.
model = None
def items(self):
return self.model.objects.live()
def lastmod(self, obj):
return obj.modified
<commit_msg>Remove defaults from the sitemap.py that should not be set in Mininews.<commit_after>from django.contrib.sitemaps import Sitemap
class MininewsSitemap(Sitemap):
def items(self):
return self.model.objects.live()
def lastmod(self, obj):
return obj.modified
|
4ae0f5ea2c48aaa141f25edc0d35e07da0d5e5f4 | project/api/managers.py | project/api/managers.py | # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', **kwargs):
user = self.model(
email=email,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **kwargs):
user = self.model(
email=email,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
| # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, person, password='', **kwargs):
user = self.model(
email=email,
person=person,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, person, password, **kwargs):
user = self.model(
email=email,
person=person,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
| Update `create_user` method manager to require person | Update `create_user` method manager to require person
| Python | bsd-2-clause | barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore-django,barberscore/barberscore-api | # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', **kwargs):
user = self.model(
email=email,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **kwargs):
user = self.model(
email=email,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
Update `create_user` method manager to require person | # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, person, password='', **kwargs):
user = self.model(
email=email,
person=person,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, person, password, **kwargs):
user = self.model(
email=email,
person=person,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
| <commit_before># Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', **kwargs):
user = self.model(
email=email,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **kwargs):
user = self.model(
email=email,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
<commit_msg>Update `create_user` method manager to require person<commit_after> | # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, person, password='', **kwargs):
user = self.model(
email=email,
person=person,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, person, password, **kwargs):
user = self.model(
email=email,
person=person,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
| # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', **kwargs):
user = self.model(
email=email,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **kwargs):
user = self.model(
email=email,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
Update `create_user` method manager to require person# Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, person, password='', **kwargs):
user = self.model(
email=email,
person=person,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, person, password, **kwargs):
user = self.model(
email=email,
person=person,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
| <commit_before># Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', **kwargs):
user = self.model(
email=email,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **kwargs):
user = self.model(
email=email,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
<commit_msg>Update `create_user` method manager to require person<commit_after># Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, person, password='', **kwargs):
user = self.model(
email=email,
person=person,
password='',
is_active=True,
**kwargs
)
user.save(using=self._db)
return user
def create_superuser(self, email, person, password, **kwargs):
user = self.model(
email=email,
person=person,
is_staff=True,
is_active=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
|
c2b294483035c0b846be2dcacb7b9db4b36c2014 | tests/settings/base.py | tests/settings/base.py | import os
local_path = lambda path: os.path.join(os.path.dirname(__file__), path)
APP_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
DEBUG = True
SECRET_KEY = 'not-so-secret-for-tests'
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.humanize',
'name',
'tests']
ROOT_URLCONF = 'tests.urls'
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'name.context_processors.name')
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
# Minimal template settings for testing Django 1.8.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'name.context_processors.name'
],
},
},
]
STATIC_URL = '/static/'
| import os
local_path = lambda path: os.path.join(os.path.dirname(__file__), path)
APP_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
DEBUG = True
SECRET_KEY = 'not-so-secret-for-tests'
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.humanize',
'name',
'tests']
ROOT_URLCONF = 'tests.urls'
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'name.context_processors.name')
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
# Minimal template settings for testing Django 1.8.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'name.context_processors.name'
],
},
},
]
STATIC_URL = '/static/'
TIME_ZONE = 'UTC'
USE_TZ = True
| Add timezone settings to the test project. | Add timezone settings to the test project.
| Python | bsd-3-clause | unt-libraries/django-name,damonkelley/django-name,unt-libraries/django-name,unt-libraries/django-name,damonkelley/django-name,damonkelley/django-name | import os
local_path = lambda path: os.path.join(os.path.dirname(__file__), path)
APP_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
DEBUG = True
SECRET_KEY = 'not-so-secret-for-tests'
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.humanize',
'name',
'tests']
ROOT_URLCONF = 'tests.urls'
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'name.context_processors.name')
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
# Minimal template settings for testing Django 1.8.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'name.context_processors.name'
],
},
},
]
STATIC_URL = '/static/'
Add timezone settings to the test project. | import os
local_path = lambda path: os.path.join(os.path.dirname(__file__), path)
APP_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
DEBUG = True
SECRET_KEY = 'not-so-secret-for-tests'
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.humanize',
'name',
'tests']
ROOT_URLCONF = 'tests.urls'
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'name.context_processors.name')
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
# Minimal template settings for testing Django 1.8.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'name.context_processors.name'
],
},
},
]
STATIC_URL = '/static/'
TIME_ZONE = 'UTC'
USE_TZ = True
| <commit_before>import os
local_path = lambda path: os.path.join(os.path.dirname(__file__), path)
APP_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
DEBUG = True
SECRET_KEY = 'not-so-secret-for-tests'
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.humanize',
'name',
'tests']
ROOT_URLCONF = 'tests.urls'
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'name.context_processors.name')
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
# Minimal template settings for testing Django 1.8.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'name.context_processors.name'
],
},
},
]
STATIC_URL = '/static/'
<commit_msg>Add timezone settings to the test project.<commit_after> | import os
local_path = lambda path: os.path.join(os.path.dirname(__file__), path)
APP_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
DEBUG = True
SECRET_KEY = 'not-so-secret-for-tests'
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.humanize',
'name',
'tests']
ROOT_URLCONF = 'tests.urls'
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'name.context_processors.name')
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
# Minimal template settings for testing Django 1.8.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'name.context_processors.name'
],
},
},
]
STATIC_URL = '/static/'
TIME_ZONE = 'UTC'
USE_TZ = True
| import os
local_path = lambda path: os.path.join(os.path.dirname(__file__), path)
APP_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
DEBUG = True
SECRET_KEY = 'not-so-secret-for-tests'
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.humanize',
'name',
'tests']
ROOT_URLCONF = 'tests.urls'
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'name.context_processors.name')
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
# Minimal template settings for testing Django 1.8.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'name.context_processors.name'
],
},
},
]
STATIC_URL = '/static/'
Add timezone settings to the test project.import os
local_path = lambda path: os.path.join(os.path.dirname(__file__), path)
APP_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
DEBUG = True
SECRET_KEY = 'not-so-secret-for-tests'
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.humanize',
'name',
'tests']
ROOT_URLCONF = 'tests.urls'
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'name.context_processors.name')
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
# Minimal template settings for testing Django 1.8.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'name.context_processors.name'
],
},
},
]
STATIC_URL = '/static/'
TIME_ZONE = 'UTC'
USE_TZ = True
| <commit_before>import os
local_path = lambda path: os.path.join(os.path.dirname(__file__), path)
APP_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
DEBUG = True
SECRET_KEY = 'not-so-secret-for-tests'
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.humanize',
'name',
'tests']
ROOT_URLCONF = 'tests.urls'
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'name.context_processors.name')
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
# Minimal template settings for testing Django 1.8.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'name.context_processors.name'
],
},
},
]
STATIC_URL = '/static/'
<commit_msg>Add timezone settings to the test project.<commit_after>import os
local_path = lambda path: os.path.join(os.path.dirname(__file__), path)
APP_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
DEBUG = True
SECRET_KEY = 'not-so-secret-for-tests'
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.humanize',
'name',
'tests']
ROOT_URLCONF = 'tests.urls'
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
'name.context_processors.name')
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
# Minimal template settings for testing Django 1.8.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'name.context_processors.name'
],
},
},
]
STATIC_URL = '/static/'
TIME_ZONE = 'UTC'
USE_TZ = True
|
1cda977eff5a2edaa0de82882ef2e7d1611329b7 | tests/test_protocol.py | tests/test_protocol.py | """
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import pytest
class TestProtocol:
@pytest.mark.asyncio
def test_server_hello(self, ws_client_factory, get_unencrypted_packet):
"""
The server must send a valid `server-hello` on connection.
"""
client = yield from ws_client_factory()
receiver, message = yield from get_unencrypted_packet(client)
assert receiver == 0x00
assert message['type'] == 'server-hello'
assert len(message['key']) == 32
assert len(message['my-cookie']) == 16
yield from client.close()
| """
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import asyncio
import pytest
import saltyrtc
class TestProtocol:
@pytest.mark.asyncio
def test_no_subprotocols(self, ws_client_factory):
"""
The server must drop the client after the connection has been
established with a close code of *1002*.
"""
client = yield from ws_client_factory(subprotocols=None)
yield from asyncio.sleep(0.05)
assert not client.open
assert client.close_code == saltyrtc.CloseCode.sub_protocol_error
@pytest.mark.asyncio
def test_invalid_subprotocols(self, ws_client_factory):
"""
The server must drop the client after the connection has been
established with a close code of *1002*.
"""
client = yield from ws_client_factory(subprotocols=['kittie-protocol-3000'])
yield from asyncio.sleep(0.05)
assert not client.open
assert client.close_code == saltyrtc.CloseCode.sub_protocol_error
@pytest.mark.asyncio
def test_server_hello(self, ws_client_factory, get_unencrypted_packet):
"""
The server must send a valid `server-hello` on connection.
"""
client = yield from ws_client_factory()
receiver, message = yield from get_unencrypted_packet(client)
assert receiver == 0x00
assert message['type'] == 'server-hello'
assert len(message['key']) == 32
assert len(message['my-cookie']) == 16
yield from client.close()
| Add tests for invalid and no provided sub-protocols | Add tests for invalid and no provided sub-protocols
| Python | mit | saltyrtc/saltyrtc-server-python,saltyrtc/saltyrtc-server-python | """
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import pytest
class TestProtocol:
@pytest.mark.asyncio
def test_server_hello(self, ws_client_factory, get_unencrypted_packet):
"""
The server must send a valid `server-hello` on connection.
"""
client = yield from ws_client_factory()
receiver, message = yield from get_unencrypted_packet(client)
assert receiver == 0x00
assert message['type'] == 'server-hello'
assert len(message['key']) == 32
assert len(message['my-cookie']) == 16
yield from client.close()
Add tests for invalid and no provided sub-protocols | """
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import asyncio
import pytest
import saltyrtc
class TestProtocol:
@pytest.mark.asyncio
def test_no_subprotocols(self, ws_client_factory):
"""
The server must drop the client after the connection has been
established with a close code of *1002*.
"""
client = yield from ws_client_factory(subprotocols=None)
yield from asyncio.sleep(0.05)
assert not client.open
assert client.close_code == saltyrtc.CloseCode.sub_protocol_error
@pytest.mark.asyncio
def test_invalid_subprotocols(self, ws_client_factory):
"""
The server must drop the client after the connection has been
established with a close code of *1002*.
"""
client = yield from ws_client_factory(subprotocols=['kittie-protocol-3000'])
yield from asyncio.sleep(0.05)
assert not client.open
assert client.close_code == saltyrtc.CloseCode.sub_protocol_error
@pytest.mark.asyncio
def test_server_hello(self, ws_client_factory, get_unencrypted_packet):
"""
The server must send a valid `server-hello` on connection.
"""
client = yield from ws_client_factory()
receiver, message = yield from get_unencrypted_packet(client)
assert receiver == 0x00
assert message['type'] == 'server-hello'
assert len(message['key']) == 32
assert len(message['my-cookie']) == 16
yield from client.close()
| <commit_before>"""
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import pytest
class TestProtocol:
@pytest.mark.asyncio
def test_server_hello(self, ws_client_factory, get_unencrypted_packet):
"""
The server must send a valid `server-hello` on connection.
"""
client = yield from ws_client_factory()
receiver, message = yield from get_unencrypted_packet(client)
assert receiver == 0x00
assert message['type'] == 'server-hello'
assert len(message['key']) == 32
assert len(message['my-cookie']) == 16
yield from client.close()
<commit_msg>Add tests for invalid and no provided sub-protocols<commit_after> | """
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import asyncio
import pytest
import saltyrtc
class TestProtocol:
@pytest.mark.asyncio
def test_no_subprotocols(self, ws_client_factory):
"""
The server must drop the client after the connection has been
established with a close code of *1002*.
"""
client = yield from ws_client_factory(subprotocols=None)
yield from asyncio.sleep(0.05)
assert not client.open
assert client.close_code == saltyrtc.CloseCode.sub_protocol_error
@pytest.mark.asyncio
def test_invalid_subprotocols(self, ws_client_factory):
"""
The server must drop the client after the connection has been
established with a close code of *1002*.
"""
client = yield from ws_client_factory(subprotocols=['kittie-protocol-3000'])
yield from asyncio.sleep(0.05)
assert not client.open
assert client.close_code == saltyrtc.CloseCode.sub_protocol_error
@pytest.mark.asyncio
def test_server_hello(self, ws_client_factory, get_unencrypted_packet):
"""
The server must send a valid `server-hello` on connection.
"""
client = yield from ws_client_factory()
receiver, message = yield from get_unencrypted_packet(client)
assert receiver == 0x00
assert message['type'] == 'server-hello'
assert len(message['key']) == 32
assert len(message['my-cookie']) == 16
yield from client.close()
| """
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import pytest
class TestProtocol:
@pytest.mark.asyncio
def test_server_hello(self, ws_client_factory, get_unencrypted_packet):
"""
The server must send a valid `server-hello` on connection.
"""
client = yield from ws_client_factory()
receiver, message = yield from get_unencrypted_packet(client)
assert receiver == 0x00
assert message['type'] == 'server-hello'
assert len(message['key']) == 32
assert len(message['my-cookie']) == 16
yield from client.close()
Add tests for invalid and no provided sub-protocols"""
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import asyncio
import pytest
import saltyrtc
class TestProtocol:
@pytest.mark.asyncio
def test_no_subprotocols(self, ws_client_factory):
"""
The server must drop the client after the connection has been
established with a close code of *1002*.
"""
client = yield from ws_client_factory(subprotocols=None)
yield from asyncio.sleep(0.05)
assert not client.open
assert client.close_code == saltyrtc.CloseCode.sub_protocol_error
@pytest.mark.asyncio
def test_invalid_subprotocols(self, ws_client_factory):
"""
The server must drop the client after the connection has been
established with a close code of *1002*.
"""
client = yield from ws_client_factory(subprotocols=['kittie-protocol-3000'])
yield from asyncio.sleep(0.05)
assert not client.open
assert client.close_code == saltyrtc.CloseCode.sub_protocol_error
@pytest.mark.asyncio
def test_server_hello(self, ws_client_factory, get_unencrypted_packet):
"""
The server must send a valid `server-hello` on connection.
"""
client = yield from ws_client_factory()
receiver, message = yield from get_unencrypted_packet(client)
assert receiver == 0x00
assert message['type'] == 'server-hello'
assert len(message['key']) == 32
assert len(message['my-cookie']) == 16
yield from client.close()
| <commit_before>"""
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import pytest
class TestProtocol:
@pytest.mark.asyncio
def test_server_hello(self, ws_client_factory, get_unencrypted_packet):
"""
The server must send a valid `server-hello` on connection.
"""
client = yield from ws_client_factory()
receiver, message = yield from get_unencrypted_packet(client)
assert receiver == 0x00
assert message['type'] == 'server-hello'
assert len(message['key']) == 32
assert len(message['my-cookie']) == 16
yield from client.close()
<commit_msg>Add tests for invalid and no provided sub-protocols<commit_after>"""
The tests provided in this module make sure that the server is
compliant to the SaltyRTC protocol.
"""
import asyncio
import pytest
import saltyrtc
class TestProtocol:
@pytest.mark.asyncio
def test_no_subprotocols(self, ws_client_factory):
"""
The server must drop the client after the connection has been
established with a close code of *1002*.
"""
client = yield from ws_client_factory(subprotocols=None)
yield from asyncio.sleep(0.05)
assert not client.open
assert client.close_code == saltyrtc.CloseCode.sub_protocol_error
@pytest.mark.asyncio
def test_invalid_subprotocols(self, ws_client_factory):
"""
The server must drop the client after the connection has been
established with a close code of *1002*.
"""
client = yield from ws_client_factory(subprotocols=['kittie-protocol-3000'])
yield from asyncio.sleep(0.05)
assert not client.open
assert client.close_code == saltyrtc.CloseCode.sub_protocol_error
@pytest.mark.asyncio
def test_server_hello(self, ws_client_factory, get_unencrypted_packet):
"""
The server must send a valid `server-hello` on connection.
"""
client = yield from ws_client_factory()
receiver, message = yield from get_unencrypted_packet(client)
assert receiver == 0x00
assert message['type'] == 'server-hello'
assert len(message['key']) == 32
assert len(message['my-cookie']) == 16
yield from client.close()
|
a86ecdb187c06da216be0dd5020748bf84f8638b | tests/test_settings.py | tests/test_settings.py | from os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.slack.SlackChannel": {
# Required
"URL": environ.get("CHANNELS_SLACK_URL"),
# Optional
"USERNAME": environ.get("CHANNELS_SLACK_USERNAME", None),
"ICON_URL": environ.get("CHANNELS_SLACK_ICON_URL", None),
"ICON_EMOJI": environ.get("CHANNELS_SLACK_ICON_EMOJI", None),
"CHANNEL": environ.get("CHANNELS_SLACK_CHANNEL", None)
}
}
}
| from os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.hipchat.HipChatChannel": {
# Required
"API_ID": environ.get("CHANNELS_HIPCHAT_API_ID"),
"TOKEN": environ.get("CHANNELS_HIPCHAT_TOKEN"),
# Optional
"BASE_URL": environ.get("CHANNELS_HIPCHAT_BASE_URL")
},
"channels.backends.slack.SlackChannel": {
# Required
"URL": environ.get("CHANNELS_SLACK_URL"),
# Optional
"USERNAME": environ.get("CHANNELS_SLACK_USERNAME", None),
"ICON_URL": environ.get("CHANNELS_SLACK_ICON_URL", None),
"ICON_EMOJI": environ.get("CHANNELS_SLACK_ICON_EMOJI", None),
"CHANNEL": environ.get("CHANNELS_SLACK_CHANNEL", None)
}
}
}
| Add test settings for HipChatChannel | Add test settings for HipChatChannel
| Python | mit | ymyzk/django-channels,ymyzk/kawasemi | from os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.slack.SlackChannel": {
# Required
"URL": environ.get("CHANNELS_SLACK_URL"),
# Optional
"USERNAME": environ.get("CHANNELS_SLACK_USERNAME", None),
"ICON_URL": environ.get("CHANNELS_SLACK_ICON_URL", None),
"ICON_EMOJI": environ.get("CHANNELS_SLACK_ICON_EMOJI", None),
"CHANNEL": environ.get("CHANNELS_SLACK_CHANNEL", None)
}
}
}
Add test settings for HipChatChannel | from os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.hipchat.HipChatChannel": {
# Required
"API_ID": environ.get("CHANNELS_HIPCHAT_API_ID"),
"TOKEN": environ.get("CHANNELS_HIPCHAT_TOKEN"),
# Optional
"BASE_URL": environ.get("CHANNELS_HIPCHAT_BASE_URL")
},
"channels.backends.slack.SlackChannel": {
# Required
"URL": environ.get("CHANNELS_SLACK_URL"),
# Optional
"USERNAME": environ.get("CHANNELS_SLACK_USERNAME", None),
"ICON_URL": environ.get("CHANNELS_SLACK_ICON_URL", None),
"ICON_EMOJI": environ.get("CHANNELS_SLACK_ICON_EMOJI", None),
"CHANNEL": environ.get("CHANNELS_SLACK_CHANNEL", None)
}
}
}
| <commit_before>from os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.slack.SlackChannel": {
# Required
"URL": environ.get("CHANNELS_SLACK_URL"),
# Optional
"USERNAME": environ.get("CHANNELS_SLACK_USERNAME", None),
"ICON_URL": environ.get("CHANNELS_SLACK_ICON_URL", None),
"ICON_EMOJI": environ.get("CHANNELS_SLACK_ICON_EMOJI", None),
"CHANNEL": environ.get("CHANNELS_SLACK_CHANNEL", None)
}
}
}
<commit_msg>Add test settings for HipChatChannel<commit_after> | from os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.hipchat.HipChatChannel": {
# Required
"API_ID": environ.get("CHANNELS_HIPCHAT_API_ID"),
"TOKEN": environ.get("CHANNELS_HIPCHAT_TOKEN"),
# Optional
"BASE_URL": environ.get("CHANNELS_HIPCHAT_BASE_URL")
},
"channels.backends.slack.SlackChannel": {
# Required
"URL": environ.get("CHANNELS_SLACK_URL"),
# Optional
"USERNAME": environ.get("CHANNELS_SLACK_USERNAME", None),
"ICON_URL": environ.get("CHANNELS_SLACK_ICON_URL", None),
"ICON_EMOJI": environ.get("CHANNELS_SLACK_ICON_EMOJI", None),
"CHANNEL": environ.get("CHANNELS_SLACK_CHANNEL", None)
}
}
}
| from os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.slack.SlackChannel": {
# Required
"URL": environ.get("CHANNELS_SLACK_URL"),
# Optional
"USERNAME": environ.get("CHANNELS_SLACK_USERNAME", None),
"ICON_URL": environ.get("CHANNELS_SLACK_ICON_URL", None),
"ICON_EMOJI": environ.get("CHANNELS_SLACK_ICON_EMOJI", None),
"CHANNEL": environ.get("CHANNELS_SLACK_CHANNEL", None)
}
}
}
Add test settings for HipChatChannelfrom os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.hipchat.HipChatChannel": {
# Required
"API_ID": environ.get("CHANNELS_HIPCHAT_API_ID"),
"TOKEN": environ.get("CHANNELS_HIPCHAT_TOKEN"),
# Optional
"BASE_URL": environ.get("CHANNELS_HIPCHAT_BASE_URL")
},
"channels.backends.slack.SlackChannel": {
# Required
"URL": environ.get("CHANNELS_SLACK_URL"),
# Optional
"USERNAME": environ.get("CHANNELS_SLACK_USERNAME", None),
"ICON_URL": environ.get("CHANNELS_SLACK_ICON_URL", None),
"ICON_EMOJI": environ.get("CHANNELS_SLACK_ICON_EMOJI", None),
"CHANNEL": environ.get("CHANNELS_SLACK_CHANNEL", None)
}
}
}
| <commit_before>from os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.slack.SlackChannel": {
# Required
"URL": environ.get("CHANNELS_SLACK_URL"),
# Optional
"USERNAME": environ.get("CHANNELS_SLACK_USERNAME", None),
"ICON_URL": environ.get("CHANNELS_SLACK_ICON_URL", None),
"ICON_EMOJI": environ.get("CHANNELS_SLACK_ICON_EMOJI", None),
"CHANNEL": environ.get("CHANNELS_SLACK_CHANNEL", None)
}
}
}
<commit_msg>Add test settings for HipChatChannel<commit_after>from os import environ
SECRET_KEY = "fake-secret-key"
INSTALLED_APPS = [
"tests",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
MIDDLEWARE_CLASSES = []
CHANNELS = {
"CHANNELS": {
"channels.backends.hipchat.HipChatChannel": {
# Required
"API_ID": environ.get("CHANNELS_HIPCHAT_API_ID"),
"TOKEN": environ.get("CHANNELS_HIPCHAT_TOKEN"),
# Optional
"BASE_URL": environ.get("CHANNELS_HIPCHAT_BASE_URL")
},
"channels.backends.slack.SlackChannel": {
# Required
"URL": environ.get("CHANNELS_SLACK_URL"),
# Optional
"USERNAME": environ.get("CHANNELS_SLACK_USERNAME", None),
"ICON_URL": environ.get("CHANNELS_SLACK_ICON_URL", None),
"ICON_EMOJI": environ.get("CHANNELS_SLACK_ICON_EMOJI", None),
"CHANNEL": environ.get("CHANNELS_SLACK_CHANNEL", None)
}
}
}
|
0b797d14a609172d4965320aa30eae9e9c1f892e | tests/test_strutils.py | tests/test_strutils.py | # -*- coding: utf-8 -*-
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(to_indent, ' ') == ref
| # -*- coding: utf-8 -*-
import uuid
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(to_indent, ' ') == ref
def test_is_uuid():
assert strutils.is_uuid(uuid.uuid4()) == True
assert strutils.is_uuid(uuid.uuid4(), version=1) == False
assert strutils.is_uuid(str(uuid.uuid4())) == True
assert strutils.is_uuid(str(uuid.uuid4()), version=1) == False
assert strutils.is_uuid(set('garbage')) == False
| Add is_uuid unit-tests, including garbage types. | Add is_uuid unit-tests, including garbage types.
| Python | bsd-3-clause | zeroSteiner/boltons,doublereedkurt/boltons,markrwilliams/boltons | # -*- coding: utf-8 -*-
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(to_indent, ' ') == ref
Add is_uuid unit-tests, including garbage types. | # -*- coding: utf-8 -*-
import uuid
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(to_indent, ' ') == ref
def test_is_uuid():
assert strutils.is_uuid(uuid.uuid4()) == True
assert strutils.is_uuid(uuid.uuid4(), version=1) == False
assert strutils.is_uuid(str(uuid.uuid4())) == True
assert strutils.is_uuid(str(uuid.uuid4()), version=1) == False
assert strutils.is_uuid(set('garbage')) == False
| <commit_before># -*- coding: utf-8 -*-
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(to_indent, ' ') == ref
<commit_msg>Add is_uuid unit-tests, including garbage types.<commit_after> | # -*- coding: utf-8 -*-
import uuid
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(to_indent, ' ') == ref
def test_is_uuid():
assert strutils.is_uuid(uuid.uuid4()) == True
assert strutils.is_uuid(uuid.uuid4(), version=1) == False
assert strutils.is_uuid(str(uuid.uuid4())) == True
assert strutils.is_uuid(str(uuid.uuid4()), version=1) == False
assert strutils.is_uuid(set('garbage')) == False
| # -*- coding: utf-8 -*-
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(to_indent, ' ') == ref
Add is_uuid unit-tests, including garbage types.# -*- coding: utf-8 -*-
import uuid
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(to_indent, ' ') == ref
def test_is_uuid():
assert strutils.is_uuid(uuid.uuid4()) == True
assert strutils.is_uuid(uuid.uuid4(), version=1) == False
assert strutils.is_uuid(str(uuid.uuid4())) == True
assert strutils.is_uuid(str(uuid.uuid4()), version=1) == False
assert strutils.is_uuid(set('garbage')) == False
| <commit_before># -*- coding: utf-8 -*-
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(to_indent, ' ') == ref
<commit_msg>Add is_uuid unit-tests, including garbage types.<commit_after># -*- coding: utf-8 -*-
import uuid
from boltons import strutils
def test_asciify():
ref = u'Beyoncé'
b = strutils.asciify(ref)
assert len(b) == len(b)
assert b[-1:].decode('ascii') == 'e'
def test_indent():
to_indent = '\nabc\ndef\n\nxyz\n'
ref = '\n abc\n def\n\n xyz\n'
assert strutils.indent(to_indent, ' ') == ref
def test_is_uuid():
assert strutils.is_uuid(uuid.uuid4()) == True
assert strutils.is_uuid(uuid.uuid4(), version=1) == False
assert strutils.is_uuid(str(uuid.uuid4())) == True
assert strutils.is_uuid(str(uuid.uuid4()), version=1) == False
assert strutils.is_uuid(set('garbage')) == False
|
1ce23f576888d9e5acf506443374ce0844e70e21 | south/signals.py | south/signals.py | """
South-specific signals
"""
from django.dispatch import Signal
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
| """
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
# Compatibility code for django.contrib.auth
if 'django.contrib.auth' in settings.INSTALLED_APPS:
def create_permissions_compat(app, **kwargs):
from django.db.models import get_app
from django.contrib.auth.management import create_permissions
create_permissions(get_app(app), (), 0)
post_migrate.connect(create_permissions_compat)
| Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models. | Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models.
| Python | apache-2.0 | nimnull/django-south,RaD/django-south,RaD/django-south,philipn/django-south,nimnull/django-south,RaD/django-south,philipn/django-south | """
South-specific signals
"""
from django.dispatch import Signal
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models. | """
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
# Compatibility code for django.contrib.auth
if 'django.contrib.auth' in settings.INSTALLED_APPS:
def create_permissions_compat(app, **kwargs):
from django.db.models import get_app
from django.contrib.auth.management import create_permissions
create_permissions(get_app(app), (), 0)
post_migrate.connect(create_permissions_compat)
| <commit_before>"""
South-specific signals
"""
from django.dispatch import Signal
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
<commit_msg>Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models.<commit_after> | """
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
# Compatibility code for django.contrib.auth
if 'django.contrib.auth' in settings.INSTALLED_APPS:
def create_permissions_compat(app, **kwargs):
from django.db.models import get_app
from django.contrib.auth.management import create_permissions
create_permissions(get_app(app), (), 0)
post_migrate.connect(create_permissions_compat)
| """
South-specific signals
"""
from django.dispatch import Signal
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models."""
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
# Compatibility code for django.contrib.auth
if 'django.contrib.auth' in settings.INSTALLED_APPS:
def create_permissions_compat(app, **kwargs):
from django.db.models import get_app
from django.contrib.auth.management import create_permissions
create_permissions(get_app(app), (), 0)
post_migrate.connect(create_permissions_compat)
| <commit_before>"""
South-specific signals
"""
from django.dispatch import Signal
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
<commit_msg>Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models.<commit_after>"""
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
# Compatibility code for django.contrib.auth
if 'django.contrib.auth' in settings.INSTALLED_APPS:
def create_permissions_compat(app, **kwargs):
from django.db.models import get_app
from django.contrib.auth.management import create_permissions
create_permissions(get_app(app), (), 0)
post_migrate.connect(create_permissions_compat)
|
83d767f75534da4c225eca407ec5eff6ed5774a2 | crmapp/contacts/views.py | crmapp/contacts/views.py | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Contact
@login_required()
def contact_detail(request, uuid):
contact = Contact.objects.get(uuid=uuid)
return render(request,
'contacts/contact_detail.html',
{'contact': contact}
)
| from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponseForbidden
from .models import Contact
from .forms import ContactForm
@login_required()
def contact_detail(request, uuid):
contact = Contact.objects.get(uuid=uuid)
return render(request,
'contacts/contact_detail.html',
{'contact': contact}
)
@login_required()
def contact_cru(request):
if request.POST:
form = ContactForm(request.POST)
if form.is_valid():
# make sure the user owns the account
account = form.cleaned_data['account']
if account.owner != request.user:
return HttpResponseForbidden()
# save the data
contact = form.save(commit=False)
contact.owner = request.user
contact.save()
# return the user to the account detail view
reverse_url = reverse(
'crmapp.accounts.views.account_detail',
args=(account.uuid,)
)
return HttpResponseRedirect(reverse_url)
else:
form = ContactForm()
variables = {
'form': form,
}
template = 'contacts/contact_cru.html'
return render(request, template, variables)
| Create the Contacts App - Part II > New Contact - Create View | Create the Contacts App - Part II > New Contact - Create View
| Python | mit | deenaariff/Django,tabdon/crmeasyapp,tabdon/crmeasyapp | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Contact
@login_required()
def contact_detail(request, uuid):
contact = Contact.objects.get(uuid=uuid)
return render(request,
'contacts/contact_detail.html',
{'contact': contact}
)
Create the Contacts App - Part II > New Contact - Create View | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponseForbidden
from .models import Contact
from .forms import ContactForm
@login_required()
def contact_detail(request, uuid):
contact = Contact.objects.get(uuid=uuid)
return render(request,
'contacts/contact_detail.html',
{'contact': contact}
)
@login_required()
def contact_cru(request):
if request.POST:
form = ContactForm(request.POST)
if form.is_valid():
# make sure the user owns the account
account = form.cleaned_data['account']
if account.owner != request.user:
return HttpResponseForbidden()
# save the data
contact = form.save(commit=False)
contact.owner = request.user
contact.save()
# return the user to the account detail view
reverse_url = reverse(
'crmapp.accounts.views.account_detail',
args=(account.uuid,)
)
return HttpResponseRedirect(reverse_url)
else:
form = ContactForm()
variables = {
'form': form,
}
template = 'contacts/contact_cru.html'
return render(request, template, variables)
| <commit_before>from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Contact
@login_required()
def contact_detail(request, uuid):
contact = Contact.objects.get(uuid=uuid)
return render(request,
'contacts/contact_detail.html',
{'contact': contact}
)
<commit_msg>Create the Contacts App - Part II > New Contact - Create View<commit_after> | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponseForbidden
from .models import Contact
from .forms import ContactForm
@login_required()
def contact_detail(request, uuid):
contact = Contact.objects.get(uuid=uuid)
return render(request,
'contacts/contact_detail.html',
{'contact': contact}
)
@login_required()
def contact_cru(request):
if request.POST:
form = ContactForm(request.POST)
if form.is_valid():
# make sure the user owns the account
account = form.cleaned_data['account']
if account.owner != request.user:
return HttpResponseForbidden()
# save the data
contact = form.save(commit=False)
contact.owner = request.user
contact.save()
# return the user to the account detail view
reverse_url = reverse(
'crmapp.accounts.views.account_detail',
args=(account.uuid,)
)
return HttpResponseRedirect(reverse_url)
else:
form = ContactForm()
variables = {
'form': form,
}
template = 'contacts/contact_cru.html'
return render(request, template, variables)
| from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Contact
@login_required()
def contact_detail(request, uuid):
contact = Contact.objects.get(uuid=uuid)
return render(request,
'contacts/contact_detail.html',
{'contact': contact}
)
Create the Contacts App - Part II > New Contact - Create Viewfrom django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponseForbidden
from .models import Contact
from .forms import ContactForm
@login_required()
def contact_detail(request, uuid):
contact = Contact.objects.get(uuid=uuid)
return render(request,
'contacts/contact_detail.html',
{'contact': contact}
)
@login_required()
def contact_cru(request):
if request.POST:
form = ContactForm(request.POST)
if form.is_valid():
# make sure the user owns the account
account = form.cleaned_data['account']
if account.owner != request.user:
return HttpResponseForbidden()
# save the data
contact = form.save(commit=False)
contact.owner = request.user
contact.save()
# return the user to the account detail view
reverse_url = reverse(
'crmapp.accounts.views.account_detail',
args=(account.uuid,)
)
return HttpResponseRedirect(reverse_url)
else:
form = ContactForm()
variables = {
'form': form,
}
template = 'contacts/contact_cru.html'
return render(request, template, variables)
| <commit_before>from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Contact
@login_required()
def contact_detail(request, uuid):
contact = Contact.objects.get(uuid=uuid)
return render(request,
'contacts/contact_detail.html',
{'contact': contact}
)
<commit_msg>Create the Contacts App - Part II > New Contact - Create View<commit_after>from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponseForbidden
from .models import Contact
from .forms import ContactForm
@login_required()
def contact_detail(request, uuid):
contact = Contact.objects.get(uuid=uuid)
return render(request,
'contacts/contact_detail.html',
{'contact': contact}
)
@login_required()
def contact_cru(request):
if request.POST:
form = ContactForm(request.POST)
if form.is_valid():
# make sure the user owns the account
account = form.cleaned_data['account']
if account.owner != request.user:
return HttpResponseForbidden()
# save the data
contact = form.save(commit=False)
contact.owner = request.user
contact.save()
# return the user to the account detail view
reverse_url = reverse(
'crmapp.accounts.views.account_detail',
args=(account.uuid,)
)
return HttpResponseRedirect(reverse_url)
else:
form = ContactForm()
variables = {
'form': form,
}
template = 'contacts/contact_cru.html'
return render(request, template, variables)
|
0a2fa84285a586282d79146f85d9efba12a528dd | Parallel/Testing/Cxx/TestSockets.py | Parallel/Testing/Cxx/TestSockets.py | """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
| """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
retVal = os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
sys.exit(os.WEXITSTATUS(retVal))
| Return code from script must reflect that of the test. | BUG: Return code from script must reflect that of the test.
| Python | bsd-3-clause | mspark93/VTK,jeffbaumes/jeffbaumes-vtk,demarle/VTK,sumedhasingla/VTK,sankhesh/VTK,mspark93/VTK,keithroe/vtkoptix,daviddoria/PointGraphsPhase1,SimVascular/VTK,collects/VTK,SimVascular/VTK,sumedhasingla/VTK,mspark93/VTK,biddisco/VTK,sgh/vtk,jmerkow/VTK,aashish24/VTK-old,demarle/VTK,demarle/VTK,aashish24/VTK-old,johnkit/vtk-dev,johnkit/vtk-dev,johnkit/vtk-dev,msmolens/VTK,hendradarwin/VTK,SimVascular/VTK,johnkit/vtk-dev,hendradarwin/VTK,cjh1/VTK,demarle/VTK,ashray/VTK-EVM,daviddoria/PointGraphsPhase1,sankhesh/VTK,keithroe/vtkoptix,Wuteyan/VTK,mspark93/VTK,spthaolt/VTK,candy7393/VTK,aashish24/VTK-old,jmerkow/VTK,sgh/vtk,gram526/VTK,Wuteyan/VTK,daviddoria/PointGraphsPhase1,sgh/vtk,spthaolt/VTK,keithroe/vtkoptix,sumedhasingla/VTK,hendradarwin/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,berendkleinhaneveld/VTK,jeffbaumes/jeffbaumes-vtk,jmerkow/VTK,sankhesh/VTK,SimVascular/VTK,ashray/VTK-EVM,keithroe/vtkoptix,ashray/VTK-EVM,arnaudgelas/VTK,biddisco/VTK,candy7393/VTK,collects/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,jeffbaumes/jeffbaumes-vtk,naucoin/VTKSlicerWidgets,aashish24/VTK-old,Wuteyan/VTK,msmolens/VTK,jmerkow/VTK,cjh1/VTK,jeffbaumes/jeffbaumes-vtk,naucoin/VTKSlicerWidgets,jmerkow/VTK,johnkit/vtk-dev,msmolens/VTK,jmerkow/VTK,spthaolt/VTK,cjh1/VTK,spthaolt/VTK,msmolens/VTK,biddisco/VTK,cjh1/VTK,collects/VTK,arnaudgelas/VTK,Wuteyan/VTK,aashish24/VTK-old,spthaolt/VTK,hendradarwin/VTK,mspark93/VTK,naucoin/VTKSlicerWidgets,naucoin/VTKSlicerWidgets,jeffbaumes/jeffbaumes-vtk,SimVascular/VTK,Wuteyan/VTK,sankhesh/VTK,sankhesh/VTK,hendradarwin/VTK,arnaudgelas/VTK,daviddoria/PointGraphsPhase1,collects/VTK,spthaolt/VTK,Wuteyan/VTK,johnkit/vtk-dev,Wuteyan/VTK,gram526/VTK,candy7393/VTK,candy7393/VTK,candy7393/VTK,keithroe/vtkoptix,keithroe/vtkoptix,sumedhasingla/VTK,sankhesh/VTK,berendkleinhaneveld/VTK,candy7393/VTK,msmolens/VTK,demarle/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,msmolens/VTK,ashray/VTK-EVM,daviddoria/PointGraphsPhase1,msmolens/VTK,keithroe/vtkoptix,gram526/VTK,sgh/vtk,sgh/vtk,keithroe/vtkoptix,berendkleinhaneveld/VTK,demarle/VTK,sankhesh/VTK,candy7393/VTK,daviddoria/PointGraphsPhase1,collects/VTK,cjh1/VTK,jeffbaumes/jeffbaumes-vtk,collects/VTK,johnkit/vtk-dev,gram526/VTK,sumedhasingla/VTK,biddisco/VTK,ashray/VTK-EVM,mspark93/VTK,mspark93/VTK,sgh/vtk,demarle/VTK,arnaudgelas/VTK,hendradarwin/VTK,jmerkow/VTK,gram526/VTK,candy7393/VTK,SimVascular/VTK,jmerkow/VTK,aashish24/VTK-old,gram526/VTK,biddisco/VTK,mspark93/VTK,sankhesh/VTK,hendradarwin/VTK,ashray/VTK-EVM,biddisco/VTK,SimVascular/VTK,msmolens/VTK,naucoin/VTKSlicerWidgets,biddisco/VTK,gram526/VTK,cjh1/VTK,ashray/VTK-EVM,SimVascular/VTK,naucoin/VTKSlicerWidgets,arnaudgelas/VTK,arnaudgelas/VTK,spthaolt/VTK,gram526/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,demarle/VTK | """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
BUG: Return code from script must reflect that of the test. | """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
retVal = os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
sys.exit(os.WEXITSTATUS(retVal))
| <commit_before>""" Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
<commit_msg>BUG: Return code from script must reflect that of the test.<commit_after> | """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
retVal = os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
sys.exit(os.WEXITSTATUS(retVal))
| """ Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
BUG: Return code from script must reflect that of the test.""" Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
retVal = os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
sys.exit(os.WEXITSTATUS(retVal))
| <commit_before>""" Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
<commit_msg>BUG: Return code from script must reflect that of the test.<commit_after>""" Driver script for testing sockets
Unix only
"""
import os, sys, time
# Fork, run server in child, client in parent
pid = os.fork()
if pid == 0:
# exec the parent
os.execv(sys.argv[1], ('-D', sys.argv[3]))
else:
# wait a little to make sure that the server is ready
time.sleep(10)
# run the client
retVal = os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3],
sys.argv[4] ))
# in case the client fails, we need to kill the server
# or it will stay around
time.sleep(20)
os.kill(pid, 15)
sys.exit(os.WEXITSTATUS(retVal))
|
52803c6cea6a1e1b06486f137f62e6e827cdcb1d | tests/conftest.py | tests/conftest.py | from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append(transport_url)
metafunc.parametrize('test', tests, ids=ids)
| from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append('%s:%s' % (token_type, transport_url))
metafunc.parametrize('test', tests, ids=ids)
| Add token type to test id | Add token type to test id
| Python | apache-2.0 | devicehive/devicehive-python | from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append(transport_url)
metafunc.parametrize('test', tests, ids=ids)
Add token type to test id | from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append('%s:%s' % (token_type, transport_url))
metafunc.parametrize('test', tests, ids=ids)
| <commit_before>from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append(transport_url)
metafunc.parametrize('test', tests, ids=ids)
<commit_msg>Add token type to test id<commit_after> | from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append('%s:%s' % (token_type, transport_url))
metafunc.parametrize('test', tests, ids=ids)
| from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append(transport_url)
metafunc.parametrize('test', tests, ids=ids)
Add token type to test idfrom tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append('%s:%s' % (token_type, transport_url))
metafunc.parametrize('test', tests, ids=ids)
| <commit_before>from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append(transport_url)
metafunc.parametrize('test', tests, ids=ids)
<commit_msg>Add token type to test id<commit_after>from tests.test import Test
def pytest_addoption(parser):
parser.addoption('--transport-urls', action='store', help='Transport urls')
parser.addoption('--admin-refresh-token', action='store',
help='Admin refresh tokens')
parser.addoption('--user-refresh-token', action='store',
help='User refresh tokens')
def pytest_generate_tests(metafunc):
if metafunc.module.__name__.find('.test_api') == -1:
return
transport_urls = metafunc.config.option.transport_urls.split(',')
refresh_tokens = {'admin': metafunc.config.option.admin_refresh_token,
'user': metafunc.config.option.user_refresh_token}
tests = []
ids = []
for transport_url in transport_urls:
for token_type, refresh_token in refresh_tokens.items():
if not refresh_token:
continue
tests.append(Test(transport_url, refresh_token, token_type))
ids.append('%s:%s' % (token_type, transport_url))
metafunc.parametrize('test', tests, ids=ids)
|
701402c4a51474b244ff28dd2d5c9a0731440308 | mozcal/events/api.py | mozcal/events/api.py | from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
| from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
filtering = {
"title": ('startswith',),
} | Allow filtering of event by title | Allow filtering of event by title
| Python | bsd-3-clause | ppapadeas/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents,ppapadeas/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents | from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
Allow filtering of event by title | from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
filtering = {
"title": ('startswith',),
} | <commit_before>from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
<commit_msg>Allow filtering of event by title<commit_after> | from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
filtering = {
"title": ('startswith',),
} | from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
Allow filtering of event by titlefrom tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
filtering = {
"title": ('startswith',),
} | <commit_before>from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
<commit_msg>Allow filtering of event by title<commit_after>from tastypie.resources import ModelResource
from models import Event
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
filtering = {
"title": ('startswith',),
} |
f5af9624359523ddf67b63327d8fe85382497c47 | pycroft/helpers/user.py | pycroft/helpers/user.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
ldap_context = ldap_context.copy(default="ldap_sha512_crypt")
def generate_password(length):
charset = "abcdefghijklmnopqrstuvwxyz!$%&()=.," \
":;-_#+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return passlib.utils.generate_password(length, charset)
def hash_password(plaintext_passwd):
"""Use a ldap_context to generate a RFC 2307 from given plaintext.
The ldap_context is configured to generate the very secure ldap_sha512_crypt
hashes (a crypt extension available since glibc 2.7).
"""
return ldap_context.encrypt(plaintext_passwd)
def verify_password(plaintext_password, hash):
"""Verifies a plain password string against a given password hash.
It uses a ldap_context to verify RFC 2307 hashes.
"""
try:
return ldap_context.verify(plaintext_password, hash)
except ValueError:
return False
| # -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
crypt_context = ldap_context.copy(
default="ldap_sha512_crypt",
deprecated=["ldap_plaintext", "ldap_md5", "ldap_sha1", "ldap_salted_md5",
"ldap_des_crypt", "ldap_bsdi_crypt", "ldap_md5_crypt"])
def generate_password(length):
charset = "abcdefghijklmnopqrstuvwxyz!$%&()=.," \
":;-_#+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return passlib.utils.generate_password(length, charset)
def hash_password(plaintext_passwd):
"""Generate a RFC 2307 complaint hash from given plaintext.
The passlib CryptContext is configured to generate the very secure
ldap_sha512_crypt hashes (a crypt extension available since glibc 2.7).
"""
return crypt_context.encrypt(plaintext_passwd)
def verify_password(plaintext_password, hash):
"""Verifies a plain password string against a given password hash.
It uses a crypt_context to verify RFC 2307 hashes.
"""
try:
return crypt_context.verify(plaintext_password, hash)
except ValueError:
return False
| Set deprecated password hashing schemes | Set deprecated password hashing schemes
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft | # -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
ldap_context = ldap_context.copy(default="ldap_sha512_crypt")
def generate_password(length):
charset = "abcdefghijklmnopqrstuvwxyz!$%&()=.," \
":;-_#+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return passlib.utils.generate_password(length, charset)
def hash_password(plaintext_passwd):
"""Use a ldap_context to generate a RFC 2307 from given plaintext.
The ldap_context is configured to generate the very secure ldap_sha512_crypt
hashes (a crypt extension available since glibc 2.7).
"""
return ldap_context.encrypt(plaintext_passwd)
def verify_password(plaintext_password, hash):
"""Verifies a plain password string against a given password hash.
It uses a ldap_context to verify RFC 2307 hashes.
"""
try:
return ldap_context.verify(plaintext_password, hash)
except ValueError:
return False
Set deprecated password hashing schemes | # -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
crypt_context = ldap_context.copy(
default="ldap_sha512_crypt",
deprecated=["ldap_plaintext", "ldap_md5", "ldap_sha1", "ldap_salted_md5",
"ldap_des_crypt", "ldap_bsdi_crypt", "ldap_md5_crypt"])
def generate_password(length):
charset = "abcdefghijklmnopqrstuvwxyz!$%&()=.," \
":;-_#+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return passlib.utils.generate_password(length, charset)
def hash_password(plaintext_passwd):
"""Generate a RFC 2307 complaint hash from given plaintext.
The passlib CryptContext is configured to generate the very secure
ldap_sha512_crypt hashes (a crypt extension available since glibc 2.7).
"""
return crypt_context.encrypt(plaintext_passwd)
def verify_password(plaintext_password, hash):
"""Verifies a plain password string against a given password hash.
It uses a crypt_context to verify RFC 2307 hashes.
"""
try:
return crypt_context.verify(plaintext_password, hash)
except ValueError:
return False
| <commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
ldap_context = ldap_context.copy(default="ldap_sha512_crypt")
def generate_password(length):
charset = "abcdefghijklmnopqrstuvwxyz!$%&()=.," \
":;-_#+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return passlib.utils.generate_password(length, charset)
def hash_password(plaintext_passwd):
"""Use a ldap_context to generate a RFC 2307 from given plaintext.
The ldap_context is configured to generate the very secure ldap_sha512_crypt
hashes (a crypt extension available since glibc 2.7).
"""
return ldap_context.encrypt(plaintext_passwd)
def verify_password(plaintext_password, hash):
"""Verifies a plain password string against a given password hash.
It uses a ldap_context to verify RFC 2307 hashes.
"""
try:
return ldap_context.verify(plaintext_password, hash)
except ValueError:
return False
<commit_msg>Set deprecated password hashing schemes<commit_after> | # -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
crypt_context = ldap_context.copy(
default="ldap_sha512_crypt",
deprecated=["ldap_plaintext", "ldap_md5", "ldap_sha1", "ldap_salted_md5",
"ldap_des_crypt", "ldap_bsdi_crypt", "ldap_md5_crypt"])
def generate_password(length):
charset = "abcdefghijklmnopqrstuvwxyz!$%&()=.," \
":;-_#+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return passlib.utils.generate_password(length, charset)
def hash_password(plaintext_passwd):
"""Generate a RFC 2307 complaint hash from given plaintext.
The passlib CryptContext is configured to generate the very secure
ldap_sha512_crypt hashes (a crypt extension available since glibc 2.7).
"""
return crypt_context.encrypt(plaintext_passwd)
def verify_password(plaintext_password, hash):
"""Verifies a plain password string against a given password hash.
It uses a crypt_context to verify RFC 2307 hashes.
"""
try:
return crypt_context.verify(plaintext_password, hash)
except ValueError:
return False
| # -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
ldap_context = ldap_context.copy(default="ldap_sha512_crypt")
def generate_password(length):
charset = "abcdefghijklmnopqrstuvwxyz!$%&()=.," \
":;-_#+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return passlib.utils.generate_password(length, charset)
def hash_password(plaintext_passwd):
"""Use a ldap_context to generate a RFC 2307 from given plaintext.
The ldap_context is configured to generate the very secure ldap_sha512_crypt
hashes (a crypt extension available since glibc 2.7).
"""
return ldap_context.encrypt(plaintext_passwd)
def verify_password(plaintext_password, hash):
"""Verifies a plain password string against a given password hash.
It uses a ldap_context to verify RFC 2307 hashes.
"""
try:
return ldap_context.verify(plaintext_password, hash)
except ValueError:
return False
Set deprecated password hashing schemes# -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
crypt_context = ldap_context.copy(
default="ldap_sha512_crypt",
deprecated=["ldap_plaintext", "ldap_md5", "ldap_sha1", "ldap_salted_md5",
"ldap_des_crypt", "ldap_bsdi_crypt", "ldap_md5_crypt"])
def generate_password(length):
charset = "abcdefghijklmnopqrstuvwxyz!$%&()=.," \
":;-_#+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return passlib.utils.generate_password(length, charset)
def hash_password(plaintext_passwd):
"""Generate a RFC 2307 complaint hash from given plaintext.
The passlib CryptContext is configured to generate the very secure
ldap_sha512_crypt hashes (a crypt extension available since glibc 2.7).
"""
return crypt_context.encrypt(plaintext_passwd)
def verify_password(plaintext_password, hash):
"""Verifies a plain password string against a given password hash.
It uses a crypt_context to verify RFC 2307 hashes.
"""
try:
return crypt_context.verify(plaintext_password, hash)
except ValueError:
return False
| <commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
ldap_context = ldap_context.copy(default="ldap_sha512_crypt")
def generate_password(length):
charset = "abcdefghijklmnopqrstuvwxyz!$%&()=.," \
":;-_#+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return passlib.utils.generate_password(length, charset)
def hash_password(plaintext_passwd):
"""Use a ldap_context to generate a RFC 2307 from given plaintext.
The ldap_context is configured to generate the very secure ldap_sha512_crypt
hashes (a crypt extension available since glibc 2.7).
"""
return ldap_context.encrypt(plaintext_passwd)
def verify_password(plaintext_password, hash):
"""Verifies a plain password string against a given password hash.
It uses a ldap_context to verify RFC 2307 hashes.
"""
try:
return ldap_context.verify(plaintext_password, hash)
except ValueError:
return False
<commit_msg>Set deprecated password hashing schemes<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from passlib.apps import ldap_context
import passlib.utils
crypt_context = ldap_context.copy(
default="ldap_sha512_crypt",
deprecated=["ldap_plaintext", "ldap_md5", "ldap_sha1", "ldap_salted_md5",
"ldap_des_crypt", "ldap_bsdi_crypt", "ldap_md5_crypt"])
def generate_password(length):
charset = "abcdefghijklmnopqrstuvwxyz!$%&()=.," \
":;-_#+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return passlib.utils.generate_password(length, charset)
def hash_password(plaintext_passwd):
"""Generate a RFC 2307 complaint hash from given plaintext.
The passlib CryptContext is configured to generate the very secure
ldap_sha512_crypt hashes (a crypt extension available since glibc 2.7).
"""
return crypt_context.encrypt(plaintext_passwd)
def verify_password(plaintext_password, hash):
"""Verifies a plain password string against a given password hash.
It uses a crypt_context to verify RFC 2307 hashes.
"""
try:
return crypt_context.verify(plaintext_password, hash)
except ValueError:
return False
|
5e60696e781b538bdffd9db15eca28b22ed3c705 | myuw_mobile/views.py | myuw_mobile/views.py | from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging.getLogger('myuw_mobile.views')
#@mobile_template('{mobile/}index.html')
def index(request):
context = {'year': None,
'quarter': None,
'regid': None,
'myuw_base_url': '',
'err': None}
person_dao = PersonDAO()
try:
person = person_dao.get_person_by_netid("javerage")
request.session["user_netid"] = person.uwnetid
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get regid'
try:
cur_term = Quarter().get_cur_quarter()
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get quarter '
else:
context['year'] = cur_term.year
context['quarter'] = cur_term.quarter
return render_to_response('index.html',
context,
context_instance=RequestContext(request))
| from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.conf import settings
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging.getLogger('myuw_mobile.views')
#@mobile_template('{mobile/}index.html')
def index(request):
context = {'year': None,
'quarter': None,
'regid': None,
'myuw_base_url': '',
'err': None}
if settings.DEBUG:
netid = 'javerage'
else:
netid = request.user
if netid is None:
raise("Must have a logged in user when DEBUG is off")
person_dao = PersonDAO()
try:
person = person_dao.get_person_by_netid(netid)
request.session["user_netid"] = person.uwnetid
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get regid'
try:
cur_term = Quarter().get_cur_quarter()
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get quarter '
else:
context['year'] = cur_term.year
context['quarter'] = cur_term.quarter
return render_to_response('index.html',
context,
context_instance=RequestContext(request))
| Allow javerage to persist as the user if debug is on, otherwise use request.user - allows this to work behind pubcookie/other auth | Allow javerage to persist as the user if debug is on, otherwise use request.user - allows this to work behind pubcookie/other auth
| Python | apache-2.0 | uw-it-aca/myuw,fanglinfang/myuw,uw-it-aca/myuw,uw-it-aca/myuw,fanglinfang/myuw,uw-it-aca/myuw,fanglinfang/myuw | from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging.getLogger('myuw_mobile.views')
#@mobile_template('{mobile/}index.html')
def index(request):
context = {'year': None,
'quarter': None,
'regid': None,
'myuw_base_url': '',
'err': None}
person_dao = PersonDAO()
try:
person = person_dao.get_person_by_netid("javerage")
request.session["user_netid"] = person.uwnetid
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get regid'
try:
cur_term = Quarter().get_cur_quarter()
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get quarter '
else:
context['year'] = cur_term.year
context['quarter'] = cur_term.quarter
return render_to_response('index.html',
context,
context_instance=RequestContext(request))
Allow javerage to persist as the user if debug is on, otherwise use request.user - allows this to work behind pubcookie/other auth | from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.conf import settings
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging.getLogger('myuw_mobile.views')
#@mobile_template('{mobile/}index.html')
def index(request):
context = {'year': None,
'quarter': None,
'regid': None,
'myuw_base_url': '',
'err': None}
if settings.DEBUG:
netid = 'javerage'
else:
netid = request.user
if netid is None:
raise("Must have a logged in user when DEBUG is off")
person_dao = PersonDAO()
try:
person = person_dao.get_person_by_netid(netid)
request.session["user_netid"] = person.uwnetid
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get regid'
try:
cur_term = Quarter().get_cur_quarter()
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get quarter '
else:
context['year'] = cur_term.year
context['quarter'] = cur_term.quarter
return render_to_response('index.html',
context,
context_instance=RequestContext(request))
| <commit_before>from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging.getLogger('myuw_mobile.views')
#@mobile_template('{mobile/}index.html')
def index(request):
context = {'year': None,
'quarter': None,
'regid': None,
'myuw_base_url': '',
'err': None}
person_dao = PersonDAO()
try:
person = person_dao.get_person_by_netid("javerage")
request.session["user_netid"] = person.uwnetid
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get regid'
try:
cur_term = Quarter().get_cur_quarter()
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get quarter '
else:
context['year'] = cur_term.year
context['quarter'] = cur_term.quarter
return render_to_response('index.html',
context,
context_instance=RequestContext(request))
<commit_msg>Allow javerage to persist as the user if debug is on, otherwise use request.user - allows this to work behind pubcookie/other auth<commit_after> | from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.conf import settings
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging.getLogger('myuw_mobile.views')
#@mobile_template('{mobile/}index.html')
def index(request):
context = {'year': None,
'quarter': None,
'regid': None,
'myuw_base_url': '',
'err': None}
if settings.DEBUG:
netid = 'javerage'
else:
netid = request.user
if netid is None:
raise("Must have a logged in user when DEBUG is off")
person_dao = PersonDAO()
try:
person = person_dao.get_person_by_netid(netid)
request.session["user_netid"] = person.uwnetid
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get regid'
try:
cur_term = Quarter().get_cur_quarter()
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get quarter '
else:
context['year'] = cur_term.year
context['quarter'] = cur_term.quarter
return render_to_response('index.html',
context,
context_instance=RequestContext(request))
| from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging.getLogger('myuw_mobile.views')
#@mobile_template('{mobile/}index.html')
def index(request):
context = {'year': None,
'quarter': None,
'regid': None,
'myuw_base_url': '',
'err': None}
person_dao = PersonDAO()
try:
person = person_dao.get_person_by_netid("javerage")
request.session["user_netid"] = person.uwnetid
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get regid'
try:
cur_term = Quarter().get_cur_quarter()
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get quarter '
else:
context['year'] = cur_term.year
context['quarter'] = cur_term.quarter
return render_to_response('index.html',
context,
context_instance=RequestContext(request))
Allow javerage to persist as the user if debug is on, otherwise use request.user - allows this to work behind pubcookie/other authfrom django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.conf import settings
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging.getLogger('myuw_mobile.views')
#@mobile_template('{mobile/}index.html')
def index(request):
context = {'year': None,
'quarter': None,
'regid': None,
'myuw_base_url': '',
'err': None}
if settings.DEBUG:
netid = 'javerage'
else:
netid = request.user
if netid is None:
raise("Must have a logged in user when DEBUG is off")
person_dao = PersonDAO()
try:
person = person_dao.get_person_by_netid(netid)
request.session["user_netid"] = person.uwnetid
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get regid'
try:
cur_term = Quarter().get_cur_quarter()
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get quarter '
else:
context['year'] = cur_term.year
context['quarter'] = cur_term.quarter
return render_to_response('index.html',
context,
context_instance=RequestContext(request))
| <commit_before>from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging.getLogger('myuw_mobile.views')
#@mobile_template('{mobile/}index.html')
def index(request):
context = {'year': None,
'quarter': None,
'regid': None,
'myuw_base_url': '',
'err': None}
person_dao = PersonDAO()
try:
person = person_dao.get_person_by_netid("javerage")
request.session["user_netid"] = person.uwnetid
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get regid'
try:
cur_term = Quarter().get_cur_quarter()
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get quarter '
else:
context['year'] = cur_term.year
context['quarter'] = cur_term.quarter
return render_to_response('index.html',
context,
context_instance=RequestContext(request))
<commit_msg>Allow javerage to persist as the user if debug is on, otherwise use request.user - allows this to work behind pubcookie/other auth<commit_after>from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.conf import settings
import logging
from myuw_api.sws_dao import Quarter
from myuw_api.pws_dao import Person as PersonDAO
logger = logging.getLogger('myuw_mobile.views')
#@mobile_template('{mobile/}index.html')
def index(request):
context = {'year': None,
'quarter': None,
'regid': None,
'myuw_base_url': '',
'err': None}
if settings.DEBUG:
netid = 'javerage'
else:
netid = request.user
if netid is None:
raise("Must have a logged in user when DEBUG is off")
person_dao = PersonDAO()
try:
person = person_dao.get_person_by_netid(netid)
request.session["user_netid"] = person.uwnetid
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get regid'
try:
cur_term = Quarter().get_cur_quarter()
except Exception, message:
logger.error(message)
context['err'] = 'Failed to get quarter '
else:
context['year'] = cur_term.year
context['quarter'] = cur_term.quarter
return render_to_response('index.html',
context,
context_instance=RequestContext(request))
|
a5409ca51e95b4d6ca99a63e0422ca1fe8d344f8 | tags/templatetags/tags_tags.py | tags/templatetags/tags_tags.py | # -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.db.models.loading import get_model
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
| # -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.loading import get_model
from django.http import Http404
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
try:
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
except ObjectDoesNotExist:
raise Http404
| Fix server error in tag search for non-existing tag. | Fix server error in tag search for non-existing tag.
| Python | bsd-3-clause | ugoertz/django-familio,ugoertz/django-familio,ugoertz/django-familio,ugoertz/django-familio | # -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.db.models.loading import get_model
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
Fix server error in tag search for non-existing tag. | # -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.loading import get_model
from django.http import Http404
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
try:
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
except ObjectDoesNotExist:
raise Http404
| <commit_before># -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.db.models.loading import get_model
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
<commit_msg>Fix server error in tag search for non-existing tag.<commit_after> | # -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.loading import get_model
from django.http import Http404
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
try:
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
except ObjectDoesNotExist:
raise Http404
| # -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.db.models.loading import get_model
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
Fix server error in tag search for non-existing tag.# -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.loading import get_model
from django.http import Http404
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
try:
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
except ObjectDoesNotExist:
raise Http404
| <commit_before># -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.db.models.loading import get_model
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
<commit_msg>Fix server error in tag search for non-existing tag.<commit_after># -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.loading import get_model
from django.http import Http404
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
try:
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
except ObjectDoesNotExist:
raise Http404
|
33f1c68dbb0228cf995fb120f659fbad20968bf6 | mopidy_dleyna/__init__.py | mopidy_dleyna/__init__.py | import os
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(os.path.join(os.path.dirname(__file__), "ext.conf"))
def get_config_schema(self):
schema = super().get_config_schema()
schema["upnp_browse_limit"] = config.Integer(minimum=0)
schema["upnp_lookup_limit"] = config.Integer(minimum=0)
schema["upnp_search_limit"] = config.Integer(minimum=0)
schema["dbus_start_session"] = config.String()
return schema
def setup(self, registry):
from .backend import dLeynaBackend
registry.add("backend", dLeynaBackend)
def validate_environment(self):
try:
import dbus # noqa
except ImportError:
raise exceptions.ExtensionError("Cannot import dbus")
| import pathlib
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["upnp_browse_limit"] = config.Integer(minimum=0)
schema["upnp_lookup_limit"] = config.Integer(minimum=0)
schema["upnp_search_limit"] = config.Integer(minimum=0)
schema["dbus_start_session"] = config.String()
return schema
def setup(self, registry):
from .backend import dLeynaBackend
registry.add("backend", dLeynaBackend)
def validate_environment(self):
try:
import dbus # noqa
except ImportError:
raise exceptions.ExtensionError("Cannot import dbus")
| Use pathlib to read ext.conf | Use pathlib to read ext.conf
| Python | apache-2.0 | tkem/mopidy-dleyna | import os
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(os.path.join(os.path.dirname(__file__), "ext.conf"))
def get_config_schema(self):
schema = super().get_config_schema()
schema["upnp_browse_limit"] = config.Integer(minimum=0)
schema["upnp_lookup_limit"] = config.Integer(minimum=0)
schema["upnp_search_limit"] = config.Integer(minimum=0)
schema["dbus_start_session"] = config.String()
return schema
def setup(self, registry):
from .backend import dLeynaBackend
registry.add("backend", dLeynaBackend)
def validate_environment(self):
try:
import dbus # noqa
except ImportError:
raise exceptions.ExtensionError("Cannot import dbus")
Use pathlib to read ext.conf | import pathlib
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["upnp_browse_limit"] = config.Integer(minimum=0)
schema["upnp_lookup_limit"] = config.Integer(minimum=0)
schema["upnp_search_limit"] = config.Integer(minimum=0)
schema["dbus_start_session"] = config.String()
return schema
def setup(self, registry):
from .backend import dLeynaBackend
registry.add("backend", dLeynaBackend)
def validate_environment(self):
try:
import dbus # noqa
except ImportError:
raise exceptions.ExtensionError("Cannot import dbus")
| <commit_before>import os
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(os.path.join(os.path.dirname(__file__), "ext.conf"))
def get_config_schema(self):
schema = super().get_config_schema()
schema["upnp_browse_limit"] = config.Integer(minimum=0)
schema["upnp_lookup_limit"] = config.Integer(minimum=0)
schema["upnp_search_limit"] = config.Integer(minimum=0)
schema["dbus_start_session"] = config.String()
return schema
def setup(self, registry):
from .backend import dLeynaBackend
registry.add("backend", dLeynaBackend)
def validate_environment(self):
try:
import dbus # noqa
except ImportError:
raise exceptions.ExtensionError("Cannot import dbus")
<commit_msg>Use pathlib to read ext.conf<commit_after> | import pathlib
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["upnp_browse_limit"] = config.Integer(minimum=0)
schema["upnp_lookup_limit"] = config.Integer(minimum=0)
schema["upnp_search_limit"] = config.Integer(minimum=0)
schema["dbus_start_session"] = config.String()
return schema
def setup(self, registry):
from .backend import dLeynaBackend
registry.add("backend", dLeynaBackend)
def validate_environment(self):
try:
import dbus # noqa
except ImportError:
raise exceptions.ExtensionError("Cannot import dbus")
| import os
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(os.path.join(os.path.dirname(__file__), "ext.conf"))
def get_config_schema(self):
schema = super().get_config_schema()
schema["upnp_browse_limit"] = config.Integer(minimum=0)
schema["upnp_lookup_limit"] = config.Integer(minimum=0)
schema["upnp_search_limit"] = config.Integer(minimum=0)
schema["dbus_start_session"] = config.String()
return schema
def setup(self, registry):
from .backend import dLeynaBackend
registry.add("backend", dLeynaBackend)
def validate_environment(self):
try:
import dbus # noqa
except ImportError:
raise exceptions.ExtensionError("Cannot import dbus")
Use pathlib to read ext.confimport pathlib
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["upnp_browse_limit"] = config.Integer(minimum=0)
schema["upnp_lookup_limit"] = config.Integer(minimum=0)
schema["upnp_search_limit"] = config.Integer(minimum=0)
schema["dbus_start_session"] = config.String()
return schema
def setup(self, registry):
from .backend import dLeynaBackend
registry.add("backend", dLeynaBackend)
def validate_environment(self):
try:
import dbus # noqa
except ImportError:
raise exceptions.ExtensionError("Cannot import dbus")
| <commit_before>import os
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(os.path.join(os.path.dirname(__file__), "ext.conf"))
def get_config_schema(self):
schema = super().get_config_schema()
schema["upnp_browse_limit"] = config.Integer(minimum=0)
schema["upnp_lookup_limit"] = config.Integer(minimum=0)
schema["upnp_search_limit"] = config.Integer(minimum=0)
schema["dbus_start_session"] = config.String()
return schema
def setup(self, registry):
from .backend import dLeynaBackend
registry.add("backend", dLeynaBackend)
def validate_environment(self):
try:
import dbus # noqa
except ImportError:
raise exceptions.ExtensionError("Cannot import dbus")
<commit_msg>Use pathlib to read ext.conf<commit_after>import pathlib
from mopidy import config, exceptions, ext
__version__ = "1.2.2"
class Extension(ext.Extension):
dist_name = "Mopidy-dLeyna"
ext_name = "dleyna"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["upnp_browse_limit"] = config.Integer(minimum=0)
schema["upnp_lookup_limit"] = config.Integer(minimum=0)
schema["upnp_search_limit"] = config.Integer(minimum=0)
schema["dbus_start_session"] = config.String()
return schema
def setup(self, registry):
from .backend import dLeynaBackend
registry.add("backend", dLeynaBackend)
def validate_environment(self):
try:
import dbus # noqa
except ImportError:
raise exceptions.ExtensionError("Cannot import dbus")
|
0f48c588e8f7f3a2a678b981d58df0e792bfdf1d | mopidy_pandora/pydora.py | mopidy_pandora/pydora.py | import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
def get_playlist(self, station_token):
return super(MopidyPandoraAPIClient, self).get_playlist(station_token)
| import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
| Remove superfluous override of 'get_playlist'. | Remove superfluous override of 'get_playlist'.
| Python | apache-2.0 | rectalogic/mopidy-pandora,jcass77/mopidy-pandora | import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
def get_playlist(self, station_token):
return super(MopidyPandoraAPIClient, self).get_playlist(station_token)
Remove superfluous override of 'get_playlist'. | import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
| <commit_before>import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
def get_playlist(self, station_token):
return super(MopidyPandoraAPIClient, self).get_playlist(station_token)
<commit_msg>Remove superfluous override of 'get_playlist'.<commit_after> | import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
| import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
def get_playlist(self, station_token):
return super(MopidyPandoraAPIClient, self).get_playlist(station_token)
Remove superfluous override of 'get_playlist'.import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
| <commit_before>import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
def get_playlist(self, station_token):
return super(MopidyPandoraAPIClient, self).get_playlist(station_token)
<commit_msg>Remove superfluous override of 'get_playlist'.<commit_after>import logging
import pandora
logger = logging.getLogger(__name__)
class MopidyPandoraAPIClient(pandora.APIClient):
"""Pydora API Client for Mopidy-Pandora
This API client implements caching of the station list.
"""
def __init__(self, transport, partner_user, partner_password, device,
default_audio_quality=pandora.BaseAPIClient.MED_AUDIO_QUALITY):
super(MopidyPandoraAPIClient, self).__init__(transport, partner_user, partner_password, device,
default_audio_quality)
self.station_list = None
def get_station_list(self):
if self.station_list is None or not any(self.station_list) or self.station_list.has_changed():
self.station_list = super(MopidyPandoraAPIClient, self).get_station_list()
return self.station_list
def get_station(self, station_token):
return self.get_station_list()[station_token]
|
ff187c82a0aa5d06c23a3a4a7974018a63699c6a | sir/indexing.py | sir/indexing.py | from . import querying
from logging import getLogger
logger = getLogger("sir")
def index_entity(solr_connection, query, search_entity):
"""
Indexes a single entity type.
:param solr.Solr solr_connection:
:param sqlalchemy.orm.query.Query query:
:param sir.schema.search_entity.SearchEntity search_entity:
"""
for row in query:
data = query_result_to_dict(search_entity, row)
logger.info("Sending a document to solr: %s", data)
solr_connection.add(data)
def query_result_to_dict(entity, obj):
"""
Converts the result of single ``query`` result into a dictionary via the
field specification of ``entity``.
:param sir.schema.searchentities.SearchEntity entity:
:param obj: A :ref:`declarative <sqla:declarative_toplevel>` object.
"""
data = {}
for field in entity.fields:
fieldname = field.name
tempvals = set()
for path in field.paths:
for val in querying._iterate_path_values(path, obj):
tempvals.add(val)
if len(tempvals) == 1:
tempvals = tempvals.pop()
if field.transformfunc is not None:
tempvals = field.transformfunc(tempvals)
data[fieldname] = tempvals
return data
| from . import querying
from logging import getLogger
logger = getLogger("sir")
def index_entity(solr_connection, query, search_entity):
"""
Indexes a single entity type.
:param solr.Solr solr_connection:
:param sqlalchemy.orm.query.Query query:
:param sir.schema.searchentities.SearchEntity search_entity:
"""
for row in query:
data = query_result_to_dict(search_entity, row)
logger.info("Sending a document to solr: %s", data)
solr_connection.add(data)
def query_result_to_dict(entity, obj):
"""
Converts the result of single ``query`` result into a dictionary via the
field specification of ``entity``.
:param sir.schema.searchentities.SearchEntity entity:
:param obj: A :ref:`declarative <sqla:declarative_toplevel>` object.
"""
data = {}
for field in entity.fields:
fieldname = field.name
tempvals = set()
for path in field.paths:
for val in querying._iterate_path_values(path, obj):
tempvals.add(val)
if len(tempvals) == 1:
tempvals = tempvals.pop()
if field.transformfunc is not None:
tempvals = field.transformfunc(tempvals)
data[fieldname] = tempvals
return data
| Fix a link in index_entity's docstring | Fix a link in index_entity's docstring
| Python | mit | jeffweeksio/sir | from . import querying
from logging import getLogger
logger = getLogger("sir")
def index_entity(solr_connection, query, search_entity):
"""
Indexes a single entity type.
:param solr.Solr solr_connection:
:param sqlalchemy.orm.query.Query query:
:param sir.schema.search_entity.SearchEntity search_entity:
"""
for row in query:
data = query_result_to_dict(search_entity, row)
logger.info("Sending a document to solr: %s", data)
solr_connection.add(data)
def query_result_to_dict(entity, obj):
"""
Converts the result of single ``query`` result into a dictionary via the
field specification of ``entity``.
:param sir.schema.searchentities.SearchEntity entity:
:param obj: A :ref:`declarative <sqla:declarative_toplevel>` object.
"""
data = {}
for field in entity.fields:
fieldname = field.name
tempvals = set()
for path in field.paths:
for val in querying._iterate_path_values(path, obj):
tempvals.add(val)
if len(tempvals) == 1:
tempvals = tempvals.pop()
if field.transformfunc is not None:
tempvals = field.transformfunc(tempvals)
data[fieldname] = tempvals
return data
Fix a link in index_entity's docstring | from . import querying
from logging import getLogger
logger = getLogger("sir")
def index_entity(solr_connection, query, search_entity):
"""
Indexes a single entity type.
:param solr.Solr solr_connection:
:param sqlalchemy.orm.query.Query query:
:param sir.schema.searchentities.SearchEntity search_entity:
"""
for row in query:
data = query_result_to_dict(search_entity, row)
logger.info("Sending a document to solr: %s", data)
solr_connection.add(data)
def query_result_to_dict(entity, obj):
"""
Converts the result of single ``query`` result into a dictionary via the
field specification of ``entity``.
:param sir.schema.searchentities.SearchEntity entity:
:param obj: A :ref:`declarative <sqla:declarative_toplevel>` object.
"""
data = {}
for field in entity.fields:
fieldname = field.name
tempvals = set()
for path in field.paths:
for val in querying._iterate_path_values(path, obj):
tempvals.add(val)
if len(tempvals) == 1:
tempvals = tempvals.pop()
if field.transformfunc is not None:
tempvals = field.transformfunc(tempvals)
data[fieldname] = tempvals
return data
| <commit_before>from . import querying
from logging import getLogger
logger = getLogger("sir")
def index_entity(solr_connection, query, search_entity):
"""
Indexes a single entity type.
:param solr.Solr solr_connection:
:param sqlalchemy.orm.query.Query query:
:param sir.schema.search_entity.SearchEntity search_entity:
"""
for row in query:
data = query_result_to_dict(search_entity, row)
logger.info("Sending a document to solr: %s", data)
solr_connection.add(data)
def query_result_to_dict(entity, obj):
"""
Converts the result of single ``query`` result into a dictionary via the
field specification of ``entity``.
:param sir.schema.searchentities.SearchEntity entity:
:param obj: A :ref:`declarative <sqla:declarative_toplevel>` object.
"""
data = {}
for field in entity.fields:
fieldname = field.name
tempvals = set()
for path in field.paths:
for val in querying._iterate_path_values(path, obj):
tempvals.add(val)
if len(tempvals) == 1:
tempvals = tempvals.pop()
if field.transformfunc is not None:
tempvals = field.transformfunc(tempvals)
data[fieldname] = tempvals
return data
<commit_msg>Fix a link in index_entity's docstring<commit_after> | from . import querying
from logging import getLogger
logger = getLogger("sir")
def index_entity(solr_connection, query, search_entity):
"""
Indexes a single entity type.
:param solr.Solr solr_connection:
:param sqlalchemy.orm.query.Query query:
:param sir.schema.searchentities.SearchEntity search_entity:
"""
for row in query:
data = query_result_to_dict(search_entity, row)
logger.info("Sending a document to solr: %s", data)
solr_connection.add(data)
def query_result_to_dict(entity, obj):
"""
Converts the result of single ``query`` result into a dictionary via the
field specification of ``entity``.
:param sir.schema.searchentities.SearchEntity entity:
:param obj: A :ref:`declarative <sqla:declarative_toplevel>` object.
"""
data = {}
for field in entity.fields:
fieldname = field.name
tempvals = set()
for path in field.paths:
for val in querying._iterate_path_values(path, obj):
tempvals.add(val)
if len(tempvals) == 1:
tempvals = tempvals.pop()
if field.transformfunc is not None:
tempvals = field.transformfunc(tempvals)
data[fieldname] = tempvals
return data
| from . import querying
from logging import getLogger
logger = getLogger("sir")
def index_entity(solr_connection, query, search_entity):
"""
Indexes a single entity type.
:param solr.Solr solr_connection:
:param sqlalchemy.orm.query.Query query:
:param sir.schema.search_entity.SearchEntity search_entity:
"""
for row in query:
data = query_result_to_dict(search_entity, row)
logger.info("Sending a document to solr: %s", data)
solr_connection.add(data)
def query_result_to_dict(entity, obj):
"""
Converts the result of single ``query`` result into a dictionary via the
field specification of ``entity``.
:param sir.schema.searchentities.SearchEntity entity:
:param obj: A :ref:`declarative <sqla:declarative_toplevel>` object.
"""
data = {}
for field in entity.fields:
fieldname = field.name
tempvals = set()
for path in field.paths:
for val in querying._iterate_path_values(path, obj):
tempvals.add(val)
if len(tempvals) == 1:
tempvals = tempvals.pop()
if field.transformfunc is not None:
tempvals = field.transformfunc(tempvals)
data[fieldname] = tempvals
return data
Fix a link in index_entity's docstringfrom . import querying
from logging import getLogger
logger = getLogger("sir")
def index_entity(solr_connection, query, search_entity):
"""
Indexes a single entity type.
:param solr.Solr solr_connection:
:param sqlalchemy.orm.query.Query query:
:param sir.schema.searchentities.SearchEntity search_entity:
"""
for row in query:
data = query_result_to_dict(search_entity, row)
logger.info("Sending a document to solr: %s", data)
solr_connection.add(data)
def query_result_to_dict(entity, obj):
"""
Converts the result of single ``query`` result into a dictionary via the
field specification of ``entity``.
:param sir.schema.searchentities.SearchEntity entity:
:param obj: A :ref:`declarative <sqla:declarative_toplevel>` object.
"""
data = {}
for field in entity.fields:
fieldname = field.name
tempvals = set()
for path in field.paths:
for val in querying._iterate_path_values(path, obj):
tempvals.add(val)
if len(tempvals) == 1:
tempvals = tempvals.pop()
if field.transformfunc is not None:
tempvals = field.transformfunc(tempvals)
data[fieldname] = tempvals
return data
| <commit_before>from . import querying
from logging import getLogger
logger = getLogger("sir")
def index_entity(solr_connection, query, search_entity):
"""
Indexes a single entity type.
:param solr.Solr solr_connection:
:param sqlalchemy.orm.query.Query query:
:param sir.schema.search_entity.SearchEntity search_entity:
"""
for row in query:
data = query_result_to_dict(search_entity, row)
logger.info("Sending a document to solr: %s", data)
solr_connection.add(data)
def query_result_to_dict(entity, obj):
"""
Converts the result of single ``query`` result into a dictionary via the
field specification of ``entity``.
:param sir.schema.searchentities.SearchEntity entity:
:param obj: A :ref:`declarative <sqla:declarative_toplevel>` object.
"""
data = {}
for field in entity.fields:
fieldname = field.name
tempvals = set()
for path in field.paths:
for val in querying._iterate_path_values(path, obj):
tempvals.add(val)
if len(tempvals) == 1:
tempvals = tempvals.pop()
if field.transformfunc is not None:
tempvals = field.transformfunc(tempvals)
data[fieldname] = tempvals
return data
<commit_msg>Fix a link in index_entity's docstring<commit_after>from . import querying
from logging import getLogger
logger = getLogger("sir")
def index_entity(solr_connection, query, search_entity):
"""
Indexes a single entity type.
:param solr.Solr solr_connection:
:param sqlalchemy.orm.query.Query query:
:param sir.schema.searchentities.SearchEntity search_entity:
"""
for row in query:
data = query_result_to_dict(search_entity, row)
logger.info("Sending a document to solr: %s", data)
solr_connection.add(data)
def query_result_to_dict(entity, obj):
"""
Converts the result of single ``query`` result into a dictionary via the
field specification of ``entity``.
:param sir.schema.searchentities.SearchEntity entity:
:param obj: A :ref:`declarative <sqla:declarative_toplevel>` object.
"""
data = {}
for field in entity.fields:
fieldname = field.name
tempvals = set()
for path in field.paths:
for val in querying._iterate_path_values(path, obj):
tempvals.add(val)
if len(tempvals) == 1:
tempvals = tempvals.pop()
if field.transformfunc is not None:
tempvals = field.transformfunc(tempvals)
data[fieldname] = tempvals
return data
|
5c435749b043f0605e9d1b5279a5a8fd4a5a1c25 | pyfolio/tests/test_nbs.py | pyfolio/tests/test_nbs.py | #!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current import read
from pyfolio.utils import pyfolio_root
def test_nbs():
path = os.path.join(pyfolio_root(), 'examples', '*.ipynb')
for ipynb in glob.glob(path):
with open(ipynb) as f:
nb = read(f, 'json')
nb_runner = NotebookRunner(nb)
nb_runner.run_notebook(skip_exceptions=False)
| #!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current import read
from pyfolio.utils import pyfolio_root
def test_nbs():
path = os.path.join(pyfolio_root(), 'examples', '*.ipynb')
for ipynb in glob.glob(path):
# See if bayesian is useable before we run a test
if ipynb.endswith('bayesian.ipynb'):
try:
import pyfolio.bayesian # NOQA
except:
continue
with open(ipynb) as f:
nb = read(f, 'json')
nb_runner = NotebookRunner(nb)
nb_runner.run_notebook(skip_exceptions=False)
| Make nb_tests for bayesian optional because PyMC3 is not a hard dependency | TST: Make nb_tests for bayesian optional because PyMC3 is not a hard dependency
| Python | apache-2.0 | ChinaQuants/pyfolio,chayapan/pyfolio,ChinaQuants/pyfolio,quantopian/pyfolio,YihaoLu/pyfolio,quantopian/pyfolio,femtotrader/pyfolio,femtotrader/pyfolio,YihaoLu/pyfolio | #!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current import read
from pyfolio.utils import pyfolio_root
def test_nbs():
path = os.path.join(pyfolio_root(), 'examples', '*.ipynb')
for ipynb in glob.glob(path):
with open(ipynb) as f:
nb = read(f, 'json')
nb_runner = NotebookRunner(nb)
nb_runner.run_notebook(skip_exceptions=False)
TST: Make nb_tests for bayesian optional because PyMC3 is not a hard dependency | #!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current import read
from pyfolio.utils import pyfolio_root
def test_nbs():
path = os.path.join(pyfolio_root(), 'examples', '*.ipynb')
for ipynb in glob.glob(path):
# See if bayesian is useable before we run a test
if ipynb.endswith('bayesian.ipynb'):
try:
import pyfolio.bayesian # NOQA
except:
continue
with open(ipynb) as f:
nb = read(f, 'json')
nb_runner = NotebookRunner(nb)
nb_runner.run_notebook(skip_exceptions=False)
| <commit_before>#!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current import read
from pyfolio.utils import pyfolio_root
def test_nbs():
path = os.path.join(pyfolio_root(), 'examples', '*.ipynb')
for ipynb in glob.glob(path):
with open(ipynb) as f:
nb = read(f, 'json')
nb_runner = NotebookRunner(nb)
nb_runner.run_notebook(skip_exceptions=False)
<commit_msg>TST: Make nb_tests for bayesian optional because PyMC3 is not a hard dependency<commit_after> | #!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current import read
from pyfolio.utils import pyfolio_root
def test_nbs():
path = os.path.join(pyfolio_root(), 'examples', '*.ipynb')
for ipynb in glob.glob(path):
# See if bayesian is useable before we run a test
if ipynb.endswith('bayesian.ipynb'):
try:
import pyfolio.bayesian # NOQA
except:
continue
with open(ipynb) as f:
nb = read(f, 'json')
nb_runner = NotebookRunner(nb)
nb_runner.run_notebook(skip_exceptions=False)
| #!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current import read
from pyfolio.utils import pyfolio_root
def test_nbs():
path = os.path.join(pyfolio_root(), 'examples', '*.ipynb')
for ipynb in glob.glob(path):
with open(ipynb) as f:
nb = read(f, 'json')
nb_runner = NotebookRunner(nb)
nb_runner.run_notebook(skip_exceptions=False)
TST: Make nb_tests for bayesian optional because PyMC3 is not a hard dependency#!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current import read
from pyfolio.utils import pyfolio_root
def test_nbs():
path = os.path.join(pyfolio_root(), 'examples', '*.ipynb')
for ipynb in glob.glob(path):
# See if bayesian is useable before we run a test
if ipynb.endswith('bayesian.ipynb'):
try:
import pyfolio.bayesian # NOQA
except:
continue
with open(ipynb) as f:
nb = read(f, 'json')
nb_runner = NotebookRunner(nb)
nb_runner.run_notebook(skip_exceptions=False)
| <commit_before>#!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current import read
from pyfolio.utils import pyfolio_root
def test_nbs():
path = os.path.join(pyfolio_root(), 'examples', '*.ipynb')
for ipynb in glob.glob(path):
with open(ipynb) as f:
nb = read(f, 'json')
nb_runner = NotebookRunner(nb)
nb_runner.run_notebook(skip_exceptions=False)
<commit_msg>TST: Make nb_tests for bayesian optional because PyMC3 is not a hard dependency<commit_after>#!/usr/bin/env python
"""
simple example script for running notebooks and reporting exceptions.
Usage: `checkipnb.py foo.ipynb [bar.ipynb [...]]`
Each cell is submitted to the kernel, and checked for errors.
"""
import os
import glob
from runipy.notebook_runner import NotebookRunner
from IPython.nbformat.current import read
from pyfolio.utils import pyfolio_root
def test_nbs():
path = os.path.join(pyfolio_root(), 'examples', '*.ipynb')
for ipynb in glob.glob(path):
# See if bayesian is useable before we run a test
if ipynb.endswith('bayesian.ipynb'):
try:
import pyfolio.bayesian # NOQA
except:
continue
with open(ipynb) as f:
nb = read(f, 'json')
nb_runner = NotebookRunner(nb)
nb_runner.run_notebook(skip_exceptions=False)
|
572feef82f113e25b480ea8428f36ca0f7510fc3 | getwords.py | getwords.py | from subprocess import getoutput
from random import randrange
from filelock import FileLock
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(DICT_PATH):
with open(DICT_PATH, 'w') as f:
f.write(out)
f.close()
def getwords():
with open(DICT_PATH, 'r') as f:
f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR)))
out = f.readlines(OOPS_SEEK_TOO_FAR)
out = [x.replace('\n', '') for x in out]
return '_'.join(out[1:4])
if __name__ == '__main__':
while True:
print(getwords())
| from subprocess import getoutput
from random import randrange
from filelock import FileLock
LOCK_PATH = '/tmp/ifixit_dict.lock'
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(LOCK_PATH):
with open(DICT_PATH, 'w') as f:
f.write(out)
f.close()
def getwords():
with open(DICT_PATH, 'r') as f:
f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR)))
out = f.readlines(OOPS_SEEK_TOO_FAR)
out = [x.replace('\n', '') for x in out]
return '_'.join(out[1:4])
if __name__ == '__main__':
while True:
print(getwords())
| Use a separate lock path | Use a separate lock path
| Python | mit | DeltaHeavy/wrath-ctf-framework,DeltaHeavy/wrath-ctf-framework,WhiteHatCP/wrath-ctf-framework,DeltaHeavy/wrath-ctf-framework,DeltaHeavy/wrath-ctf-framework,WhiteHatCP/wrath-ctf-framework,WhiteHatCP/wrath-ctf-framework,WhiteHatCP/wrath-ctf-framework | from subprocess import getoutput
from random import randrange
from filelock import FileLock
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(DICT_PATH):
with open(DICT_PATH, 'w') as f:
f.write(out)
f.close()
def getwords():
with open(DICT_PATH, 'r') as f:
f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR)))
out = f.readlines(OOPS_SEEK_TOO_FAR)
out = [x.replace('\n', '') for x in out]
return '_'.join(out[1:4])
if __name__ == '__main__':
while True:
print(getwords())
Use a separate lock path | from subprocess import getoutput
from random import randrange
from filelock import FileLock
LOCK_PATH = '/tmp/ifixit_dict.lock'
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(LOCK_PATH):
with open(DICT_PATH, 'w') as f:
f.write(out)
f.close()
def getwords():
with open(DICT_PATH, 'r') as f:
f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR)))
out = f.readlines(OOPS_SEEK_TOO_FAR)
out = [x.replace('\n', '') for x in out]
return '_'.join(out[1:4])
if __name__ == '__main__':
while True:
print(getwords())
| <commit_before>from subprocess import getoutput
from random import randrange
from filelock import FileLock
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(DICT_PATH):
with open(DICT_PATH, 'w') as f:
f.write(out)
f.close()
def getwords():
with open(DICT_PATH, 'r') as f:
f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR)))
out = f.readlines(OOPS_SEEK_TOO_FAR)
out = [x.replace('\n', '') for x in out]
return '_'.join(out[1:4])
if __name__ == '__main__':
while True:
print(getwords())
<commit_msg>Use a separate lock path<commit_after> | from subprocess import getoutput
from random import randrange
from filelock import FileLock
LOCK_PATH = '/tmp/ifixit_dict.lock'
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(LOCK_PATH):
with open(DICT_PATH, 'w') as f:
f.write(out)
f.close()
def getwords():
with open(DICT_PATH, 'r') as f:
f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR)))
out = f.readlines(OOPS_SEEK_TOO_FAR)
out = [x.replace('\n', '') for x in out]
return '_'.join(out[1:4])
if __name__ == '__main__':
while True:
print(getwords())
| from subprocess import getoutput
from random import randrange
from filelock import FileLock
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(DICT_PATH):
with open(DICT_PATH, 'w') as f:
f.write(out)
f.close()
def getwords():
with open(DICT_PATH, 'r') as f:
f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR)))
out = f.readlines(OOPS_SEEK_TOO_FAR)
out = [x.replace('\n', '') for x in out]
return '_'.join(out[1:4])
if __name__ == '__main__':
while True:
print(getwords())
Use a separate lock pathfrom subprocess import getoutput
from random import randrange
from filelock import FileLock
LOCK_PATH = '/tmp/ifixit_dict.lock'
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(LOCK_PATH):
with open(DICT_PATH, 'w') as f:
f.write(out)
f.close()
def getwords():
with open(DICT_PATH, 'r') as f:
f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR)))
out = f.readlines(OOPS_SEEK_TOO_FAR)
out = [x.replace('\n', '') for x in out]
return '_'.join(out[1:4])
if __name__ == '__main__':
while True:
print(getwords())
| <commit_before>from subprocess import getoutput
from random import randrange
from filelock import FileLock
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(DICT_PATH):
with open(DICT_PATH, 'w') as f:
f.write(out)
f.close()
def getwords():
with open(DICT_PATH, 'r') as f:
f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR)))
out = f.readlines(OOPS_SEEK_TOO_FAR)
out = [x.replace('\n', '') for x in out]
return '_'.join(out[1:4])
if __name__ == '__main__':
while True:
print(getwords())
<commit_msg>Use a separate lock path<commit_after>from subprocess import getoutput
from random import randrange
from filelock import FileLock
LOCK_PATH = '/tmp/ifixit_dict.lock'
DICT_PATH = './dict.txt'
OOPS_SEEK_TOO_FAR = 48
DICT_LENGTH = 61973
# don't run on OS X
def randomize():
out = getoutput('sort -R ' + DICT_PATH)
with FileLock(LOCK_PATH):
with open(DICT_PATH, 'w') as f:
f.write(out)
f.close()
def getwords():
with open(DICT_PATH, 'r') as f:
f.seek(randrange(0, int(DICT_LENGTH-OOPS_SEEK_TOO_FAR)))
out = f.readlines(OOPS_SEEK_TOO_FAR)
out = [x.replace('\n', '') for x in out]
return '_'.join(out[1:4])
if __name__ == '__main__':
while True:
print(getwords())
|
893f1724321fd9d4b25e6ddaac5749bdadecbabd | python_apps/pypo/setup.py | python_apps/pypo/setup.py | import os
from setuptools import setup
# Change directory since setuptools uses relative paths
os.chdir(os.path.dirname(os.path.realpath(__file__)))
setup(
name="airtime-playout",
version="1.0",
description="LibreTime Playout",
author="LibreTime Contributors",
url="https://github.com/libretime/libretime",
project_urls={
"Bug Tracker": "https://github.com/libretime/libretime/issues",
"Documentation": "https://libretime.org",
"Source Code": "https://github.com/libretime/libretime",
},
license="AGPLv3",
packages=[
"pypo",
"liquidsoap",
],
package_data={"": ["**/*.liq", "*.cfg", "*.types"]},
scripts=[
"bin/airtime-playout",
"bin/airtime-liquidsoap",
"bin/pyponotify",
],
python_requires=">=3.6",
install_requires=[
"amqplib",
"configobj",
"defusedxml",
"kombu",
"mutagen",
"packaging",
"pytz",
"requests",
],
zip_safe=False,
)
| from os import chdir
from pathlib import Path
from setuptools import setup
# Change directory since setuptools uses relative paths
here = Path(__file__).parent
chdir(here)
setup(
name="airtime-playout",
version="1.0",
description="LibreTime Playout",
author="LibreTime Contributors",
url="https://github.com/libretime/libretime",
project_urls={
"Bug Tracker": "https://github.com/libretime/libretime/issues",
"Documentation": "https://libretime.org",
"Source Code": "https://github.com/libretime/libretime",
},
license="AGPLv3",
packages=[
"pypo",
"liquidsoap",
],
package_data={"": ["**/*.liq", "*.cfg", "*.types"]},
scripts=[
"bin/airtime-playout",
"bin/airtime-liquidsoap",
"bin/pyponotify",
],
python_requires=">=3.6",
install_requires=[
f"api_clients @ file://localhost/{here.parent}/api_clients#egg=api_clients",
"amqplib",
"configobj",
"defusedxml",
"kombu",
"mutagen",
"packaging",
"pytz",
"requests",
],
zip_safe=False,
)
| Add local api_client dependency to playout | Add local api_client dependency to playout
| Python | agpl-3.0 | LibreTime/libretime,LibreTime/libretime,LibreTime/libretime,LibreTime/libretime,LibreTime/libretime,LibreTime/libretime | import os
from setuptools import setup
# Change directory since setuptools uses relative paths
os.chdir(os.path.dirname(os.path.realpath(__file__)))
setup(
name="airtime-playout",
version="1.0",
description="LibreTime Playout",
author="LibreTime Contributors",
url="https://github.com/libretime/libretime",
project_urls={
"Bug Tracker": "https://github.com/libretime/libretime/issues",
"Documentation": "https://libretime.org",
"Source Code": "https://github.com/libretime/libretime",
},
license="AGPLv3",
packages=[
"pypo",
"liquidsoap",
],
package_data={"": ["**/*.liq", "*.cfg", "*.types"]},
scripts=[
"bin/airtime-playout",
"bin/airtime-liquidsoap",
"bin/pyponotify",
],
python_requires=">=3.6",
install_requires=[
"amqplib",
"configobj",
"defusedxml",
"kombu",
"mutagen",
"packaging",
"pytz",
"requests",
],
zip_safe=False,
)
Add local api_client dependency to playout | from os import chdir
from pathlib import Path
from setuptools import setup
# Change directory since setuptools uses relative paths
here = Path(__file__).parent
chdir(here)
setup(
name="airtime-playout",
version="1.0",
description="LibreTime Playout",
author="LibreTime Contributors",
url="https://github.com/libretime/libretime",
project_urls={
"Bug Tracker": "https://github.com/libretime/libretime/issues",
"Documentation": "https://libretime.org",
"Source Code": "https://github.com/libretime/libretime",
},
license="AGPLv3",
packages=[
"pypo",
"liquidsoap",
],
package_data={"": ["**/*.liq", "*.cfg", "*.types"]},
scripts=[
"bin/airtime-playout",
"bin/airtime-liquidsoap",
"bin/pyponotify",
],
python_requires=">=3.6",
install_requires=[
f"api_clients @ file://localhost/{here.parent}/api_clients#egg=api_clients",
"amqplib",
"configobj",
"defusedxml",
"kombu",
"mutagen",
"packaging",
"pytz",
"requests",
],
zip_safe=False,
)
| <commit_before>import os
from setuptools import setup
# Change directory since setuptools uses relative paths
os.chdir(os.path.dirname(os.path.realpath(__file__)))
setup(
name="airtime-playout",
version="1.0",
description="LibreTime Playout",
author="LibreTime Contributors",
url="https://github.com/libretime/libretime",
project_urls={
"Bug Tracker": "https://github.com/libretime/libretime/issues",
"Documentation": "https://libretime.org",
"Source Code": "https://github.com/libretime/libretime",
},
license="AGPLv3",
packages=[
"pypo",
"liquidsoap",
],
package_data={"": ["**/*.liq", "*.cfg", "*.types"]},
scripts=[
"bin/airtime-playout",
"bin/airtime-liquidsoap",
"bin/pyponotify",
],
python_requires=">=3.6",
install_requires=[
"amqplib",
"configobj",
"defusedxml",
"kombu",
"mutagen",
"packaging",
"pytz",
"requests",
],
zip_safe=False,
)
<commit_msg>Add local api_client dependency to playout<commit_after> | from os import chdir
from pathlib import Path
from setuptools import setup
# Change directory since setuptools uses relative paths
here = Path(__file__).parent
chdir(here)
setup(
name="airtime-playout",
version="1.0",
description="LibreTime Playout",
author="LibreTime Contributors",
url="https://github.com/libretime/libretime",
project_urls={
"Bug Tracker": "https://github.com/libretime/libretime/issues",
"Documentation": "https://libretime.org",
"Source Code": "https://github.com/libretime/libretime",
},
license="AGPLv3",
packages=[
"pypo",
"liquidsoap",
],
package_data={"": ["**/*.liq", "*.cfg", "*.types"]},
scripts=[
"bin/airtime-playout",
"bin/airtime-liquidsoap",
"bin/pyponotify",
],
python_requires=">=3.6",
install_requires=[
f"api_clients @ file://localhost/{here.parent}/api_clients#egg=api_clients",
"amqplib",
"configobj",
"defusedxml",
"kombu",
"mutagen",
"packaging",
"pytz",
"requests",
],
zip_safe=False,
)
| import os
from setuptools import setup
# Change directory since setuptools uses relative paths
os.chdir(os.path.dirname(os.path.realpath(__file__)))
setup(
name="airtime-playout",
version="1.0",
description="LibreTime Playout",
author="LibreTime Contributors",
url="https://github.com/libretime/libretime",
project_urls={
"Bug Tracker": "https://github.com/libretime/libretime/issues",
"Documentation": "https://libretime.org",
"Source Code": "https://github.com/libretime/libretime",
},
license="AGPLv3",
packages=[
"pypo",
"liquidsoap",
],
package_data={"": ["**/*.liq", "*.cfg", "*.types"]},
scripts=[
"bin/airtime-playout",
"bin/airtime-liquidsoap",
"bin/pyponotify",
],
python_requires=">=3.6",
install_requires=[
"amqplib",
"configobj",
"defusedxml",
"kombu",
"mutagen",
"packaging",
"pytz",
"requests",
],
zip_safe=False,
)
Add local api_client dependency to playoutfrom os import chdir
from pathlib import Path
from setuptools import setup
# Change directory since setuptools uses relative paths
here = Path(__file__).parent
chdir(here)
setup(
name="airtime-playout",
version="1.0",
description="LibreTime Playout",
author="LibreTime Contributors",
url="https://github.com/libretime/libretime",
project_urls={
"Bug Tracker": "https://github.com/libretime/libretime/issues",
"Documentation": "https://libretime.org",
"Source Code": "https://github.com/libretime/libretime",
},
license="AGPLv3",
packages=[
"pypo",
"liquidsoap",
],
package_data={"": ["**/*.liq", "*.cfg", "*.types"]},
scripts=[
"bin/airtime-playout",
"bin/airtime-liquidsoap",
"bin/pyponotify",
],
python_requires=">=3.6",
install_requires=[
f"api_clients @ file://localhost/{here.parent}/api_clients#egg=api_clients",
"amqplib",
"configobj",
"defusedxml",
"kombu",
"mutagen",
"packaging",
"pytz",
"requests",
],
zip_safe=False,
)
| <commit_before>import os
from setuptools import setup
# Change directory since setuptools uses relative paths
os.chdir(os.path.dirname(os.path.realpath(__file__)))
setup(
name="airtime-playout",
version="1.0",
description="LibreTime Playout",
author="LibreTime Contributors",
url="https://github.com/libretime/libretime",
project_urls={
"Bug Tracker": "https://github.com/libretime/libretime/issues",
"Documentation": "https://libretime.org",
"Source Code": "https://github.com/libretime/libretime",
},
license="AGPLv3",
packages=[
"pypo",
"liquidsoap",
],
package_data={"": ["**/*.liq", "*.cfg", "*.types"]},
scripts=[
"bin/airtime-playout",
"bin/airtime-liquidsoap",
"bin/pyponotify",
],
python_requires=">=3.6",
install_requires=[
"amqplib",
"configobj",
"defusedxml",
"kombu",
"mutagen",
"packaging",
"pytz",
"requests",
],
zip_safe=False,
)
<commit_msg>Add local api_client dependency to playout<commit_after>from os import chdir
from pathlib import Path
from setuptools import setup
# Change directory since setuptools uses relative paths
here = Path(__file__).parent
chdir(here)
setup(
name="airtime-playout",
version="1.0",
description="LibreTime Playout",
author="LibreTime Contributors",
url="https://github.com/libretime/libretime",
project_urls={
"Bug Tracker": "https://github.com/libretime/libretime/issues",
"Documentation": "https://libretime.org",
"Source Code": "https://github.com/libretime/libretime",
},
license="AGPLv3",
packages=[
"pypo",
"liquidsoap",
],
package_data={"": ["**/*.liq", "*.cfg", "*.types"]},
scripts=[
"bin/airtime-playout",
"bin/airtime-liquidsoap",
"bin/pyponotify",
],
python_requires=">=3.6",
install_requires=[
f"api_clients @ file://localhost/{here.parent}/api_clients#egg=api_clients",
"amqplib",
"configobj",
"defusedxml",
"kombu",
"mutagen",
"packaging",
"pytz",
"requests",
],
zip_safe=False,
)
|
b776a05c8bb57d63259263c985883422f56298c7 | pyvac/helpers/calendar.py | pyvac/helpers/calendar.py | import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""
client = caldav.DAVClient(url)
principal = client.principal()
calendars = principal.calendars()
if not len(calendars):
return False
vcal_entry = vcal_entry % (summary,
date_from.strftime('%Y%m%d'),
(date_end + relativedelta(days=1)).strftime('%Y%m%d'))
calendar = calendars[0]
log.info('Using calendar %r' % calendar)
log.info('Using entry: %s' % vcal_entry)
event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
log.info('Event %s created' % event)
url_obj = event.url
return str(url_obj)
def delFromCal(url, ics):
""" Delete entry in calendar"""
if not url:
return False
client = caldav.DAVClient(url)
log.info('Deleting entry %r' % ics)
client.delete(ics)
return True
| import urllib
import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""
client = caldav.DAVClient(url)
principal = client.principal()
calendars = principal.calendars()
if not len(calendars):
return False
vcal_entry = vcal_entry % (summary,
date_from.strftime('%Y%m%d'),
(date_end + relativedelta(days=1)).strftime('%Y%m%d'))
calendar = calendars[0]
log.info('Using calendar %r' % calendar)
log.info('Using entry: %s' % vcal_entry)
event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
log.info('Event %s created' % event)
url_obj = event.url
url_obj = urllib.quote(url_obj, safe='/:')
return str(url_obj)
def delFromCal(url, ics):
""" Delete entry in calendar"""
if not url:
return False
client = caldav.DAVClient(url)
log.info('Deleting entry %r' % ics)
client.delete(ics)
return True
| Fix bug with ics url format with latest vobject version | Fix bug with ics url format with latest vobject version
| Python | bsd-3-clause | sayoun/pyvac,sayoun/pyvac,sayoun/pyvac | import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""
client = caldav.DAVClient(url)
principal = client.principal()
calendars = principal.calendars()
if not len(calendars):
return False
vcal_entry = vcal_entry % (summary,
date_from.strftime('%Y%m%d'),
(date_end + relativedelta(days=1)).strftime('%Y%m%d'))
calendar = calendars[0]
log.info('Using calendar %r' % calendar)
log.info('Using entry: %s' % vcal_entry)
event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
log.info('Event %s created' % event)
url_obj = event.url
return str(url_obj)
def delFromCal(url, ics):
""" Delete entry in calendar"""
if not url:
return False
client = caldav.DAVClient(url)
log.info('Deleting entry %r' % ics)
client.delete(ics)
return True
Fix bug with ics url format with latest vobject version | import urllib
import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""
client = caldav.DAVClient(url)
principal = client.principal()
calendars = principal.calendars()
if not len(calendars):
return False
vcal_entry = vcal_entry % (summary,
date_from.strftime('%Y%m%d'),
(date_end + relativedelta(days=1)).strftime('%Y%m%d'))
calendar = calendars[0]
log.info('Using calendar %r' % calendar)
log.info('Using entry: %s' % vcal_entry)
event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
log.info('Event %s created' % event)
url_obj = event.url
url_obj = urllib.quote(url_obj, safe='/:')
return str(url_obj)
def delFromCal(url, ics):
""" Delete entry in calendar"""
if not url:
return False
client = caldav.DAVClient(url)
log.info('Deleting entry %r' % ics)
client.delete(ics)
return True
| <commit_before>import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""
client = caldav.DAVClient(url)
principal = client.principal()
calendars = principal.calendars()
if not len(calendars):
return False
vcal_entry = vcal_entry % (summary,
date_from.strftime('%Y%m%d'),
(date_end + relativedelta(days=1)).strftime('%Y%m%d'))
calendar = calendars[0]
log.info('Using calendar %r' % calendar)
log.info('Using entry: %s' % vcal_entry)
event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
log.info('Event %s created' % event)
url_obj = event.url
return str(url_obj)
def delFromCal(url, ics):
""" Delete entry in calendar"""
if not url:
return False
client = caldav.DAVClient(url)
log.info('Deleting entry %r' % ics)
client.delete(ics)
return True
<commit_msg>Fix bug with ics url format with latest vobject version<commit_after> | import urllib
import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""
client = caldav.DAVClient(url)
principal = client.principal()
calendars = principal.calendars()
if not len(calendars):
return False
vcal_entry = vcal_entry % (summary,
date_from.strftime('%Y%m%d'),
(date_end + relativedelta(days=1)).strftime('%Y%m%d'))
calendar = calendars[0]
log.info('Using calendar %r' % calendar)
log.info('Using entry: %s' % vcal_entry)
event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
log.info('Event %s created' % event)
url_obj = event.url
url_obj = urllib.quote(url_obj, safe='/:')
return str(url_obj)
def delFromCal(url, ics):
""" Delete entry in calendar"""
if not url:
return False
client = caldav.DAVClient(url)
log.info('Deleting entry %r' % ics)
client.delete(ics)
return True
| import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""
client = caldav.DAVClient(url)
principal = client.principal()
calendars = principal.calendars()
if not len(calendars):
return False
vcal_entry = vcal_entry % (summary,
date_from.strftime('%Y%m%d'),
(date_end + relativedelta(days=1)).strftime('%Y%m%d'))
calendar = calendars[0]
log.info('Using calendar %r' % calendar)
log.info('Using entry: %s' % vcal_entry)
event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
log.info('Event %s created' % event)
url_obj = event.url
return str(url_obj)
def delFromCal(url, ics):
""" Delete entry in calendar"""
if not url:
return False
client = caldav.DAVClient(url)
log.info('Deleting entry %r' % ics)
client.delete(ics)
return True
Fix bug with ics url format with latest vobject versionimport urllib
import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""
client = caldav.DAVClient(url)
principal = client.principal()
calendars = principal.calendars()
if not len(calendars):
return False
vcal_entry = vcal_entry % (summary,
date_from.strftime('%Y%m%d'),
(date_end + relativedelta(days=1)).strftime('%Y%m%d'))
calendar = calendars[0]
log.info('Using calendar %r' % calendar)
log.info('Using entry: %s' % vcal_entry)
event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
log.info('Event %s created' % event)
url_obj = event.url
url_obj = urllib.quote(url_obj, safe='/:')
return str(url_obj)
def delFromCal(url, ics):
""" Delete entry in calendar"""
if not url:
return False
client = caldav.DAVClient(url)
log.info('Deleting entry %r' % ics)
client.delete(ics)
return True
| <commit_before>import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""
client = caldav.DAVClient(url)
principal = client.principal()
calendars = principal.calendars()
if not len(calendars):
return False
vcal_entry = vcal_entry % (summary,
date_from.strftime('%Y%m%d'),
(date_end + relativedelta(days=1)).strftime('%Y%m%d'))
calendar = calendars[0]
log.info('Using calendar %r' % calendar)
log.info('Using entry: %s' % vcal_entry)
event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
log.info('Event %s created' % event)
url_obj = event.url
return str(url_obj)
def delFromCal(url, ics):
""" Delete entry in calendar"""
if not url:
return False
client = caldav.DAVClient(url)
log.info('Deleting entry %r' % ics)
client.delete(ics)
return True
<commit_msg>Fix bug with ics url format with latest vobject version<commit_after>import urllib
import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""
client = caldav.DAVClient(url)
principal = client.principal()
calendars = principal.calendars()
if not len(calendars):
return False
vcal_entry = vcal_entry % (summary,
date_from.strftime('%Y%m%d'),
(date_end + relativedelta(days=1)).strftime('%Y%m%d'))
calendar = calendars[0]
log.info('Using calendar %r' % calendar)
log.info('Using entry: %s' % vcal_entry)
event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
log.info('Event %s created' % event)
url_obj = event.url
url_obj = urllib.quote(url_obj, safe='/:')
return str(url_obj)
def delFromCal(url, ics):
""" Delete entry in calendar"""
if not url:
return False
client = caldav.DAVClient(url)
log.info('Deleting entry %r' % ics)
client.delete(ics)
return True
|
a5cd7e2bea66003c1223891853077e47df24b7cf | vx_intro.py | vx_intro.py | import vx
import math
from sys import argv
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tick_function
vx.files = argv[1:]
import utils
import scheduler
import keybindings
import windows
import prompt
def _default_start():
if len(vx.files) == 0:
win = vx.window(vx.rows, vx.cols, 0, 0)
win.blank()
win.focus()
else:
d = math.floor(vx.rows / (len(vx.files)))
y = 0
for f in vx.files:
win = vx.window(d, vx.cols, y, 0)
win.attach_file(f)
y += d
win.focus()
vx.default_start = _default_start
| import vx
import math
import os
import sys
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tick_function
vx.files = sys.argv[1:]
import utils
import scheduler
import keybindings
import windows
import prompt
def _default_start():
if len(vx.files) == 0:
win = vx.window(vx.rows, vx.cols, 0, 0)
win.blank()
win.focus()
else:
d = math.floor(vx.rows / (len(vx.files)))
y = 0
for f in vx.files:
win = vx.window(d, vx.cols, y, 0)
win.attach_file(f)
y += d
win.focus()
vx.default_start = _default_start
sys.path.append(os.path.expanduser('~/.python'))
import rc
| Add ~/.python to PYTHONPATH and import rc | Add ~/.python to PYTHONPATH and import rc
| Python | mit | philipdexter/vx,philipdexter/vx | import vx
import math
from sys import argv
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tick_function
vx.files = argv[1:]
import utils
import scheduler
import keybindings
import windows
import prompt
def _default_start():
if len(vx.files) == 0:
win = vx.window(vx.rows, vx.cols, 0, 0)
win.blank()
win.focus()
else:
d = math.floor(vx.rows / (len(vx.files)))
y = 0
for f in vx.files:
win = vx.window(d, vx.cols, y, 0)
win.attach_file(f)
y += d
win.focus()
vx.default_start = _default_start
Add ~/.python to PYTHONPATH and import rc | import vx
import math
import os
import sys
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tick_function
vx.files = sys.argv[1:]
import utils
import scheduler
import keybindings
import windows
import prompt
def _default_start():
if len(vx.files) == 0:
win = vx.window(vx.rows, vx.cols, 0, 0)
win.blank()
win.focus()
else:
d = math.floor(vx.rows / (len(vx.files)))
y = 0
for f in vx.files:
win = vx.window(d, vx.cols, y, 0)
win.attach_file(f)
y += d
win.focus()
vx.default_start = _default_start
sys.path.append(os.path.expanduser('~/.python'))
import rc
| <commit_before>import vx
import math
from sys import argv
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tick_function
vx.files = argv[1:]
import utils
import scheduler
import keybindings
import windows
import prompt
def _default_start():
if len(vx.files) == 0:
win = vx.window(vx.rows, vx.cols, 0, 0)
win.blank()
win.focus()
else:
d = math.floor(vx.rows / (len(vx.files)))
y = 0
for f in vx.files:
win = vx.window(d, vx.cols, y, 0)
win.attach_file(f)
y += d
win.focus()
vx.default_start = _default_start
<commit_msg>Add ~/.python to PYTHONPATH and import rc<commit_after> | import vx
import math
import os
import sys
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tick_function
vx.files = sys.argv[1:]
import utils
import scheduler
import keybindings
import windows
import prompt
def _default_start():
if len(vx.files) == 0:
win = vx.window(vx.rows, vx.cols, 0, 0)
win.blank()
win.focus()
else:
d = math.floor(vx.rows / (len(vx.files)))
y = 0
for f in vx.files:
win = vx.window(d, vx.cols, y, 0)
win.attach_file(f)
y += d
win.focus()
vx.default_start = _default_start
sys.path.append(os.path.expanduser('~/.python'))
import rc
| import vx
import math
from sys import argv
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tick_function
vx.files = argv[1:]
import utils
import scheduler
import keybindings
import windows
import prompt
def _default_start():
if len(vx.files) == 0:
win = vx.window(vx.rows, vx.cols, 0, 0)
win.blank()
win.focus()
else:
d = math.floor(vx.rows / (len(vx.files)))
y = 0
for f in vx.files:
win = vx.window(d, vx.cols, y, 0)
win.attach_file(f)
y += d
win.focus()
vx.default_start = _default_start
Add ~/.python to PYTHONPATH and import rcimport vx
import math
import os
import sys
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tick_function
vx.files = sys.argv[1:]
import utils
import scheduler
import keybindings
import windows
import prompt
def _default_start():
if len(vx.files) == 0:
win = vx.window(vx.rows, vx.cols, 0, 0)
win.blank()
win.focus()
else:
d = math.floor(vx.rows / (len(vx.files)))
y = 0
for f in vx.files:
win = vx.window(d, vx.cols, y, 0)
win.attach_file(f)
y += d
win.focus()
vx.default_start = _default_start
sys.path.append(os.path.expanduser('~/.python'))
import rc
| <commit_before>import vx
import math
from sys import argv
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tick_function
vx.files = argv[1:]
import utils
import scheduler
import keybindings
import windows
import prompt
def _default_start():
if len(vx.files) == 0:
win = vx.window(vx.rows, vx.cols, 0, 0)
win.blank()
win.focus()
else:
d = math.floor(vx.rows / (len(vx.files)))
y = 0
for f in vx.files:
win = vx.window(d, vx.cols, y, 0)
win.attach_file(f)
y += d
win.focus()
vx.default_start = _default_start
<commit_msg>Add ~/.python to PYTHONPATH and import rc<commit_after>import vx
import math
import os
import sys
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tick_function
vx.files = sys.argv[1:]
import utils
import scheduler
import keybindings
import windows
import prompt
def _default_start():
if len(vx.files) == 0:
win = vx.window(vx.rows, vx.cols, 0, 0)
win.blank()
win.focus()
else:
d = math.floor(vx.rows / (len(vx.files)))
y = 0
for f in vx.files:
win = vx.window(d, vx.cols, y, 0)
win.attach_file(f)
y += d
win.focus()
vx.default_start = _default_start
sys.path.append(os.path.expanduser('~/.python'))
import rc
|
0064ce135507df6ec5d5e3b70240b7483f2f9025 | polygraph/types/tests/test_union.py | polygraph/types/tests/test_union.py | from unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
@skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Union(Int, String))
def test_associativity(self):
self.assertEqual(
Union(Union(String, Int), Float),
Union(String, Int, Float),
)
def test_pipe_operator(self):
self.assertEqual(
String | Int,
Union(String, Int),
)
def test_pipe_operator_with_more_than_two_types(self):
self.assertEqual(
String | Int | Float,
Union(String, Int, Float),
)
class UnionValueTest(TestCase):
def test_valid_type(self):
union = String | Int
self.assertEqual(union(Int(32)), Int(32))
self.assertEqual(union(String("Test")), String("Test"))
def test_value_must_be_typed(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(32)
with self.assertRaises(PolygraphValueError):
union("Test")
def test_value_must_have_right_type(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(Float(32))
| from unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
# @skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Union(Int, String))
self.assertEqual(Union(String, Int, Float), Union(Float, String, Int, String))
@skip
def test_associativity(self):
self.assertEqual(
Union(Union(String, Int), Float),
Union(String, Int, Float),
)
def test_pipe_operator(self):
self.assertEqual(
String | Int,
Union(String, Int),
)
@skip
def test_pipe_operator_with_more_than_two_types(self):
self.assertEqual(
String | Int | Float,
Union(String, Int, Float),
)
class UnionValueTest(TestCase):
def test_valid_type(self):
union = String | Int
self.assertEqual(union(Int(32)), Int(32))
self.assertEqual(union(String("Test")), String("Test"))
def test_value_must_be_typed(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(32)
with self.assertRaises(PolygraphValueError):
union("Test")
def test_value_must_have_right_type(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(Float(32))
| Add failing tests for type equality | Add failing tests for type equality
| Python | mit | polygraph-python/polygraph | from unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
@skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Union(Int, String))
def test_associativity(self):
self.assertEqual(
Union(Union(String, Int), Float),
Union(String, Int, Float),
)
def test_pipe_operator(self):
self.assertEqual(
String | Int,
Union(String, Int),
)
def test_pipe_operator_with_more_than_two_types(self):
self.assertEqual(
String | Int | Float,
Union(String, Int, Float),
)
class UnionValueTest(TestCase):
def test_valid_type(self):
union = String | Int
self.assertEqual(union(Int(32)), Int(32))
self.assertEqual(union(String("Test")), String("Test"))
def test_value_must_be_typed(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(32)
with self.assertRaises(PolygraphValueError):
union("Test")
def test_value_must_have_right_type(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(Float(32))
Add failing tests for type equality | from unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
# @skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Union(Int, String))
self.assertEqual(Union(String, Int, Float), Union(Float, String, Int, String))
@skip
def test_associativity(self):
self.assertEqual(
Union(Union(String, Int), Float),
Union(String, Int, Float),
)
def test_pipe_operator(self):
self.assertEqual(
String | Int,
Union(String, Int),
)
@skip
def test_pipe_operator_with_more_than_two_types(self):
self.assertEqual(
String | Int | Float,
Union(String, Int, Float),
)
class UnionValueTest(TestCase):
def test_valid_type(self):
union = String | Int
self.assertEqual(union(Int(32)), Int(32))
self.assertEqual(union(String("Test")), String("Test"))
def test_value_must_be_typed(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(32)
with self.assertRaises(PolygraphValueError):
union("Test")
def test_value_must_have_right_type(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(Float(32))
| <commit_before>from unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
@skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Union(Int, String))
def test_associativity(self):
self.assertEqual(
Union(Union(String, Int), Float),
Union(String, Int, Float),
)
def test_pipe_operator(self):
self.assertEqual(
String | Int,
Union(String, Int),
)
def test_pipe_operator_with_more_than_two_types(self):
self.assertEqual(
String | Int | Float,
Union(String, Int, Float),
)
class UnionValueTest(TestCase):
def test_valid_type(self):
union = String | Int
self.assertEqual(union(Int(32)), Int(32))
self.assertEqual(union(String("Test")), String("Test"))
def test_value_must_be_typed(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(32)
with self.assertRaises(PolygraphValueError):
union("Test")
def test_value_must_have_right_type(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(Float(32))
<commit_msg>Add failing tests for type equality<commit_after> | from unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
# @skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Union(Int, String))
self.assertEqual(Union(String, Int, Float), Union(Float, String, Int, String))
@skip
def test_associativity(self):
self.assertEqual(
Union(Union(String, Int), Float),
Union(String, Int, Float),
)
def test_pipe_operator(self):
self.assertEqual(
String | Int,
Union(String, Int),
)
@skip
def test_pipe_operator_with_more_than_two_types(self):
self.assertEqual(
String | Int | Float,
Union(String, Int, Float),
)
class UnionValueTest(TestCase):
def test_valid_type(self):
union = String | Int
self.assertEqual(union(Int(32)), Int(32))
self.assertEqual(union(String("Test")), String("Test"))
def test_value_must_be_typed(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(32)
with self.assertRaises(PolygraphValueError):
union("Test")
def test_value_must_have_right_type(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(Float(32))
| from unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
@skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Union(Int, String))
def test_associativity(self):
self.assertEqual(
Union(Union(String, Int), Float),
Union(String, Int, Float),
)
def test_pipe_operator(self):
self.assertEqual(
String | Int,
Union(String, Int),
)
def test_pipe_operator_with_more_than_two_types(self):
self.assertEqual(
String | Int | Float,
Union(String, Int, Float),
)
class UnionValueTest(TestCase):
def test_valid_type(self):
union = String | Int
self.assertEqual(union(Int(32)), Int(32))
self.assertEqual(union(String("Test")), String("Test"))
def test_value_must_be_typed(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(32)
with self.assertRaises(PolygraphValueError):
union("Test")
def test_value_must_have_right_type(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(Float(32))
Add failing tests for type equalityfrom unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
# @skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Union(Int, String))
self.assertEqual(Union(String, Int, Float), Union(Float, String, Int, String))
@skip
def test_associativity(self):
self.assertEqual(
Union(Union(String, Int), Float),
Union(String, Int, Float),
)
def test_pipe_operator(self):
self.assertEqual(
String | Int,
Union(String, Int),
)
@skip
def test_pipe_operator_with_more_than_two_types(self):
self.assertEqual(
String | Int | Float,
Union(String, Int, Float),
)
class UnionValueTest(TestCase):
def test_valid_type(self):
union = String | Int
self.assertEqual(union(Int(32)), Int(32))
self.assertEqual(union(String("Test")), String("Test"))
def test_value_must_be_typed(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(32)
with self.assertRaises(PolygraphValueError):
union("Test")
def test_value_must_have_right_type(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(Float(32))
| <commit_before>from unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
@skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Union(Int, String))
def test_associativity(self):
self.assertEqual(
Union(Union(String, Int), Float),
Union(String, Int, Float),
)
def test_pipe_operator(self):
self.assertEqual(
String | Int,
Union(String, Int),
)
def test_pipe_operator_with_more_than_two_types(self):
self.assertEqual(
String | Int | Float,
Union(String, Int, Float),
)
class UnionValueTest(TestCase):
def test_valid_type(self):
union = String | Int
self.assertEqual(union(Int(32)), Int(32))
self.assertEqual(union(String("Test")), String("Test"))
def test_value_must_be_typed(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(32)
with self.assertRaises(PolygraphValueError):
union("Test")
def test_value_must_have_right_type(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(Float(32))
<commit_msg>Add failing tests for type equality<commit_after>from unittest import TestCase, skip
from polygraph.exceptions import PolygraphValueError
from polygraph.types.basic_type import Union
from polygraph.types.scalar import Float, Int, String
# @skip # FIXME
class UnionTypeTest(TestCase):
def test_commutativity(self):
self.assertEqual(Union(String, Int), Union(Int, String))
self.assertEqual(Union(String, Int, Float), Union(Float, String, Int, String))
@skip
def test_associativity(self):
self.assertEqual(
Union(Union(String, Int), Float),
Union(String, Int, Float),
)
def test_pipe_operator(self):
self.assertEqual(
String | Int,
Union(String, Int),
)
@skip
def test_pipe_operator_with_more_than_two_types(self):
self.assertEqual(
String | Int | Float,
Union(String, Int, Float),
)
class UnionValueTest(TestCase):
def test_valid_type(self):
union = String | Int
self.assertEqual(union(Int(32)), Int(32))
self.assertEqual(union(String("Test")), String("Test"))
def test_value_must_be_typed(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(32)
with self.assertRaises(PolygraphValueError):
union("Test")
def test_value_must_have_right_type(self):
union = String | Int
with self.assertRaises(PolygraphValueError):
union(Float(32))
|
b9d5c21a1c18fafd205e6fdc931b82cad6875bc8 | unit_tests/test_ccs.py | unit_tests/test_ccs.py | #!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93'
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
| #!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93',
'Coefficient of correlation : 28.78%'
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
},
{
'name': 'Coefficient of correlation',
'percentage': 28.78
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
| Add tests for parsing percentages | Add tests for parsing percentages
| Python | mit | ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData | #!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93'
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
Add tests for parsing percentages | #!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93',
'Coefficient of correlation : 28.78%'
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
},
{
'name': 'Coefficient of correlation',
'percentage': 28.78
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
| <commit_before>#!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93'
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
<commit_msg>Add tests for parsing percentages<commit_after> | #!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93',
'Coefficient of correlation : 28.78%'
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
},
{
'name': 'Coefficient of correlation',
'percentage': 28.78
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
| #!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93'
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
Add tests for parsing percentages#!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93',
'Coefficient of correlation : 28.78%'
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
},
{
'name': 'Coefficient of correlation',
'percentage': 28.78
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
| <commit_before>#!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93'
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
<commit_msg>Add tests for parsing percentages<commit_after>#!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93',
'Coefficient of correlation : 28.78%'
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
},
{
'name': 'Coefficient of correlation',
'percentage': 28.78
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
|
43a54b9d8e753f721619aa5fcecec39eb4ca6eff | django_amber/utils.py | django_amber/utils.py | from multiprocessing import Process
from time import sleep
from socket import socket
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
return requests.get(url)
except requests.exceptions.ConnectionError:
pass
sleep(0.1 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
| from multiprocessing import Process
from time import sleep
from socket import socket
import traceback
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
rsp = requests.get(url)
rsp.raise_for_status()
except requests.exceptions.RequestException as e:
print('get_with_retries', i)
traceback.print_exc()
sleep(0.2 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
| Add logging and increase timeout | Add logging and increase timeout | Python | mit | PyconUK/2017.pyconuk.org,PyconUK/2017.pyconuk.org,PyconUK/2017.pyconuk.org | from multiprocessing import Process
from time import sleep
from socket import socket
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
return requests.get(url)
except requests.exceptions.ConnectionError:
pass
sleep(0.1 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
Add logging and increase timeout | from multiprocessing import Process
from time import sleep
from socket import socket
import traceback
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
rsp = requests.get(url)
rsp.raise_for_status()
except requests.exceptions.RequestException as e:
print('get_with_retries', i)
traceback.print_exc()
sleep(0.2 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
| <commit_before>from multiprocessing import Process
from time import sleep
from socket import socket
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
return requests.get(url)
except requests.exceptions.ConnectionError:
pass
sleep(0.1 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
<commit_msg>Add logging and increase timeout<commit_after> | from multiprocessing import Process
from time import sleep
from socket import socket
import traceback
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
rsp = requests.get(url)
rsp.raise_for_status()
except requests.exceptions.RequestException as e:
print('get_with_retries', i)
traceback.print_exc()
sleep(0.2 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
| from multiprocessing import Process
from time import sleep
from socket import socket
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
return requests.get(url)
except requests.exceptions.ConnectionError:
pass
sleep(0.1 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
Add logging and increase timeoutfrom multiprocessing import Process
from time import sleep
from socket import socket
import traceback
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
rsp = requests.get(url)
rsp.raise_for_status()
except requests.exceptions.RequestException as e:
print('get_with_retries', i)
traceback.print_exc()
sleep(0.2 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
| <commit_before>from multiprocessing import Process
from time import sleep
from socket import socket
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
return requests.get(url)
except requests.exceptions.ConnectionError:
pass
sleep(0.1 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
<commit_msg>Add logging and increase timeout<commit_after>from multiprocessing import Process
from time import sleep
from socket import socket
import traceback
import requests
from django.core.management import call_command
from django.core.management.commands.runserver import Command as RunserverCommand
default_port = RunserverCommand.default_port
def run_runserver_in_process(port=default_port):
p = Process(
target=call_command,
args=('runserver', port),
kwargs={'use_reloader': False},
)
p.start()
wait_for_server(port)
return p
def wait_for_server(port=default_port):
get_with_retries('http://localhost:{}/'.format(port))
def get_with_retries(url, num_retries=5):
for i in range(num_retries):
try:
rsp = requests.get(url)
rsp.raise_for_status()
except requests.exceptions.RequestException as e:
print('get_with_retries', i)
traceback.print_exc()
sleep(0.2 * 2 ** i)
requests.get(url)
def get_free_port():
s = socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return str(port)
|
5254e31d2309aa21b347d854293084eefddaa465 | virtool/error_pages.py | virtool/error_pages.py | from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
try:
response = await handler(request)
if not request.path.startswith("/api"):
if response.status == 404:
return handle_404()
return response
except web.HTTPException as ex:
if ex.status == 404:
return handle_404()
raise
return middleware_handler
def handle_404():
html = Template(filename="virtool/templates/error_404.html").render(hash=get_static_hash())
return web.Response(body=html, content_type="text/html")
| from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
is_api_call = request.path.startswith("/api")
try:
response = await handler(request)
if not is_api_call:
if response.status == 404:
return handle_404()
return response
except web.HTTPException as ex:
if not is_api_call and ex.status == 404:
return handle_404()
raise
return middleware_handler
def handle_404():
html = Template(filename="virtool/templates/error_404.html").render(hash=get_static_hash())
return web.Response(body=html, content_type="text/html")
| Make HTTPExceptions return errors for /api calls | Make HTTPExceptions return errors for /api calls
| Python | mit | virtool/virtool,virtool/virtool,igboyes/virtool,igboyes/virtool | from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
try:
response = await handler(request)
if not request.path.startswith("/api"):
if response.status == 404:
return handle_404()
return response
except web.HTTPException as ex:
if ex.status == 404:
return handle_404()
raise
return middleware_handler
def handle_404():
html = Template(filename="virtool/templates/error_404.html").render(hash=get_static_hash())
return web.Response(body=html, content_type="text/html")
Make HTTPExceptions return errors for /api calls | from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
is_api_call = request.path.startswith("/api")
try:
response = await handler(request)
if not is_api_call:
if response.status == 404:
return handle_404()
return response
except web.HTTPException as ex:
if not is_api_call and ex.status == 404:
return handle_404()
raise
return middleware_handler
def handle_404():
html = Template(filename="virtool/templates/error_404.html").render(hash=get_static_hash())
return web.Response(body=html, content_type="text/html")
| <commit_before>from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
try:
response = await handler(request)
if not request.path.startswith("/api"):
if response.status == 404:
return handle_404()
return response
except web.HTTPException as ex:
if ex.status == 404:
return handle_404()
raise
return middleware_handler
def handle_404():
html = Template(filename="virtool/templates/error_404.html").render(hash=get_static_hash())
return web.Response(body=html, content_type="text/html")
<commit_msg>Make HTTPExceptions return errors for /api calls<commit_after> | from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
is_api_call = request.path.startswith("/api")
try:
response = await handler(request)
if not is_api_call:
if response.status == 404:
return handle_404()
return response
except web.HTTPException as ex:
if not is_api_call and ex.status == 404:
return handle_404()
raise
return middleware_handler
def handle_404():
html = Template(filename="virtool/templates/error_404.html").render(hash=get_static_hash())
return web.Response(body=html, content_type="text/html")
| from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
try:
response = await handler(request)
if not request.path.startswith("/api"):
if response.status == 404:
return handle_404()
return response
except web.HTTPException as ex:
if ex.status == 404:
return handle_404()
raise
return middleware_handler
def handle_404():
html = Template(filename="virtool/templates/error_404.html").render(hash=get_static_hash())
return web.Response(body=html, content_type="text/html")
Make HTTPExceptions return errors for /api callsfrom aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
is_api_call = request.path.startswith("/api")
try:
response = await handler(request)
if not is_api_call:
if response.status == 404:
return handle_404()
return response
except web.HTTPException as ex:
if not is_api_call and ex.status == 404:
return handle_404()
raise
return middleware_handler
def handle_404():
html = Template(filename="virtool/templates/error_404.html").render(hash=get_static_hash())
return web.Response(body=html, content_type="text/html")
| <commit_before>from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
try:
response = await handler(request)
if not request.path.startswith("/api"):
if response.status == 404:
return handle_404()
return response
except web.HTTPException as ex:
if ex.status == 404:
return handle_404()
raise
return middleware_handler
def handle_404():
html = Template(filename="virtool/templates/error_404.html").render(hash=get_static_hash())
return web.Response(body=html, content_type="text/html")
<commit_msg>Make HTTPExceptions return errors for /api calls<commit_after>from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
template_500 = Template(filename="virtool/templates/error_500.html")
async def middleware_factory(app, handler):
async def middleware_handler(request):
is_api_call = request.path.startswith("/api")
try:
response = await handler(request)
if not is_api_call:
if response.status == 404:
return handle_404()
return response
except web.HTTPException as ex:
if not is_api_call and ex.status == 404:
return handle_404()
raise
return middleware_handler
def handle_404():
html = Template(filename="virtool/templates/error_404.html").render(hash=get_static_hash())
return web.Response(body=html, content_type="text/html")
|
6e31ee3aba81e0cafe3b95d1eefd8b0d30d956d1 | manual_test.py | manual_test.py | def output(arg):
print("MANUAL: arg=", arg)
def main():
for abc in range(10):
import ipdb; ipdb.set_trace()
output(abc)
# code to test with nose
import unittest
class IpdbUsageTests(unittest.TestCase):
def testMain(self):
main()
if __name__ == "__main__":
main()
| def output(arg):
print("MANUAL: arg=%s" % arg)
def main():
for abc in range(10):
import ipdb; ipdb.set_trace()
output(abc)
# code to test with nose
import unittest
class IpdbUsageTests(unittest.TestCase):
def testMain(self):
main()
if __name__ == "__main__":
main()
| Update 2to3 output to use string substitution. | Update 2to3 output to use string substitution.
| Python | bsd-3-clause | michelesr/ipdb | def output(arg):
print("MANUAL: arg=", arg)
def main():
for abc in range(10):
import ipdb; ipdb.set_trace()
output(abc)
# code to test with nose
import unittest
class IpdbUsageTests(unittest.TestCase):
def testMain(self):
main()
if __name__ == "__main__":
main()
Update 2to3 output to use string substitution. | def output(arg):
print("MANUAL: arg=%s" % arg)
def main():
for abc in range(10):
import ipdb; ipdb.set_trace()
output(abc)
# code to test with nose
import unittest
class IpdbUsageTests(unittest.TestCase):
def testMain(self):
main()
if __name__ == "__main__":
main()
| <commit_before>def output(arg):
print("MANUAL: arg=", arg)
def main():
for abc in range(10):
import ipdb; ipdb.set_trace()
output(abc)
# code to test with nose
import unittest
class IpdbUsageTests(unittest.TestCase):
def testMain(self):
main()
if __name__ == "__main__":
main()
<commit_msg>Update 2to3 output to use string substitution.<commit_after> | def output(arg):
print("MANUAL: arg=%s" % arg)
def main():
for abc in range(10):
import ipdb; ipdb.set_trace()
output(abc)
# code to test with nose
import unittest
class IpdbUsageTests(unittest.TestCase):
def testMain(self):
main()
if __name__ == "__main__":
main()
| def output(arg):
print("MANUAL: arg=", arg)
def main():
for abc in range(10):
import ipdb; ipdb.set_trace()
output(abc)
# code to test with nose
import unittest
class IpdbUsageTests(unittest.TestCase):
def testMain(self):
main()
if __name__ == "__main__":
main()
Update 2to3 output to use string substitution.def output(arg):
print("MANUAL: arg=%s" % arg)
def main():
for abc in range(10):
import ipdb; ipdb.set_trace()
output(abc)
# code to test with nose
import unittest
class IpdbUsageTests(unittest.TestCase):
def testMain(self):
main()
if __name__ == "__main__":
main()
| <commit_before>def output(arg):
print("MANUAL: arg=", arg)
def main():
for abc in range(10):
import ipdb; ipdb.set_trace()
output(abc)
# code to test with nose
import unittest
class IpdbUsageTests(unittest.TestCase):
def testMain(self):
main()
if __name__ == "__main__":
main()
<commit_msg>Update 2to3 output to use string substitution.<commit_after>def output(arg):
print("MANUAL: arg=%s" % arg)
def main():
for abc in range(10):
import ipdb; ipdb.set_trace()
output(abc)
# code to test with nose
import unittest
class IpdbUsageTests(unittest.TestCase):
def testMain(self):
main()
if __name__ == "__main__":
main()
|
41ed48324354ba9e4263c4085c44902d983835fe | telemetry/telemetry/core/platform/factory.py | telemetry/telemetry/core/platform/factory.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.
import sys
from telemetry import decorators
from telemetry.core.platform import linux_platform_backend
from telemetry.core.platform import mac_platform_backend
from telemetry.core.platform import win_platform_backend
@decorators.Cache
def GetPlatformBackendForCurrentOS():
if sys.platform.startswith('linux'):
return linux_platform_backend.LinuxPlatformBackend()
elif sys.platform == 'darwin':
return mac_platform_backend.MacPlatformBackend()
elif sys.platform == 'win32':
return win_platform_backend.WinPlatformBackend()
else:
raise NotImplementedError()
| # 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.
import sys
from telemetry import decorators
from telemetry.core.platform import linux_platform_backend
from telemetry.core.platform import mac_platform_backend
from telemetry.core.platform import win_platform_backend
@decorators.Cache
def GetPlatformBackendForCurrentOS():
if sys.platform.startswith('linux'):
return linux_platform_backend.LinuxPlatformBackend()
elif sys.platform == 'darwin':
return mac_platform_backend.MacPlatformBackend()
elif sys.platform == 'win32':
return win_platform_backend.WinPlatformBackend()
else:
raise NotImplementedError()
| Enable sandbox on OS X page cyclers | [Telemetry] Enable sandbox on OS X page cyclers
The sandbox is disabled when running the page cyclers because it interferes with collecting IO stats on some platforms.
The sandbox does not interfere with IO stat collection on OS X..
BUG=361049
Review URL: https://codereview.chromium.org/176603002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@262377 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | SummerLW/Perf-Insight-Report,catapult-project/catapult,benschmaus/catapult,sahiljain/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult,sahiljain/catapult,sahiljain/catapult,benschmaus/catapult,sahiljain/catapult,catapult-project/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult,sahiljain/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,benschmaus/catapult,SummerLW/Perf-Insight-Report,SummerLW/Perf-Insight-Report,benschmaus/catapult,sahiljain/catapult,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report | # 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.
import sys
from telemetry import decorators
from telemetry.core.platform import linux_platform_backend
from telemetry.core.platform import mac_platform_backend
from telemetry.core.platform import win_platform_backend
@decorators.Cache
def GetPlatformBackendForCurrentOS():
if sys.platform.startswith('linux'):
return linux_platform_backend.LinuxPlatformBackend()
elif sys.platform == 'darwin':
return mac_platform_backend.MacPlatformBackend()
elif sys.platform == 'win32':
return win_platform_backend.WinPlatformBackend()
else:
raise NotImplementedError()
[Telemetry] Enable sandbox on OS X page cyclers
The sandbox is disabled when running the page cyclers because it interferes with collecting IO stats on some platforms.
The sandbox does not interfere with IO stat collection on OS X..
BUG=361049
Review URL: https://codereview.chromium.org/176603002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@262377 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.
import sys
from telemetry import decorators
from telemetry.core.platform import linux_platform_backend
from telemetry.core.platform import mac_platform_backend
from telemetry.core.platform import win_platform_backend
@decorators.Cache
def GetPlatformBackendForCurrentOS():
if sys.platform.startswith('linux'):
return linux_platform_backend.LinuxPlatformBackend()
elif sys.platform == 'darwin':
return mac_platform_backend.MacPlatformBackend()
elif sys.platform == 'win32':
return win_platform_backend.WinPlatformBackend()
else:
raise NotImplementedError()
| <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.
import sys
from telemetry import decorators
from telemetry.core.platform import linux_platform_backend
from telemetry.core.platform import mac_platform_backend
from telemetry.core.platform import win_platform_backend
@decorators.Cache
def GetPlatformBackendForCurrentOS():
if sys.platform.startswith('linux'):
return linux_platform_backend.LinuxPlatformBackend()
elif sys.platform == 'darwin':
return mac_platform_backend.MacPlatformBackend()
elif sys.platform == 'win32':
return win_platform_backend.WinPlatformBackend()
else:
raise NotImplementedError()
<commit_msg>[Telemetry] Enable sandbox on OS X page cyclers
The sandbox is disabled when running the page cyclers because it interferes with collecting IO stats on some platforms.
The sandbox does not interfere with IO stat collection on OS X..
BUG=361049
Review URL: https://codereview.chromium.org/176603002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@262377 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.
import sys
from telemetry import decorators
from telemetry.core.platform import linux_platform_backend
from telemetry.core.platform import mac_platform_backend
from telemetry.core.platform import win_platform_backend
@decorators.Cache
def GetPlatformBackendForCurrentOS():
if sys.platform.startswith('linux'):
return linux_platform_backend.LinuxPlatformBackend()
elif sys.platform == 'darwin':
return mac_platform_backend.MacPlatformBackend()
elif sys.platform == 'win32':
return win_platform_backend.WinPlatformBackend()
else:
raise NotImplementedError()
| # 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.
import sys
from telemetry import decorators
from telemetry.core.platform import linux_platform_backend
from telemetry.core.platform import mac_platform_backend
from telemetry.core.platform import win_platform_backend
@decorators.Cache
def GetPlatformBackendForCurrentOS():
if sys.platform.startswith('linux'):
return linux_platform_backend.LinuxPlatformBackend()
elif sys.platform == 'darwin':
return mac_platform_backend.MacPlatformBackend()
elif sys.platform == 'win32':
return win_platform_backend.WinPlatformBackend()
else:
raise NotImplementedError()
[Telemetry] Enable sandbox on OS X page cyclers
The sandbox is disabled when running the page cyclers because it interferes with collecting IO stats on some platforms.
The sandbox does not interfere with IO stat collection on OS X..
BUG=361049
Review URL: https://codereview.chromium.org/176603002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@262377 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.
import sys
from telemetry import decorators
from telemetry.core.platform import linux_platform_backend
from telemetry.core.platform import mac_platform_backend
from telemetry.core.platform import win_platform_backend
@decorators.Cache
def GetPlatformBackendForCurrentOS():
if sys.platform.startswith('linux'):
return linux_platform_backend.LinuxPlatformBackend()
elif sys.platform == 'darwin':
return mac_platform_backend.MacPlatformBackend()
elif sys.platform == 'win32':
return win_platform_backend.WinPlatformBackend()
else:
raise NotImplementedError()
| <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.
import sys
from telemetry import decorators
from telemetry.core.platform import linux_platform_backend
from telemetry.core.platform import mac_platform_backend
from telemetry.core.platform import win_platform_backend
@decorators.Cache
def GetPlatformBackendForCurrentOS():
if sys.platform.startswith('linux'):
return linux_platform_backend.LinuxPlatformBackend()
elif sys.platform == 'darwin':
return mac_platform_backend.MacPlatformBackend()
elif sys.platform == 'win32':
return win_platform_backend.WinPlatformBackend()
else:
raise NotImplementedError()
<commit_msg>[Telemetry] Enable sandbox on OS X page cyclers
The sandbox is disabled when running the page cyclers because it interferes with collecting IO stats on some platforms.
The sandbox does not interfere with IO stat collection on OS X..
BUG=361049
Review URL: https://codereview.chromium.org/176603002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@262377 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.
import sys
from telemetry import decorators
from telemetry.core.platform import linux_platform_backend
from telemetry.core.platform import mac_platform_backend
from telemetry.core.platform import win_platform_backend
@decorators.Cache
def GetPlatformBackendForCurrentOS():
if sys.platform.startswith('linux'):
return linux_platform_backend.LinuxPlatformBackend()
elif sys.platform == 'darwin':
return mac_platform_backend.MacPlatformBackend()
elif sys.platform == 'win32':
return win_platform_backend.WinPlatformBackend()
else:
raise NotImplementedError()
|
90a265c9c673856a6f119ab04bbd5d57ab375dc6 | django_fsm_log/models.py | django_fsm_log/models.py | from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
| from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.timezone import now
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(default=now)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
| Switch from auto_now_add=True to default=now | Switch from auto_now_add=True to default=now
This allows for optional direct setting of the timestamp, eg when loading fixtures. | Python | mit | ticosax/django-fsm-log,blueyed/django-fsm-log,Andrey86/django-fsm-log,gizmag/django-fsm-log,fjcapdevila/django-fsm-log,mord4z/django-fsm-log,pombredanne/django-fsm-log | from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
Switch from auto_now_add=True to default=now
This allows for optional direct setting of the timestamp, eg when loading fixtures. | from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.timezone import now
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(default=now)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
| <commit_before>from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
<commit_msg>Switch from auto_now_add=True to default=now
This allows for optional direct setting of the timestamp, eg when loading fixtures.<commit_after> | from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.timezone import now
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(default=now)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
| from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
Switch from auto_now_add=True to default=now
This allows for optional direct setting of the timestamp, eg when loading fixtures.from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.timezone import now
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(default=now)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
| <commit_before>from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
<commit_msg>Switch from auto_now_add=True to default=now
This allows for optional direct setting of the timestamp, eg when loading fixtures.<commit_after>from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.timezone import now
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(default=now)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
|
2359b65a59b5326a07768578469177d65bbddf6e | celery/__init__.py | celery/__init__.py | """Distributed Task Queue"""
from celery.distmeta import __version__, __author__, __contact__
from celery.distmeta import __homepage__, __docformat__
from celery.distmeta import VERSION, is_stable_release, version_with_meta
| """Distributed Task Queue"""
from celery.distmeta import (__version__, __author__, __contact__,
__homepage__, __docformat__, VERSION,
is_stable_release, version_with_meta)
| Use from .. import (...) parens | Use from .. import (...) parens
| Python | bsd-3-clause | frac/celery,cbrepo/celery,frac/celery,WoLpH/celery,WoLpH/celery,ask/celery,mitsuhiko/celery,cbrepo/celery,ask/celery,mitsuhiko/celery | """Distributed Task Queue"""
from celery.distmeta import __version__, __author__, __contact__
from celery.distmeta import __homepage__, __docformat__
from celery.distmeta import VERSION, is_stable_release, version_with_meta
Use from .. import (...) parens | """Distributed Task Queue"""
from celery.distmeta import (__version__, __author__, __contact__,
__homepage__, __docformat__, VERSION,
is_stable_release, version_with_meta)
| <commit_before>"""Distributed Task Queue"""
from celery.distmeta import __version__, __author__, __contact__
from celery.distmeta import __homepage__, __docformat__
from celery.distmeta import VERSION, is_stable_release, version_with_meta
<commit_msg>Use from .. import (...) parens<commit_after> | """Distributed Task Queue"""
from celery.distmeta import (__version__, __author__, __contact__,
__homepage__, __docformat__, VERSION,
is_stable_release, version_with_meta)
| """Distributed Task Queue"""
from celery.distmeta import __version__, __author__, __contact__
from celery.distmeta import __homepage__, __docformat__
from celery.distmeta import VERSION, is_stable_release, version_with_meta
Use from .. import (...) parens"""Distributed Task Queue"""
from celery.distmeta import (__version__, __author__, __contact__,
__homepage__, __docformat__, VERSION,
is_stable_release, version_with_meta)
| <commit_before>"""Distributed Task Queue"""
from celery.distmeta import __version__, __author__, __contact__
from celery.distmeta import __homepage__, __docformat__
from celery.distmeta import VERSION, is_stable_release, version_with_meta
<commit_msg>Use from .. import (...) parens<commit_after>"""Distributed Task Queue"""
from celery.distmeta import (__version__, __author__, __contact__,
__homepage__, __docformat__, VERSION,
is_stable_release, version_with_meta)
|
610c979d00b3b89f3f2b16d58e4b2a797b380d41 | tests/fixtures/postgres.py | tests/fixtures/postgres.py | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
| import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
pg_connection_string = test_pg_connection_string.split('/')
pg_connection_string[-1] = 'virtool'
engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
| Add connection string for connecting to virtool database in order to create a test database | Add connection string for connecting to virtool database in order to create a test database
| Python | mit | igboyes/virtool,virtool/virtool,igboyes/virtool,virtool/virtool | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
Add connection string for connecting to virtool database in order to create a test database | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
pg_connection_string = test_pg_connection_string.split('/')
pg_connection_string[-1] = 'virtool'
engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
| <commit_before>import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
<commit_msg>Add connection string for connecting to virtool database in order to create a test database<commit_after> | import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
pg_connection_string = test_pg_connection_string.split('/')
pg_connection_string[-1] = 'virtool'
engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
| import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
Add connection string for connecting to virtool database in order to create a test databaseimport pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
pg_connection_string = test_pg_connection_string.split('/')
pg_connection_string[-1] = 'virtool'
engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
| <commit_before>import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
<commit_msg>Add connection string for connecting to virtool database in order to create a test database<commit_after>import pytest
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.postgres import Base
@pytest.fixture
def test_pg_connection_string(request):
return request.config.getoption("postgres_connection_string")
@pytest.fixture(scope="function")
async def pg_engine(test_pg_connection_string):
pg_connection_string = test_pg_connection_string.split('/')
pg_connection_string[-1] = 'virtool'
engine = create_async_engine('/'.join(pg_connection_string), isolation_level="AUTOCOMMIT")
async with engine.connect() as conn:
try:
await conn.execute(text("CREATE DATABASE test"))
except ProgrammingError:
pass
return create_async_engine(test_pg_connection_string)
@pytest.fixture(scope="function")
async def test_session(pg_engine, loop):
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
session = AsyncSession(bind=pg_engine)
yield session
async with pg_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await session.close()
|
253ec40f59d2d28a848e17a7c62f85c3bd97dce9 | pages/views.py | pages/views.py | from django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
template_name=settings.DEFAULT_PAGE_TEMPLATE):
lang = get_language_from_request(request)
site = request.site
pages = Page.objects.navigation(site).order_by("tree_id")
if pages:
if page_id:
current_page = get_object_or_404(
Page.objects.published(site), pk=page_id)
elif slug:
slug_content = Content.objects.get_page_slug(slug, site)
if slug_content and \
slug_content.page.calculated_status in (
Page.PUBLISHED, Page.HIDDEN):
current_page = slug_content.page
else:
raise Http404
else:
current_page = pages[0]
template_name = current_page.get_template()
else:
raise Http404
return template_name, locals()
details = auto_render(details)
| from django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
template_name=settings.DEFAULT_PAGE_TEMPLATE):
"""
Example view that get the root pages for navigation,
and the current page if there is any root page.
All is rendered with the current page's template.
"""
lang = get_language_from_request(request)
site = request.site
pages = Page.objects.navigation(site).order_by("tree_id")
if pages:
if page_id:
current_page = get_object_or_404(
Page.objects.published(site), pk=page_id)
elif slug:
slug_content = Content.objects.get_page_slug(slug, site)
if slug_content and \
slug_content.page.calculated_status in (
Page.PUBLISHED, Page.HIDDEN):
current_page = slug_content.page
else:
raise Http404
else:
current_page = pages[0]
template_name = current_page.get_template()
else:
raise Http404
return template_name, locals()
details = auto_render(details)
| Add documentation to the default view | Add documentation to the default view | Python | bsd-3-clause | PiRSquared17/django-page-cms,google-code-export/django-page-cms,PiRSquared17/django-page-cms,PiRSquared17/django-page-cms,google-code-export/django-page-cms,pombreda/django-page-cms,Alwnikrotikz/django-page-cms,pombreda/django-page-cms,odyaka341/django-page-cms,odyaka341/django-page-cms,Alwnikrotikz/django-page-cms,pombreda/django-page-cms,PiRSquared17/django-page-cms,google-code-export/django-page-cms,pombreda/django-page-cms,google-code-export/django-page-cms,odyaka341/django-page-cms,Alwnikrotikz/django-page-cms,odyaka341/django-page-cms,Alwnikrotikz/django-page-cms | from django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
template_name=settings.DEFAULT_PAGE_TEMPLATE):
lang = get_language_from_request(request)
site = request.site
pages = Page.objects.navigation(site).order_by("tree_id")
if pages:
if page_id:
current_page = get_object_or_404(
Page.objects.published(site), pk=page_id)
elif slug:
slug_content = Content.objects.get_page_slug(slug, site)
if slug_content and \
slug_content.page.calculated_status in (
Page.PUBLISHED, Page.HIDDEN):
current_page = slug_content.page
else:
raise Http404
else:
current_page = pages[0]
template_name = current_page.get_template()
else:
raise Http404
return template_name, locals()
details = auto_render(details)
Add documentation to the default view | from django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
template_name=settings.DEFAULT_PAGE_TEMPLATE):
"""
Example view that get the root pages for navigation,
and the current page if there is any root page.
All is rendered with the current page's template.
"""
lang = get_language_from_request(request)
site = request.site
pages = Page.objects.navigation(site).order_by("tree_id")
if pages:
if page_id:
current_page = get_object_or_404(
Page.objects.published(site), pk=page_id)
elif slug:
slug_content = Content.objects.get_page_slug(slug, site)
if slug_content and \
slug_content.page.calculated_status in (
Page.PUBLISHED, Page.HIDDEN):
current_page = slug_content.page
else:
raise Http404
else:
current_page = pages[0]
template_name = current_page.get_template()
else:
raise Http404
return template_name, locals()
details = auto_render(details)
| <commit_before>from django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
template_name=settings.DEFAULT_PAGE_TEMPLATE):
lang = get_language_from_request(request)
site = request.site
pages = Page.objects.navigation(site).order_by("tree_id")
if pages:
if page_id:
current_page = get_object_or_404(
Page.objects.published(site), pk=page_id)
elif slug:
slug_content = Content.objects.get_page_slug(slug, site)
if slug_content and \
slug_content.page.calculated_status in (
Page.PUBLISHED, Page.HIDDEN):
current_page = slug_content.page
else:
raise Http404
else:
current_page = pages[0]
template_name = current_page.get_template()
else:
raise Http404
return template_name, locals()
details = auto_render(details)
<commit_msg>Add documentation to the default view<commit_after> | from django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
template_name=settings.DEFAULT_PAGE_TEMPLATE):
"""
Example view that get the root pages for navigation,
and the current page if there is any root page.
All is rendered with the current page's template.
"""
lang = get_language_from_request(request)
site = request.site
pages = Page.objects.navigation(site).order_by("tree_id")
if pages:
if page_id:
current_page = get_object_or_404(
Page.objects.published(site), pk=page_id)
elif slug:
slug_content = Content.objects.get_page_slug(slug, site)
if slug_content and \
slug_content.page.calculated_status in (
Page.PUBLISHED, Page.HIDDEN):
current_page = slug_content.page
else:
raise Http404
else:
current_page = pages[0]
template_name = current_page.get_template()
else:
raise Http404
return template_name, locals()
details = auto_render(details)
| from django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
template_name=settings.DEFAULT_PAGE_TEMPLATE):
lang = get_language_from_request(request)
site = request.site
pages = Page.objects.navigation(site).order_by("tree_id")
if pages:
if page_id:
current_page = get_object_or_404(
Page.objects.published(site), pk=page_id)
elif slug:
slug_content = Content.objects.get_page_slug(slug, site)
if slug_content and \
slug_content.page.calculated_status in (
Page.PUBLISHED, Page.HIDDEN):
current_page = slug_content.page
else:
raise Http404
else:
current_page = pages[0]
template_name = current_page.get_template()
else:
raise Http404
return template_name, locals()
details = auto_render(details)
Add documentation to the default viewfrom django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
template_name=settings.DEFAULT_PAGE_TEMPLATE):
"""
Example view that get the root pages for navigation,
and the current page if there is any root page.
All is rendered with the current page's template.
"""
lang = get_language_from_request(request)
site = request.site
pages = Page.objects.navigation(site).order_by("tree_id")
if pages:
if page_id:
current_page = get_object_or_404(
Page.objects.published(site), pk=page_id)
elif slug:
slug_content = Content.objects.get_page_slug(slug, site)
if slug_content and \
slug_content.page.calculated_status in (
Page.PUBLISHED, Page.HIDDEN):
current_page = slug_content.page
else:
raise Http404
else:
current_page = pages[0]
template_name = current_page.get_template()
else:
raise Http404
return template_name, locals()
details = auto_render(details)
| <commit_before>from django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
template_name=settings.DEFAULT_PAGE_TEMPLATE):
lang = get_language_from_request(request)
site = request.site
pages = Page.objects.navigation(site).order_by("tree_id")
if pages:
if page_id:
current_page = get_object_or_404(
Page.objects.published(site), pk=page_id)
elif slug:
slug_content = Content.objects.get_page_slug(slug, site)
if slug_content and \
slug_content.page.calculated_status in (
Page.PUBLISHED, Page.HIDDEN):
current_page = slug_content.page
else:
raise Http404
else:
current_page = pages[0]
template_name = current_page.get_template()
else:
raise Http404
return template_name, locals()
details = auto_render(details)
<commit_msg>Add documentation to the default view<commit_after>from django.http import Http404
from django.shortcuts import get_object_or_404
from django.contrib.sites.models import SITE_CACHE
from pages import settings
from pages.models import Page, Content
from pages.utils import auto_render, get_language_from_request
def details(request, page_id=None, slug=None,
template_name=settings.DEFAULT_PAGE_TEMPLATE):
"""
Example view that get the root pages for navigation,
and the current page if there is any root page.
All is rendered with the current page's template.
"""
lang = get_language_from_request(request)
site = request.site
pages = Page.objects.navigation(site).order_by("tree_id")
if pages:
if page_id:
current_page = get_object_or_404(
Page.objects.published(site), pk=page_id)
elif slug:
slug_content = Content.objects.get_page_slug(slug, site)
if slug_content and \
slug_content.page.calculated_status in (
Page.PUBLISHED, Page.HIDDEN):
current_page = slug_content.page
else:
raise Http404
else:
current_page = pages[0]
template_name = current_page.get_template()
else:
raise Http404
return template_name, locals()
details = auto_render(details)
|
ae01c2c1e5ca693193aed12b66fb78e9d613faa7 | tests/unit/test_context.py | tests/unit/test_context.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
import unittest
from openstack.common import context
class ContextTest(unittest.TestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
import testtools
from openstack.common import context
class ContextTest(testtools.TestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
| Use testtools as test base class. | Use testtools as test base class.
On the path to testr migration, we need to replace the unittest base classes
with testtools.
Replace tearDown with addCleanup, addCleanup is more resilient than tearDown.
The fixtures library has excellent support for managing and cleaning
tempfiles. Use it.
Replace skip_ with testtools.skipTest
Part of blueprint grizzly-testtools.
Change-Id: I45e11bbb1ff9b31f3278d3b016737dcb7850cd98
| Python | apache-2.0 | dims/oslo.context,citrix-openstack-build/oslo.context,yanheven/oslo.middleware,JioCloud/oslo.context,varunarya10/oslo.context,openstack/oslo.context | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
import unittest
from openstack.common import context
class ContextTest(unittest.TestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
Use testtools as test base class.
On the path to testr migration, we need to replace the unittest base classes
with testtools.
Replace tearDown with addCleanup, addCleanup is more resilient than tearDown.
The fixtures library has excellent support for managing and cleaning
tempfiles. Use it.
Replace skip_ with testtools.skipTest
Part of blueprint grizzly-testtools.
Change-Id: I45e11bbb1ff9b31f3278d3b016737dcb7850cd98 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
import testtools
from openstack.common import context
class ContextTest(testtools.TestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
| <commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
import unittest
from openstack.common import context
class ContextTest(unittest.TestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
<commit_msg>Use testtools as test base class.
On the path to testr migration, we need to replace the unittest base classes
with testtools.
Replace tearDown with addCleanup, addCleanup is more resilient than tearDown.
The fixtures library has excellent support for managing and cleaning
tempfiles. Use it.
Replace skip_ with testtools.skipTest
Part of blueprint grizzly-testtools.
Change-Id: I45e11bbb1ff9b31f3278d3b016737dcb7850cd98<commit_after> | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
import testtools
from openstack.common import context
class ContextTest(testtools.TestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
import unittest
from openstack.common import context
class ContextTest(unittest.TestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
Use testtools as test base class.
On the path to testr migration, we need to replace the unittest base classes
with testtools.
Replace tearDown with addCleanup, addCleanup is more resilient than tearDown.
The fixtures library has excellent support for managing and cleaning
tempfiles. Use it.
Replace skip_ with testtools.skipTest
Part of blueprint grizzly-testtools.
Change-Id: I45e11bbb1ff9b31f3278d3b016737dcb7850cd98# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
import testtools
from openstack.common import context
class ContextTest(testtools.TestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
| <commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
import unittest
from openstack.common import context
class ContextTest(unittest.TestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
<commit_msg>Use testtools as test base class.
On the path to testr migration, we need to replace the unittest base classes
with testtools.
Replace tearDown with addCleanup, addCleanup is more resilient than tearDown.
The fixtures library has excellent support for managing and cleaning
tempfiles. Use it.
Replace skip_ with testtools.skipTest
Part of blueprint grizzly-testtools.
Change-Id: I45e11bbb1ff9b31f3278d3b016737dcb7850cd98<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
import testtools
from openstack.common import context
class ContextTest(testtools.TestCase):
def test_context(self):
ctx = context.RequestContext()
self.assertTrue(ctx)
|
ea710f4a2d734994ee3d18e90c7afc6aff2f8604 | djedi/admin/cms.py | djedi/admin/cms.py | from django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn’t break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
| from django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn't break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
| Replace non-ASCII character in comment | Replace non-ASCII character in comment
| Python | bsd-3-clause | 5monkeys/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms | from django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn’t break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
Replace non-ASCII character in comment | from django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn't break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
| <commit_before>from django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn’t break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
<commit_msg>Replace non-ASCII character in comment<commit_after> | from django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn't break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
| from django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn’t break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
Replace non-ASCII character in commentfrom django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn't break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
| <commit_before>from django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn’t break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
<commit_msg>Replace non-ASCII character in comment<commit_after>from django.contrib.admin import ModelAdmin
from django.core.exceptions import PermissionDenied
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic import View
from ..auth import has_permission
from ..compat import include, patterns, render, url
from .mixins import DjediContextMixin
class Admin(ModelAdmin):
verbose_name = 'CMS'
verbose_name_plural = verbose_name
def get_urls(self):
return patterns(
url(r'^', include('djedi.admin.urls', namespace='djedi')),
url(r'', lambda: None, name='djedi_cms_changelist') # Placeholder to show change link to CMS in admin
)
def has_change_permission(self, request, obj=None):
return has_permission(request)
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
# Hide Djedi in the admin, since that view is not finished yet.
# This only works in Django 1.8+, but shouldn't break older versions.
def has_module_permission(self, request):
return False
class DjediCMS(DjediContextMixin, View):
@xframe_options_exempt
def get(self, request):
if has_permission(request):
return render(request, 'djedi/cms/cms.html', self.get_context_data())
else:
raise PermissionDenied
|
957ebd10ebe51306c1f5a5ff4842077542454fcf | indra/biopax/biopax_api.py | indra/biopax/biopax_api.py | import sys
from processor import BiopaxProcessor
from indra.java_vm import autoclass, JavaException
from indra.biopax import pathway_commons_client as pcc
def process_pc_neighborhood(gene_names, neighbor_limit=1):
model = pcc.graph_query('neighborhood', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsbetween(gene_names, neighbor_limit=1):
model = pcc.graph_query('pathsbetween', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1):
model = pcc.run_pc_query('pathsfromto', source_genes,
target_genes, neighbor_limit)
if model is not None:
return process_model(model)
def process_owl(owl_filename):
model = pcc.owl_to_model(owl_filename)
return process_model(model)
def process_model(model):
bproc = BiopaxProcessor(model)
# bproc.get_complexes()
# bproc.get_phosphorylation()
# bproc.print_statements()
return bproc
if __name__ == '__main__':
pass
| import sys
from processor import BiopaxProcessor
from indra.java_vm import autoclass, JavaException
from indra.biopax import pathway_commons_client as pcc
def process_pc_neighborhood(gene_names, neighbor_limit=1):
model = pcc.graph_query('neighborhood', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsbetween(gene_names, neighbor_limit=1):
model = pcc.graph_query('pathsbetween', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1):
model = pcc.graph_query('pathsfromto', source_genes,
target_genes, neighbor_limit)
if model is not None:
return process_model(model)
def process_owl(owl_filename):
model = pcc.owl_to_model(owl_filename)
return process_model(model)
def process_model(model):
bproc = BiopaxProcessor(model)
# bproc.get_complexes()
# bproc.get_phosphorylation()
# bproc.print_statements()
return bproc
if __name__ == '__main__':
pass
| Fix calling pathway commons client in biopax api | Fix calling pathway commons client in biopax api
| Python | bsd-2-clause | pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,pvtodorov/indra,jmuhlich/indra,johnbachman/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra,jmuhlich/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,johnbachman/indra,sorgerlab/indra,jmuhlich/indra,bgyori/indra,bgyori/indra,bgyori/indra | import sys
from processor import BiopaxProcessor
from indra.java_vm import autoclass, JavaException
from indra.biopax import pathway_commons_client as pcc
def process_pc_neighborhood(gene_names, neighbor_limit=1):
model = pcc.graph_query('neighborhood', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsbetween(gene_names, neighbor_limit=1):
model = pcc.graph_query('pathsbetween', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1):
model = pcc.run_pc_query('pathsfromto', source_genes,
target_genes, neighbor_limit)
if model is not None:
return process_model(model)
def process_owl(owl_filename):
model = pcc.owl_to_model(owl_filename)
return process_model(model)
def process_model(model):
bproc = BiopaxProcessor(model)
# bproc.get_complexes()
# bproc.get_phosphorylation()
# bproc.print_statements()
return bproc
if __name__ == '__main__':
pass
Fix calling pathway commons client in biopax api | import sys
from processor import BiopaxProcessor
from indra.java_vm import autoclass, JavaException
from indra.biopax import pathway_commons_client as pcc
def process_pc_neighborhood(gene_names, neighbor_limit=1):
model = pcc.graph_query('neighborhood', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsbetween(gene_names, neighbor_limit=1):
model = pcc.graph_query('pathsbetween', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1):
model = pcc.graph_query('pathsfromto', source_genes,
target_genes, neighbor_limit)
if model is not None:
return process_model(model)
def process_owl(owl_filename):
model = pcc.owl_to_model(owl_filename)
return process_model(model)
def process_model(model):
bproc = BiopaxProcessor(model)
# bproc.get_complexes()
# bproc.get_phosphorylation()
# bproc.print_statements()
return bproc
if __name__ == '__main__':
pass
| <commit_before>import sys
from processor import BiopaxProcessor
from indra.java_vm import autoclass, JavaException
from indra.biopax import pathway_commons_client as pcc
def process_pc_neighborhood(gene_names, neighbor_limit=1):
model = pcc.graph_query('neighborhood', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsbetween(gene_names, neighbor_limit=1):
model = pcc.graph_query('pathsbetween', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1):
model = pcc.run_pc_query('pathsfromto', source_genes,
target_genes, neighbor_limit)
if model is not None:
return process_model(model)
def process_owl(owl_filename):
model = pcc.owl_to_model(owl_filename)
return process_model(model)
def process_model(model):
bproc = BiopaxProcessor(model)
# bproc.get_complexes()
# bproc.get_phosphorylation()
# bproc.print_statements()
return bproc
if __name__ == '__main__':
pass
<commit_msg>Fix calling pathway commons client in biopax api<commit_after> | import sys
from processor import BiopaxProcessor
from indra.java_vm import autoclass, JavaException
from indra.biopax import pathway_commons_client as pcc
def process_pc_neighborhood(gene_names, neighbor_limit=1):
model = pcc.graph_query('neighborhood', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsbetween(gene_names, neighbor_limit=1):
model = pcc.graph_query('pathsbetween', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1):
model = pcc.graph_query('pathsfromto', source_genes,
target_genes, neighbor_limit)
if model is not None:
return process_model(model)
def process_owl(owl_filename):
model = pcc.owl_to_model(owl_filename)
return process_model(model)
def process_model(model):
bproc = BiopaxProcessor(model)
# bproc.get_complexes()
# bproc.get_phosphorylation()
# bproc.print_statements()
return bproc
if __name__ == '__main__':
pass
| import sys
from processor import BiopaxProcessor
from indra.java_vm import autoclass, JavaException
from indra.biopax import pathway_commons_client as pcc
def process_pc_neighborhood(gene_names, neighbor_limit=1):
model = pcc.graph_query('neighborhood', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsbetween(gene_names, neighbor_limit=1):
model = pcc.graph_query('pathsbetween', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1):
model = pcc.run_pc_query('pathsfromto', source_genes,
target_genes, neighbor_limit)
if model is not None:
return process_model(model)
def process_owl(owl_filename):
model = pcc.owl_to_model(owl_filename)
return process_model(model)
def process_model(model):
bproc = BiopaxProcessor(model)
# bproc.get_complexes()
# bproc.get_phosphorylation()
# bproc.print_statements()
return bproc
if __name__ == '__main__':
pass
Fix calling pathway commons client in biopax apiimport sys
from processor import BiopaxProcessor
from indra.java_vm import autoclass, JavaException
from indra.biopax import pathway_commons_client as pcc
def process_pc_neighborhood(gene_names, neighbor_limit=1):
model = pcc.graph_query('neighborhood', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsbetween(gene_names, neighbor_limit=1):
model = pcc.graph_query('pathsbetween', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1):
model = pcc.graph_query('pathsfromto', source_genes,
target_genes, neighbor_limit)
if model is not None:
return process_model(model)
def process_owl(owl_filename):
model = pcc.owl_to_model(owl_filename)
return process_model(model)
def process_model(model):
bproc = BiopaxProcessor(model)
# bproc.get_complexes()
# bproc.get_phosphorylation()
# bproc.print_statements()
return bproc
if __name__ == '__main__':
pass
| <commit_before>import sys
from processor import BiopaxProcessor
from indra.java_vm import autoclass, JavaException
from indra.biopax import pathway_commons_client as pcc
def process_pc_neighborhood(gene_names, neighbor_limit=1):
model = pcc.graph_query('neighborhood', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsbetween(gene_names, neighbor_limit=1):
model = pcc.graph_query('pathsbetween', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1):
model = pcc.run_pc_query('pathsfromto', source_genes,
target_genes, neighbor_limit)
if model is not None:
return process_model(model)
def process_owl(owl_filename):
model = pcc.owl_to_model(owl_filename)
return process_model(model)
def process_model(model):
bproc = BiopaxProcessor(model)
# bproc.get_complexes()
# bproc.get_phosphorylation()
# bproc.print_statements()
return bproc
if __name__ == '__main__':
pass
<commit_msg>Fix calling pathway commons client in biopax api<commit_after>import sys
from processor import BiopaxProcessor
from indra.java_vm import autoclass, JavaException
from indra.biopax import pathway_commons_client as pcc
def process_pc_neighborhood(gene_names, neighbor_limit=1):
model = pcc.graph_query('neighborhood', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsbetween(gene_names, neighbor_limit=1):
model = pcc.graph_query('pathsbetween', gene_names,
neighbor_limit=neighbor_limit)
if model is not None:
return process_model(model)
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1):
model = pcc.graph_query('pathsfromto', source_genes,
target_genes, neighbor_limit)
if model is not None:
return process_model(model)
def process_owl(owl_filename):
model = pcc.owl_to_model(owl_filename)
return process_model(model)
def process_model(model):
bproc = BiopaxProcessor(model)
# bproc.get_complexes()
# bproc.get_phosphorylation()
# bproc.print_statements()
return bproc
if __name__ == '__main__':
pass
|
c10afc4ebd4d7ec8571c0685c0d87f76b25b3af9 | scipy/special/_precompute/utils.py | scipy/special/_precompute/utils.py | try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = map(lambda x: mp.mpf(x), b)
return b
| try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = [mp.mpf(x) for x in b]
return b
| Use list comprehension instead of lambda function | Use list comprehension instead of lambda function
| Python | bsd-3-clause | grlee77/scipy,WarrenWeckesser/scipy,vigna/scipy,endolith/scipy,andyfaff/scipy,rgommers/scipy,scipy/scipy,grlee77/scipy,mdhaber/scipy,Stefan-Endres/scipy,zerothi/scipy,rgommers/scipy,andyfaff/scipy,scipy/scipy,zerothi/scipy,tylerjereddy/scipy,endolith/scipy,mdhaber/scipy,endolith/scipy,rgommers/scipy,mdhaber/scipy,endolith/scipy,e-q/scipy,WarrenWeckesser/scipy,ilayn/scipy,matthew-brett/scipy,anntzer/scipy,scipy/scipy,tylerjereddy/scipy,Eric89GXL/scipy,vigna/scipy,WarrenWeckesser/scipy,perimosocordiae/scipy,andyfaff/scipy,perimosocordiae/scipy,e-q/scipy,andyfaff/scipy,WarrenWeckesser/scipy,tylerjereddy/scipy,grlee77/scipy,tylerjereddy/scipy,anntzer/scipy,matthew-brett/scipy,tylerjereddy/scipy,rgommers/scipy,WarrenWeckesser/scipy,vigna/scipy,matthew-brett/scipy,zerothi/scipy,Stefan-Endres/scipy,endolith/scipy,vigna/scipy,ilayn/scipy,ilayn/scipy,zerothi/scipy,mdhaber/scipy,perimosocordiae/scipy,WarrenWeckesser/scipy,anntzer/scipy,zerothi/scipy,perimosocordiae/scipy,zerothi/scipy,andyfaff/scipy,scipy/scipy,vigna/scipy,anntzer/scipy,e-q/scipy,scipy/scipy,perimosocordiae/scipy,matthew-brett/scipy,Eric89GXL/scipy,grlee77/scipy,mdhaber/scipy,anntzer/scipy,ilayn/scipy,ilayn/scipy,matthew-brett/scipy,anntzer/scipy,grlee77/scipy,Stefan-Endres/scipy,e-q/scipy,ilayn/scipy,scipy/scipy,Eric89GXL/scipy,mdhaber/scipy,endolith/scipy,Eric89GXL/scipy,rgommers/scipy,Eric89GXL/scipy,andyfaff/scipy,Eric89GXL/scipy,Stefan-Endres/scipy,Stefan-Endres/scipy,Stefan-Endres/scipy,perimosocordiae/scipy,e-q/scipy | try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = map(lambda x: mp.mpf(x), b)
return b
Use list comprehension instead of lambda function | try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = [mp.mpf(x) for x in b]
return b
| <commit_before>try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = map(lambda x: mp.mpf(x), b)
return b
<commit_msg>Use list comprehension instead of lambda function<commit_after> | try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = [mp.mpf(x) for x in b]
return b
| try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = map(lambda x: mp.mpf(x), b)
return b
Use list comprehension instead of lambda functiontry:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = [mp.mpf(x) for x in b]
return b
| <commit_before>try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = map(lambda x: mp.mpf(x), b)
return b
<commit_msg>Use list comprehension instead of lambda function<commit_after>try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = [mp.mpf(x) for x in b]
return b
|
9e6f3f9c6816d151132b0e133524cb56a6d998d2 | skeleton/website/jasyscript.py | skeleton/website/jasyscript.py | import konstrukteur.Konstrukteur
import jasy.asset.Manager2 as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
assetManager = AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
# Copy assets to build path
assetManager.copyAssets() | import konstrukteur.Konstrukteur
import jasy.asset.Manager as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
assetManager = AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
# Copy assets to build path
assetManager.copyAssets() | Fix renaming of jasy.asset.Manager2 to jasy.asset.Manager | Fix renaming of jasy.asset.Manager2 to jasy.asset.Manager
| Python | mit | fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur | import konstrukteur.Konstrukteur
import jasy.asset.Manager2 as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
assetManager = AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
# Copy assets to build path
assetManager.copyAssets()Fix renaming of jasy.asset.Manager2 to jasy.asset.Manager | import konstrukteur.Konstrukteur
import jasy.asset.Manager as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
assetManager = AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
# Copy assets to build path
assetManager.copyAssets() | <commit_before>import konstrukteur.Konstrukteur
import jasy.asset.Manager2 as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
assetManager = AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
# Copy assets to build path
assetManager.copyAssets()<commit_msg>Fix renaming of jasy.asset.Manager2 to jasy.asset.Manager<commit_after> | import konstrukteur.Konstrukteur
import jasy.asset.Manager as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
assetManager = AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
# Copy assets to build path
assetManager.copyAssets() | import konstrukteur.Konstrukteur
import jasy.asset.Manager2 as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
assetManager = AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
# Copy assets to build path
assetManager.copyAssets()Fix renaming of jasy.asset.Manager2 to jasy.asset.Managerimport konstrukteur.Konstrukteur
import jasy.asset.Manager as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
assetManager = AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
# Copy assets to build path
assetManager.copyAssets() | <commit_before>import konstrukteur.Konstrukteur
import jasy.asset.Manager2 as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
assetManager = AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
# Copy assets to build path
assetManager.copyAssets()<commit_msg>Fix renaming of jasy.asset.Manager2 to jasy.asset.Manager<commit_after>import konstrukteur.Konstrukteur
import jasy.asset.Manager as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
assetManager = AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
# Copy assets to build path
assetManager.copyAssets() |
105864b44af3f1210e194e2deabfc760cac25055 | talempd/zest/skype/FirstRound/MiddleRandom.py | talempd/zest/skype/FirstRound/MiddleRandom.py | from random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(word[1:-1])) < 2:
return word
mid = range(1, len(word) - 1)
pre = mid[:]
while pre == mid:
pre = mid[:]
shuffle(mid)
newword = word[0]
for i in mid:
newword += word[i]
newword += word[-1]
return newword
tests = []
tests.append("I love you so much")
tests.append("A fox runs so fast so it has to die in a extremely way")
tests.append("A")
for test in tests:
print midrand(test)
| from random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(word[1:-1])) < 2:
return word
mid = range(1, len(word) - 1)
while True:
pre = mid[:]
shuffle(mid)
isdiff = False
for j in range(len(mid)):
if word[pre[j]] != word[mid[j]]:
isdiff = True
break
if isdiff:
break
newword = word[0]
for i in mid:
newword += word[i]
newword += word[-1]
return newword
def main():
tests = []
tests.append("A")
tests.append("I eat apple")
tests.append("A fox runs so fast that it suddenly die")
for test in tests:
print test
print midrand(test)
print
if __name__ == "__main__":
main()
| Fix Two Bugs for MidRand | Fix Two Bugs for MidRand
| Python | mit | cc13ny/Allin,Chasego/codi,cc13ny/algo,cc13ny/Allin,cc13ny/algo,cc13ny/Allin,cc13ny/algo,Chasego/codirit,Chasego/codi,Chasego/codirit,Chasego/codirit,Chasego/codi,Chasego/cod,Chasego/cod,Chasego/cod,Chasego/codi,cc13ny/algo,Chasego/codi,Chasego/cod,Chasego/codirit,cc13ny/Allin,Chasego/codirit,Chasego/cod,cc13ny/Allin,cc13ny/algo | from random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(word[1:-1])) < 2:
return word
mid = range(1, len(word) - 1)
pre = mid[:]
while pre == mid:
pre = mid[:]
shuffle(mid)
newword = word[0]
for i in mid:
newword += word[i]
newword += word[-1]
return newword
tests = []
tests.append("I love you so much")
tests.append("A fox runs so fast so it has to die in a extremely way")
tests.append("A")
for test in tests:
print midrand(test)
Fix Two Bugs for MidRand | from random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(word[1:-1])) < 2:
return word
mid = range(1, len(word) - 1)
while True:
pre = mid[:]
shuffle(mid)
isdiff = False
for j in range(len(mid)):
if word[pre[j]] != word[mid[j]]:
isdiff = True
break
if isdiff:
break
newword = word[0]
for i in mid:
newword += word[i]
newword += word[-1]
return newword
def main():
tests = []
tests.append("A")
tests.append("I eat apple")
tests.append("A fox runs so fast that it suddenly die")
for test in tests:
print test
print midrand(test)
print
if __name__ == "__main__":
main()
| <commit_before>from random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(word[1:-1])) < 2:
return word
mid = range(1, len(word) - 1)
pre = mid[:]
while pre == mid:
pre = mid[:]
shuffle(mid)
newword = word[0]
for i in mid:
newword += word[i]
newword += word[-1]
return newword
tests = []
tests.append("I love you so much")
tests.append("A fox runs so fast so it has to die in a extremely way")
tests.append("A")
for test in tests:
print midrand(test)
<commit_msg>Fix Two Bugs for MidRand<commit_after> | from random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(word[1:-1])) < 2:
return word
mid = range(1, len(word) - 1)
while True:
pre = mid[:]
shuffle(mid)
isdiff = False
for j in range(len(mid)):
if word[pre[j]] != word[mid[j]]:
isdiff = True
break
if isdiff:
break
newword = word[0]
for i in mid:
newword += word[i]
newword += word[-1]
return newword
def main():
tests = []
tests.append("A")
tests.append("I eat apple")
tests.append("A fox runs so fast that it suddenly die")
for test in tests:
print test
print midrand(test)
print
if __name__ == "__main__":
main()
| from random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(word[1:-1])) < 2:
return word
mid = range(1, len(word) - 1)
pre = mid[:]
while pre == mid:
pre = mid[:]
shuffle(mid)
newword = word[0]
for i in mid:
newword += word[i]
newword += word[-1]
return newword
tests = []
tests.append("I love you so much")
tests.append("A fox runs so fast so it has to die in a extremely way")
tests.append("A")
for test in tests:
print midrand(test)
Fix Two Bugs for MidRandfrom random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(word[1:-1])) < 2:
return word
mid = range(1, len(word) - 1)
while True:
pre = mid[:]
shuffle(mid)
isdiff = False
for j in range(len(mid)):
if word[pre[j]] != word[mid[j]]:
isdiff = True
break
if isdiff:
break
newword = word[0]
for i in mid:
newword += word[i]
newword += word[-1]
return newword
def main():
tests = []
tests.append("A")
tests.append("I eat apple")
tests.append("A fox runs so fast that it suddenly die")
for test in tests:
print test
print midrand(test)
print
if __name__ == "__main__":
main()
| <commit_before>from random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(word[1:-1])) < 2:
return word
mid = range(1, len(word) - 1)
pre = mid[:]
while pre == mid:
pre = mid[:]
shuffle(mid)
newword = word[0]
for i in mid:
newword += word[i]
newword += word[-1]
return newword
tests = []
tests.append("I love you so much")
tests.append("A fox runs so fast so it has to die in a extremely way")
tests.append("A")
for test in tests:
print midrand(test)
<commit_msg>Fix Two Bugs for MidRand<commit_after>from random import shuffle
def midrand(sentence):
words = sentence.split()
newwords = [randomized(word) for word in words]
newsentence = ' '.join(newwords)
if sentence == newsentence:
return "They can't be different"
else:
return newsentence
def randomized(word):
if len(set(word[1:-1])) < 2:
return word
mid = range(1, len(word) - 1)
while True:
pre = mid[:]
shuffle(mid)
isdiff = False
for j in range(len(mid)):
if word[pre[j]] != word[mid[j]]:
isdiff = True
break
if isdiff:
break
newword = word[0]
for i in mid:
newword += word[i]
newword += word[-1]
return newword
def main():
tests = []
tests.append("A")
tests.append("I eat apple")
tests.append("A fox runs so fast that it suddenly die")
for test in tests:
print test
print midrand(test)
print
if __name__ == "__main__":
main()
|
76b55e9ff15f2e0d0b7ece7e0e063a3d4ffcbade | tests/helpers.py | tests/helpers.py | from unittest.mock import call
def calls_from(list_args):
return [call(*args) for args in list_args]
| from mock import call
def calls_from(list_args):
return [call(*args) for args in list_args]
| Load mock module from mock package instead of unittest to support Python prior to 3.3 | Load mock module from mock package instead of unittest to support Python prior to 3.3
| Python | mit | mina-asham/pictures-dedupe-and-rename | from unittest.mock import call
def calls_from(list_args):
return [call(*args) for args in list_args]
Load mock module from mock package instead of unittest to support Python prior to 3.3 | from mock import call
def calls_from(list_args):
return [call(*args) for args in list_args]
| <commit_before>from unittest.mock import call
def calls_from(list_args):
return [call(*args) for args in list_args]
<commit_msg>Load mock module from mock package instead of unittest to support Python prior to 3.3<commit_after> | from mock import call
def calls_from(list_args):
return [call(*args) for args in list_args]
| from unittest.mock import call
def calls_from(list_args):
return [call(*args) for args in list_args]
Load mock module from mock package instead of unittest to support Python prior to 3.3from mock import call
def calls_from(list_args):
return [call(*args) for args in list_args]
| <commit_before>from unittest.mock import call
def calls_from(list_args):
return [call(*args) for args in list_args]
<commit_msg>Load mock module from mock package instead of unittest to support Python prior to 3.3<commit_after>from mock import call
def calls_from(list_args):
return [call(*args) for args in list_args]
|
47f1d3bf2ef53fa9fef9eff46497ca02f366e3fb | nap/auth.py | nap/auth.py | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return http.Forbidden()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
| from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return response_class()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
| Allow control of response type for failing permit check | Allow control of response type for failing permit check
| Python | bsd-3-clause | limbera/django-nap | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return http.Forbidden()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
Allow control of response type for failing permit check | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return response_class()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
| <commit_before>from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return http.Forbidden()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
<commit_msg>Allow control of response type for failing permit check<commit_after> | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return response_class()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
| from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return http.Forbidden()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
Allow control of response type for failing permit checkfrom __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return response_class()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
| <commit_before>from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return http.Forbidden()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
<commit_msg>Allow control of response type for failing permit check<commit_after>from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return response_class()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
|
a34086d5bbd63d98953919c72d4eb4623063ad0c | piptools/repositories/minimal_upgrade.py | piptools/repositories/minimal_upgrade.py | # coding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .base import BaseRepository
class MinimalUpgradeRepository(BaseRepository):
"""
The MinimalUpgradeRepository uses a provided requirements file as a proxy
in front of a repository. If a requirement can be satisfied with
a version pinned in the requirements file, we use that version as the best
match. In all other cases, the proxied repository is used instead.
"""
def __init__(self, existing_pins, proxied_repository):
self.repository = proxied_repository
self.existing_pins = existing_pins
def clear_caches(self):
self.repository.clear_caches()
def freshen_build_caches(self):
self.repository.freshen_build_caches()
def find_best_match(self, ireq, prereleases=None):
existing_pin = self.existing_pins.get(ireq.req.project_name.lower())
if existing_pin and existing_pin.req.specs[0][1] in ireq.req:
return existing_pin
else:
return self.repository.find_best_match(ireq, prereleases)
def get_dependencies(self, ireq):
return self.repository.get_dependencies(ireq)
| # coding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .base import BaseRepository
class MinimalUpgradeRepository(BaseRepository):
"""
The MinimalUpgradeRepository uses a provided requirements file as a proxy
in front of a repository. If a requirement can be satisfied with
a version pinned in the requirements file, we use that version as the best
match. In all other cases, the proxied repository is used instead.
"""
def __init__(self, existing_pins, proxied_repository):
self.repository = proxied_repository
self.existing_pins = existing_pins
@property
def finder(self):
return self.repository.finder
@property
def session(self):
return self.repository.session
@property
def DEFAULT_INDEX_URL(self):
return self.repository.DEFAULT_INDEX_URL
def clear_caches(self):
self.repository.clear_caches()
def freshen_build_caches(self):
self.repository.freshen_build_caches()
def find_best_match(self, ireq, prereleases=None):
existing_pin = self.existing_pins.get(ireq.req.project_name.lower())
if existing_pin and existing_pin.req.specs[0][1] in ireq.req:
return existing_pin
else:
return self.repository.find_best_match(ireq, prereleases)
def get_dependencies(self, ireq):
return self.repository.get_dependencies(ireq)
| Add missing properties to pass through to the proxied repository. | Add missing properties to pass through to the proxied repository.
| Python | bsd-2-clause | suutari/prequ,suutari/prequ,suutari-ai/prequ | # coding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .base import BaseRepository
class MinimalUpgradeRepository(BaseRepository):
"""
The MinimalUpgradeRepository uses a provided requirements file as a proxy
in front of a repository. If a requirement can be satisfied with
a version pinned in the requirements file, we use that version as the best
match. In all other cases, the proxied repository is used instead.
"""
def __init__(self, existing_pins, proxied_repository):
self.repository = proxied_repository
self.existing_pins = existing_pins
def clear_caches(self):
self.repository.clear_caches()
def freshen_build_caches(self):
self.repository.freshen_build_caches()
def find_best_match(self, ireq, prereleases=None):
existing_pin = self.existing_pins.get(ireq.req.project_name.lower())
if existing_pin and existing_pin.req.specs[0][1] in ireq.req:
return existing_pin
else:
return self.repository.find_best_match(ireq, prereleases)
def get_dependencies(self, ireq):
return self.repository.get_dependencies(ireq)
Add missing properties to pass through to the proxied repository. | # coding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .base import BaseRepository
class MinimalUpgradeRepository(BaseRepository):
"""
The MinimalUpgradeRepository uses a provided requirements file as a proxy
in front of a repository. If a requirement can be satisfied with
a version pinned in the requirements file, we use that version as the best
match. In all other cases, the proxied repository is used instead.
"""
def __init__(self, existing_pins, proxied_repository):
self.repository = proxied_repository
self.existing_pins = existing_pins
@property
def finder(self):
return self.repository.finder
@property
def session(self):
return self.repository.session
@property
def DEFAULT_INDEX_URL(self):
return self.repository.DEFAULT_INDEX_URL
def clear_caches(self):
self.repository.clear_caches()
def freshen_build_caches(self):
self.repository.freshen_build_caches()
def find_best_match(self, ireq, prereleases=None):
existing_pin = self.existing_pins.get(ireq.req.project_name.lower())
if existing_pin and existing_pin.req.specs[0][1] in ireq.req:
return existing_pin
else:
return self.repository.find_best_match(ireq, prereleases)
def get_dependencies(self, ireq):
return self.repository.get_dependencies(ireq)
| <commit_before># coding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .base import BaseRepository
class MinimalUpgradeRepository(BaseRepository):
"""
The MinimalUpgradeRepository uses a provided requirements file as a proxy
in front of a repository. If a requirement can be satisfied with
a version pinned in the requirements file, we use that version as the best
match. In all other cases, the proxied repository is used instead.
"""
def __init__(self, existing_pins, proxied_repository):
self.repository = proxied_repository
self.existing_pins = existing_pins
def clear_caches(self):
self.repository.clear_caches()
def freshen_build_caches(self):
self.repository.freshen_build_caches()
def find_best_match(self, ireq, prereleases=None):
existing_pin = self.existing_pins.get(ireq.req.project_name.lower())
if existing_pin and existing_pin.req.specs[0][1] in ireq.req:
return existing_pin
else:
return self.repository.find_best_match(ireq, prereleases)
def get_dependencies(self, ireq):
return self.repository.get_dependencies(ireq)
<commit_msg>Add missing properties to pass through to the proxied repository.<commit_after> | # coding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .base import BaseRepository
class MinimalUpgradeRepository(BaseRepository):
"""
The MinimalUpgradeRepository uses a provided requirements file as a proxy
in front of a repository. If a requirement can be satisfied with
a version pinned in the requirements file, we use that version as the best
match. In all other cases, the proxied repository is used instead.
"""
def __init__(self, existing_pins, proxied_repository):
self.repository = proxied_repository
self.existing_pins = existing_pins
@property
def finder(self):
return self.repository.finder
@property
def session(self):
return self.repository.session
@property
def DEFAULT_INDEX_URL(self):
return self.repository.DEFAULT_INDEX_URL
def clear_caches(self):
self.repository.clear_caches()
def freshen_build_caches(self):
self.repository.freshen_build_caches()
def find_best_match(self, ireq, prereleases=None):
existing_pin = self.existing_pins.get(ireq.req.project_name.lower())
if existing_pin and existing_pin.req.specs[0][1] in ireq.req:
return existing_pin
else:
return self.repository.find_best_match(ireq, prereleases)
def get_dependencies(self, ireq):
return self.repository.get_dependencies(ireq)
| # coding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .base import BaseRepository
class MinimalUpgradeRepository(BaseRepository):
"""
The MinimalUpgradeRepository uses a provided requirements file as a proxy
in front of a repository. If a requirement can be satisfied with
a version pinned in the requirements file, we use that version as the best
match. In all other cases, the proxied repository is used instead.
"""
def __init__(self, existing_pins, proxied_repository):
self.repository = proxied_repository
self.existing_pins = existing_pins
def clear_caches(self):
self.repository.clear_caches()
def freshen_build_caches(self):
self.repository.freshen_build_caches()
def find_best_match(self, ireq, prereleases=None):
existing_pin = self.existing_pins.get(ireq.req.project_name.lower())
if existing_pin and existing_pin.req.specs[0][1] in ireq.req:
return existing_pin
else:
return self.repository.find_best_match(ireq, prereleases)
def get_dependencies(self, ireq):
return self.repository.get_dependencies(ireq)
Add missing properties to pass through to the proxied repository.# coding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .base import BaseRepository
class MinimalUpgradeRepository(BaseRepository):
"""
The MinimalUpgradeRepository uses a provided requirements file as a proxy
in front of a repository. If a requirement can be satisfied with
a version pinned in the requirements file, we use that version as the best
match. In all other cases, the proxied repository is used instead.
"""
def __init__(self, existing_pins, proxied_repository):
self.repository = proxied_repository
self.existing_pins = existing_pins
@property
def finder(self):
return self.repository.finder
@property
def session(self):
return self.repository.session
@property
def DEFAULT_INDEX_URL(self):
return self.repository.DEFAULT_INDEX_URL
def clear_caches(self):
self.repository.clear_caches()
def freshen_build_caches(self):
self.repository.freshen_build_caches()
def find_best_match(self, ireq, prereleases=None):
existing_pin = self.existing_pins.get(ireq.req.project_name.lower())
if existing_pin and existing_pin.req.specs[0][1] in ireq.req:
return existing_pin
else:
return self.repository.find_best_match(ireq, prereleases)
def get_dependencies(self, ireq):
return self.repository.get_dependencies(ireq)
| <commit_before># coding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .base import BaseRepository
class MinimalUpgradeRepository(BaseRepository):
"""
The MinimalUpgradeRepository uses a provided requirements file as a proxy
in front of a repository. If a requirement can be satisfied with
a version pinned in the requirements file, we use that version as the best
match. In all other cases, the proxied repository is used instead.
"""
def __init__(self, existing_pins, proxied_repository):
self.repository = proxied_repository
self.existing_pins = existing_pins
def clear_caches(self):
self.repository.clear_caches()
def freshen_build_caches(self):
self.repository.freshen_build_caches()
def find_best_match(self, ireq, prereleases=None):
existing_pin = self.existing_pins.get(ireq.req.project_name.lower())
if existing_pin and existing_pin.req.specs[0][1] in ireq.req:
return existing_pin
else:
return self.repository.find_best_match(ireq, prereleases)
def get_dependencies(self, ireq):
return self.repository.get_dependencies(ireq)
<commit_msg>Add missing properties to pass through to the proxied repository.<commit_after># coding: utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .base import BaseRepository
class MinimalUpgradeRepository(BaseRepository):
"""
The MinimalUpgradeRepository uses a provided requirements file as a proxy
in front of a repository. If a requirement can be satisfied with
a version pinned in the requirements file, we use that version as the best
match. In all other cases, the proxied repository is used instead.
"""
def __init__(self, existing_pins, proxied_repository):
self.repository = proxied_repository
self.existing_pins = existing_pins
@property
def finder(self):
return self.repository.finder
@property
def session(self):
return self.repository.session
@property
def DEFAULT_INDEX_URL(self):
return self.repository.DEFAULT_INDEX_URL
def clear_caches(self):
self.repository.clear_caches()
def freshen_build_caches(self):
self.repository.freshen_build_caches()
def find_best_match(self, ireq, prereleases=None):
existing_pin = self.existing_pins.get(ireq.req.project_name.lower())
if existing_pin and existing_pin.req.specs[0][1] in ireq.req:
return existing_pin
else:
return self.repository.find_best_match(ireq, prereleases)
def get_dependencies(self, ireq):
return self.repository.get_dependencies(ireq)
|
e2452a46766abdef354d9e04f6fb61eae51bf6ee | yepes/models.py | yepes/models.py | # -*- coding:utf-8 -*-
from django import template
template.add_to_builtins('yepes.defaultfilters')
template.add_to_builtins('yepes.defaulttags')
| # -*- coding:utf-8 -*-
from __future__ import absolute_import
import types
from django import template
from django.db import connections
from django.db.models.manager import Manager
from django.db.models.query import QuerySet
from django.utils import six
template.add_to_builtins('yepes.defaultfilters')
template.add_to_builtins('yepes.defaulttags')
def in_batches(self, batch_size):
"""
Makes an iterator that returns batches of the indicated size with the
results from applying this QuerySet to the database.
WARNING: Each batch is an evaluated QuerySet, so its results are already
cached.
"""
start = 0
stop = batch_size
batch = self[start:stop]
while batch:
yield batch
start += batch_size
stop += batch_size
batch = self[start:stop]
if six.PY2:
in_batches = types.MethodType(in_batches, None, QuerySet)
setattr(QuerySet, 'in_batches', in_batches)
def in_batches(self, *args, **kwargs):
return self.get_queryset().in_batches(*args, **kwargs)
def truncate(self):
"""
Quickly removes all records of the Manager's model and tries to restart
sequences owned by fields of the truncated model.
NOTE: Sequence restarting currently is only supported by postgresql backend.
"""
qs = self.get_queryset()
qs._for_write = True
conn = connections[qs.db]
statements = self.statements.get(conn.vendor)
if statements is None:
statements = self.statements['default']
opts = self.model._meta
cursor = conn.cursor()
cursor.execute(statements['truncate'].format(table=opts.db_table))
if six.PY2:
in_batches = types.MethodType(in_batches, None, Manager)
truncate = types.MethodType(truncate, None, Manager)
setattr(Manager, 'in_batches', in_batches)
setattr(Manager, 'statements', {
'postgresql': {
'truncate': 'TRUNCATE {table} RESTART IDENTITY;',
},
'mysql': {
'truncate': 'TRUNCATE {table};',
},
'default': {
'truncate': 'DELETE FROM {table};',
},
})
setattr(Manager, 'truncate', truncate)
| Implement truncate() method for Manager and in_batches() method for QuerySet | Implement truncate() method for Manager and in_batches() method for QuerySet
| Python | bsd-3-clause | samuelmaudo/yepes,samuelmaudo/yepes,samuelmaudo/yepes,samuelmaudo/yepes | # -*- coding:utf-8 -*-
from django import template
template.add_to_builtins('yepes.defaultfilters')
template.add_to_builtins('yepes.defaulttags')
Implement truncate() method for Manager and in_batches() method for QuerySet | # -*- coding:utf-8 -*-
from __future__ import absolute_import
import types
from django import template
from django.db import connections
from django.db.models.manager import Manager
from django.db.models.query import QuerySet
from django.utils import six
template.add_to_builtins('yepes.defaultfilters')
template.add_to_builtins('yepes.defaulttags')
def in_batches(self, batch_size):
"""
Makes an iterator that returns batches of the indicated size with the
results from applying this QuerySet to the database.
WARNING: Each batch is an evaluated QuerySet, so its results are already
cached.
"""
start = 0
stop = batch_size
batch = self[start:stop]
while batch:
yield batch
start += batch_size
stop += batch_size
batch = self[start:stop]
if six.PY2:
in_batches = types.MethodType(in_batches, None, QuerySet)
setattr(QuerySet, 'in_batches', in_batches)
def in_batches(self, *args, **kwargs):
return self.get_queryset().in_batches(*args, **kwargs)
def truncate(self):
"""
Quickly removes all records of the Manager's model and tries to restart
sequences owned by fields of the truncated model.
NOTE: Sequence restarting currently is only supported by postgresql backend.
"""
qs = self.get_queryset()
qs._for_write = True
conn = connections[qs.db]
statements = self.statements.get(conn.vendor)
if statements is None:
statements = self.statements['default']
opts = self.model._meta
cursor = conn.cursor()
cursor.execute(statements['truncate'].format(table=opts.db_table))
if six.PY2:
in_batches = types.MethodType(in_batches, None, Manager)
truncate = types.MethodType(truncate, None, Manager)
setattr(Manager, 'in_batches', in_batches)
setattr(Manager, 'statements', {
'postgresql': {
'truncate': 'TRUNCATE {table} RESTART IDENTITY;',
},
'mysql': {
'truncate': 'TRUNCATE {table};',
},
'default': {
'truncate': 'DELETE FROM {table};',
},
})
setattr(Manager, 'truncate', truncate)
| <commit_before># -*- coding:utf-8 -*-
from django import template
template.add_to_builtins('yepes.defaultfilters')
template.add_to_builtins('yepes.defaulttags')
<commit_msg>Implement truncate() method for Manager and in_batches() method for QuerySet<commit_after> | # -*- coding:utf-8 -*-
from __future__ import absolute_import
import types
from django import template
from django.db import connections
from django.db.models.manager import Manager
from django.db.models.query import QuerySet
from django.utils import six
template.add_to_builtins('yepes.defaultfilters')
template.add_to_builtins('yepes.defaulttags')
def in_batches(self, batch_size):
"""
Makes an iterator that returns batches of the indicated size with the
results from applying this QuerySet to the database.
WARNING: Each batch is an evaluated QuerySet, so its results are already
cached.
"""
start = 0
stop = batch_size
batch = self[start:stop]
while batch:
yield batch
start += batch_size
stop += batch_size
batch = self[start:stop]
if six.PY2:
in_batches = types.MethodType(in_batches, None, QuerySet)
setattr(QuerySet, 'in_batches', in_batches)
def in_batches(self, *args, **kwargs):
return self.get_queryset().in_batches(*args, **kwargs)
def truncate(self):
"""
Quickly removes all records of the Manager's model and tries to restart
sequences owned by fields of the truncated model.
NOTE: Sequence restarting currently is only supported by postgresql backend.
"""
qs = self.get_queryset()
qs._for_write = True
conn = connections[qs.db]
statements = self.statements.get(conn.vendor)
if statements is None:
statements = self.statements['default']
opts = self.model._meta
cursor = conn.cursor()
cursor.execute(statements['truncate'].format(table=opts.db_table))
if six.PY2:
in_batches = types.MethodType(in_batches, None, Manager)
truncate = types.MethodType(truncate, None, Manager)
setattr(Manager, 'in_batches', in_batches)
setattr(Manager, 'statements', {
'postgresql': {
'truncate': 'TRUNCATE {table} RESTART IDENTITY;',
},
'mysql': {
'truncate': 'TRUNCATE {table};',
},
'default': {
'truncate': 'DELETE FROM {table};',
},
})
setattr(Manager, 'truncate', truncate)
| # -*- coding:utf-8 -*-
from django import template
template.add_to_builtins('yepes.defaultfilters')
template.add_to_builtins('yepes.defaulttags')
Implement truncate() method for Manager and in_batches() method for QuerySet# -*- coding:utf-8 -*-
from __future__ import absolute_import
import types
from django import template
from django.db import connections
from django.db.models.manager import Manager
from django.db.models.query import QuerySet
from django.utils import six
template.add_to_builtins('yepes.defaultfilters')
template.add_to_builtins('yepes.defaulttags')
def in_batches(self, batch_size):
"""
Makes an iterator that returns batches of the indicated size with the
results from applying this QuerySet to the database.
WARNING: Each batch is an evaluated QuerySet, so its results are already
cached.
"""
start = 0
stop = batch_size
batch = self[start:stop]
while batch:
yield batch
start += batch_size
stop += batch_size
batch = self[start:stop]
if six.PY2:
in_batches = types.MethodType(in_batches, None, QuerySet)
setattr(QuerySet, 'in_batches', in_batches)
def in_batches(self, *args, **kwargs):
return self.get_queryset().in_batches(*args, **kwargs)
def truncate(self):
"""
Quickly removes all records of the Manager's model and tries to restart
sequences owned by fields of the truncated model.
NOTE: Sequence restarting currently is only supported by postgresql backend.
"""
qs = self.get_queryset()
qs._for_write = True
conn = connections[qs.db]
statements = self.statements.get(conn.vendor)
if statements is None:
statements = self.statements['default']
opts = self.model._meta
cursor = conn.cursor()
cursor.execute(statements['truncate'].format(table=opts.db_table))
if six.PY2:
in_batches = types.MethodType(in_batches, None, Manager)
truncate = types.MethodType(truncate, None, Manager)
setattr(Manager, 'in_batches', in_batches)
setattr(Manager, 'statements', {
'postgresql': {
'truncate': 'TRUNCATE {table} RESTART IDENTITY;',
},
'mysql': {
'truncate': 'TRUNCATE {table};',
},
'default': {
'truncate': 'DELETE FROM {table};',
},
})
setattr(Manager, 'truncate', truncate)
| <commit_before># -*- coding:utf-8 -*-
from django import template
template.add_to_builtins('yepes.defaultfilters')
template.add_to_builtins('yepes.defaulttags')
<commit_msg>Implement truncate() method for Manager and in_batches() method for QuerySet<commit_after># -*- coding:utf-8 -*-
from __future__ import absolute_import
import types
from django import template
from django.db import connections
from django.db.models.manager import Manager
from django.db.models.query import QuerySet
from django.utils import six
template.add_to_builtins('yepes.defaultfilters')
template.add_to_builtins('yepes.defaulttags')
def in_batches(self, batch_size):
"""
Makes an iterator that returns batches of the indicated size with the
results from applying this QuerySet to the database.
WARNING: Each batch is an evaluated QuerySet, so its results are already
cached.
"""
start = 0
stop = batch_size
batch = self[start:stop]
while batch:
yield batch
start += batch_size
stop += batch_size
batch = self[start:stop]
if six.PY2:
in_batches = types.MethodType(in_batches, None, QuerySet)
setattr(QuerySet, 'in_batches', in_batches)
def in_batches(self, *args, **kwargs):
return self.get_queryset().in_batches(*args, **kwargs)
def truncate(self):
"""
Quickly removes all records of the Manager's model and tries to restart
sequences owned by fields of the truncated model.
NOTE: Sequence restarting currently is only supported by postgresql backend.
"""
qs = self.get_queryset()
qs._for_write = True
conn = connections[qs.db]
statements = self.statements.get(conn.vendor)
if statements is None:
statements = self.statements['default']
opts = self.model._meta
cursor = conn.cursor()
cursor.execute(statements['truncate'].format(table=opts.db_table))
if six.PY2:
in_batches = types.MethodType(in_batches, None, Manager)
truncate = types.MethodType(truncate, None, Manager)
setattr(Manager, 'in_batches', in_batches)
setattr(Manager, 'statements', {
'postgresql': {
'truncate': 'TRUNCATE {table} RESTART IDENTITY;',
},
'mysql': {
'truncate': 'TRUNCATE {table};',
},
'default': {
'truncate': 'DELETE FROM {table};',
},
})
setattr(Manager, 'truncate', truncate)
|
7717aad873f7cc68de26618c49d24cd5dc6202c5 | dodocs/__init__.py | dodocs/__init__.py | """Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import os
import sys
import colorama
from dodocs.cmdline import parse
from dodocs.logger import setLogger
__version__ = "0.0.1"
colorama.init(autoreset=True)
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
log = setLogger(args)
if "func" in args:
args.func(args)
log.debug("Finished")
else:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main(sys.argv[1:] + ["list"])
else:
# in the other cases suggest to run -h
msg = (colorama.Fore.RED + "Please provide a valid command.\n"
"Type\n " + os.path.split(sys.argv[0])[1])
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
log.error(msg)
| """Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import os
import sys
from dodocs.cmdline import parse
import dodocs.logger as dlog
__version__ = "0.0.1"
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
dlog.setLogger(args)
# make sure to reset the subcommand name
dlog.set_subcommand(args)
log = dlog.getLogger()
if "func" in args:
args.func(args)
log.debug("Finished")
return 0
else:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main(sys.argv[1:] + ["list"])
else:
# in the other cases suggest to run -h
msg = ("Please provide a valid command.\n"
"Type\n " + os.path.split(sys.argv[0])[1])
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
log.error(msg)
return 1
| Remove colorama and update the logger interface | Remove colorama and update the logger interface
| Python | mit | montefra/dodocs | """Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import os
import sys
import colorama
from dodocs.cmdline import parse
from dodocs.logger import setLogger
__version__ = "0.0.1"
colorama.init(autoreset=True)
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
log = setLogger(args)
if "func" in args:
args.func(args)
log.debug("Finished")
else:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main(sys.argv[1:] + ["list"])
else:
# in the other cases suggest to run -h
msg = (colorama.Fore.RED + "Please provide a valid command.\n"
"Type\n " + os.path.split(sys.argv[0])[1])
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
log.error(msg)
Remove colorama and update the logger interface | """Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import os
import sys
from dodocs.cmdline import parse
import dodocs.logger as dlog
__version__ = "0.0.1"
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
dlog.setLogger(args)
# make sure to reset the subcommand name
dlog.set_subcommand(args)
log = dlog.getLogger()
if "func" in args:
args.func(args)
log.debug("Finished")
return 0
else:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main(sys.argv[1:] + ["list"])
else:
# in the other cases suggest to run -h
msg = ("Please provide a valid command.\n"
"Type\n " + os.path.split(sys.argv[0])[1])
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
log.error(msg)
return 1
| <commit_before>"""Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import os
import sys
import colorama
from dodocs.cmdline import parse
from dodocs.logger import setLogger
__version__ = "0.0.1"
colorama.init(autoreset=True)
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
log = setLogger(args)
if "func" in args:
args.func(args)
log.debug("Finished")
else:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main(sys.argv[1:] + ["list"])
else:
# in the other cases suggest to run -h
msg = (colorama.Fore.RED + "Please provide a valid command.\n"
"Type\n " + os.path.split(sys.argv[0])[1])
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
log.error(msg)
<commit_msg>Remove colorama and update the logger interface<commit_after> | """Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import os
import sys
from dodocs.cmdline import parse
import dodocs.logger as dlog
__version__ = "0.0.1"
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
dlog.setLogger(args)
# make sure to reset the subcommand name
dlog.set_subcommand(args)
log = dlog.getLogger()
if "func" in args:
args.func(args)
log.debug("Finished")
return 0
else:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main(sys.argv[1:] + ["list"])
else:
# in the other cases suggest to run -h
msg = ("Please provide a valid command.\n"
"Type\n " + os.path.split(sys.argv[0])[1])
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
log.error(msg)
return 1
| """Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import os
import sys
import colorama
from dodocs.cmdline import parse
from dodocs.logger import setLogger
__version__ = "0.0.1"
colorama.init(autoreset=True)
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
log = setLogger(args)
if "func" in args:
args.func(args)
log.debug("Finished")
else:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main(sys.argv[1:] + ["list"])
else:
# in the other cases suggest to run -h
msg = (colorama.Fore.RED + "Please provide a valid command.\n"
"Type\n " + os.path.split(sys.argv[0])[1])
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
log.error(msg)
Remove colorama and update the logger interface"""Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import os
import sys
from dodocs.cmdline import parse
import dodocs.logger as dlog
__version__ = "0.0.1"
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
dlog.setLogger(args)
# make sure to reset the subcommand name
dlog.set_subcommand(args)
log = dlog.getLogger()
if "func" in args:
args.func(args)
log.debug("Finished")
return 0
else:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main(sys.argv[1:] + ["list"])
else:
# in the other cases suggest to run -h
msg = ("Please provide a valid command.\n"
"Type\n " + os.path.split(sys.argv[0])[1])
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
log.error(msg)
return 1
| <commit_before>"""Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import os
import sys
import colorama
from dodocs.cmdline import parse
from dodocs.logger import setLogger
__version__ = "0.0.1"
colorama.init(autoreset=True)
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
log = setLogger(args)
if "func" in args:
args.func(args)
log.debug("Finished")
else:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main(sys.argv[1:] + ["list"])
else:
# in the other cases suggest to run -h
msg = (colorama.Fore.RED + "Please provide a valid command.\n"
"Type\n " + os.path.split(sys.argv[0])[1])
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
log.error(msg)
<commit_msg>Remove colorama and update the logger interface<commit_after>"""Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import os
import sys
from dodocs.cmdline import parse
import dodocs.logger as dlog
__version__ = "0.0.1"
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command line arguments
"""
args = parse(argv=argv)
dlog.setLogger(args)
# make sure to reset the subcommand name
dlog.set_subcommand(args)
log = dlog.getLogger()
if "func" in args:
args.func(args)
log.debug("Finished")
return 0
else:
# defaults profile to list
if args.subparser_name == 'profile' and args.profile_cmd is None:
main(sys.argv[1:] + ["list"])
else:
# in the other cases suggest to run -h
msg = ("Please provide a valid command.\n"
"Type\n " + os.path.split(sys.argv[0])[1])
if args.subparser_name is not None:
msg += " " + args.subparser_name
msg += ' -h'
log.error(msg)
return 1
|
b435f5c07a39874195781d928b7451d2765c3cf9 | test-project/testproject/models.py | test-project/testproject/models.py | import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
backref,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
address = relationship("Address", uselist=False, backref="user")
def __init__(self, name):
self.name = name
def __str__(self):
return u"%s" % self.name
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
description = Column(Text, unique=True)
user_id = Column(Integer, ForeignKey('users.id'))
def __init__(self, description):
self.description = description
def __str__(self):
return "%s" % (self.id)
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
| from __future__ import absolute_import, unicode_literals
import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
backref,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
address = relationship("Address", uselist=False, backref="user")
def __init__(self, name):
self.name = name
def __str__(self):
return "%s" % self.name
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
description = Column(Text, unique=True)
user_id = Column(Integer, ForeignKey('users.id'))
def __init__(self, description):
self.description = description
def __str__(self):
return "%s" % (self.id)
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
| Fix to unicode problem in 3.2 | Fix to unicode problem in 3.2
| Python | mit | RedTurtle/sqlalchemy-datatables,Pegase745/sqlalchemy-datatables | import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
backref,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
address = relationship("Address", uselist=False, backref="user")
def __init__(self, name):
self.name = name
def __str__(self):
return u"%s" % self.name
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
description = Column(Text, unique=True)
user_id = Column(Integer, ForeignKey('users.id'))
def __init__(self, description):
self.description = description
def __str__(self):
return "%s" % (self.id)
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
Fix to unicode problem in 3.2 | from __future__ import absolute_import, unicode_literals
import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
backref,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
address = relationship("Address", uselist=False, backref="user")
def __init__(self, name):
self.name = name
def __str__(self):
return "%s" % self.name
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
description = Column(Text, unique=True)
user_id = Column(Integer, ForeignKey('users.id'))
def __init__(self, description):
self.description = description
def __str__(self):
return "%s" % (self.id)
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
| <commit_before>import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
backref,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
address = relationship("Address", uselist=False, backref="user")
def __init__(self, name):
self.name = name
def __str__(self):
return u"%s" % self.name
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
description = Column(Text, unique=True)
user_id = Column(Integer, ForeignKey('users.id'))
def __init__(self, description):
self.description = description
def __str__(self):
return "%s" % (self.id)
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
<commit_msg>Fix to unicode problem in 3.2<commit_after> | from __future__ import absolute_import, unicode_literals
import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
backref,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
address = relationship("Address", uselist=False, backref="user")
def __init__(self, name):
self.name = name
def __str__(self):
return "%s" % self.name
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
description = Column(Text, unique=True)
user_id = Column(Integer, ForeignKey('users.id'))
def __init__(self, description):
self.description = description
def __str__(self):
return "%s" % (self.id)
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
| import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
backref,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
address = relationship("Address", uselist=False, backref="user")
def __init__(self, name):
self.name = name
def __str__(self):
return u"%s" % self.name
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
description = Column(Text, unique=True)
user_id = Column(Integer, ForeignKey('users.id'))
def __init__(self, description):
self.description = description
def __str__(self):
return "%s" % (self.id)
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
Fix to unicode problem in 3.2from __future__ import absolute_import, unicode_literals
import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
backref,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
address = relationship("Address", uselist=False, backref="user")
def __init__(self, name):
self.name = name
def __str__(self):
return "%s" % self.name
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
description = Column(Text, unique=True)
user_id = Column(Integer, ForeignKey('users.id'))
def __init__(self, description):
self.description = description
def __str__(self):
return "%s" % (self.id)
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
| <commit_before>import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
backref,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
address = relationship("Address", uselist=False, backref="user")
def __init__(self, name):
self.name = name
def __str__(self):
return u"%s" % self.name
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
description = Column(Text, unique=True)
user_id = Column(Integer, ForeignKey('users.id'))
def __init__(self, description):
self.description = description
def __str__(self):
return "%s" % (self.id)
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
<commit_msg>Fix to unicode problem in 3.2<commit_after>from __future__ import absolute_import, unicode_literals
import datetime, json
from sqlalchemy import (
Column,
Integer,
Text,
DateTime,
ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
backref,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
address = relationship("Address", uselist=False, backref="user")
def __init__(self, name):
self.name = name
def __str__(self):
return "%s" % self.name
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
description = Column(Text, unique=True)
user_id = Column(Integer, ForeignKey('users.id'))
def __init__(self, description):
self.description = description
def __str__(self):
return "%s" % (self.id)
def __repr__(self):
return '<%s#%s>' % (self.__class__.__name__, self.id)
|
9f1ec5e42d66477fc884bf5ea853d145c0adeb4f | tests/test_fs.py | tests/test_fs.py | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
| from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
assert Path("/") < Path("/a")
| Add test case for “/“ | Add test case for “/“ | Python | mit | andrewguy9/farmfs,andrewguy9/farmfs | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
Add test case for “/“ | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
assert Path("/") < Path("/a")
| <commit_before>from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
<commit_msg>Add test case for “/“ <commit_after> | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
assert Path("/") < Path("/a")
| from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
Add test case for “/“ from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
assert Path("/") < Path("/a")
| <commit_before>from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
<commit_msg>Add test case for “/“ <commit_after>from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
assert Path("/") < Path("/a")
|
7311b134379087dd7f181682b9b58aeb8d794e6c | examples/basic_siggen.py | examples/basic_siggen.py | from pymoku import Moku, ValueOutOfRangeException
from pymoku.instruments import *
import time, logging
import matplotlib
import matplotlib.pyplot as plt
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.DEBUG)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name("Aqua")
i = m.discover_instrument()
if i is None or i.type != 'signal_generator':
print "No or wrong instrument deployed"
i = SignalGenerator()
m.attach_instrument(i)
else:
print "Attached to existing Signal Generator"
i.set_defaults()
i.synth_sinewave(1, 1.0, 1000000)
i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3)
i.commit()
try:
while True:
try:
i.out1_offset += 0.05
except ValueOutOfRangeException:
i.out1_offset = -1
print i.out1_offset
i.commit()
finally:
m.close()
| from pymoku import Moku, ValueOutOfRangeException
from pymoku.instruments import *
import time, logging
import matplotlib
import matplotlib.pyplot as plt
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.DEBUG)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name("example")
i = m.discover_instrument()
if i is None or i.type != 'signal_generator':
print "No or wrong instrument deployed"
i = SignalGenerator()
m.attach_instrument(i)
else:
print "Attached to existing Signal Generator"
i.set_defaults()
try:
i.synth_sinewave(1, 1.0, 1000000)
i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3)
i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10)
i.commit()
finally:
m.close()
| Tidy up basic siggen example | Siggen: Tidy up basic siggen example
| Python | mit | benizl/pymoku,liquidinstruments/pymoku | from pymoku import Moku, ValueOutOfRangeException
from pymoku.instruments import *
import time, logging
import matplotlib
import matplotlib.pyplot as plt
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.DEBUG)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name("Aqua")
i = m.discover_instrument()
if i is None or i.type != 'signal_generator':
print "No or wrong instrument deployed"
i = SignalGenerator()
m.attach_instrument(i)
else:
print "Attached to existing Signal Generator"
i.set_defaults()
i.synth_sinewave(1, 1.0, 1000000)
i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3)
i.commit()
try:
while True:
try:
i.out1_offset += 0.05
except ValueOutOfRangeException:
i.out1_offset = -1
print i.out1_offset
i.commit()
finally:
m.close()
Siggen: Tidy up basic siggen example | from pymoku import Moku, ValueOutOfRangeException
from pymoku.instruments import *
import time, logging
import matplotlib
import matplotlib.pyplot as plt
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.DEBUG)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name("example")
i = m.discover_instrument()
if i is None or i.type != 'signal_generator':
print "No or wrong instrument deployed"
i = SignalGenerator()
m.attach_instrument(i)
else:
print "Attached to existing Signal Generator"
i.set_defaults()
try:
i.synth_sinewave(1, 1.0, 1000000)
i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3)
i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10)
i.commit()
finally:
m.close()
| <commit_before>from pymoku import Moku, ValueOutOfRangeException
from pymoku.instruments import *
import time, logging
import matplotlib
import matplotlib.pyplot as plt
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.DEBUG)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name("Aqua")
i = m.discover_instrument()
if i is None or i.type != 'signal_generator':
print "No or wrong instrument deployed"
i = SignalGenerator()
m.attach_instrument(i)
else:
print "Attached to existing Signal Generator"
i.set_defaults()
i.synth_sinewave(1, 1.0, 1000000)
i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3)
i.commit()
try:
while True:
try:
i.out1_offset += 0.05
except ValueOutOfRangeException:
i.out1_offset = -1
print i.out1_offset
i.commit()
finally:
m.close()
<commit_msg>Siggen: Tidy up basic siggen example<commit_after> | from pymoku import Moku, ValueOutOfRangeException
from pymoku.instruments import *
import time, logging
import matplotlib
import matplotlib.pyplot as plt
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.DEBUG)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name("example")
i = m.discover_instrument()
if i is None or i.type != 'signal_generator':
print "No or wrong instrument deployed"
i = SignalGenerator()
m.attach_instrument(i)
else:
print "Attached to existing Signal Generator"
i.set_defaults()
try:
i.synth_sinewave(1, 1.0, 1000000)
i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3)
i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10)
i.commit()
finally:
m.close()
| from pymoku import Moku, ValueOutOfRangeException
from pymoku.instruments import *
import time, logging
import matplotlib
import matplotlib.pyplot as plt
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.DEBUG)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name("Aqua")
i = m.discover_instrument()
if i is None or i.type != 'signal_generator':
print "No or wrong instrument deployed"
i = SignalGenerator()
m.attach_instrument(i)
else:
print "Attached to existing Signal Generator"
i.set_defaults()
i.synth_sinewave(1, 1.0, 1000000)
i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3)
i.commit()
try:
while True:
try:
i.out1_offset += 0.05
except ValueOutOfRangeException:
i.out1_offset = -1
print i.out1_offset
i.commit()
finally:
m.close()
Siggen: Tidy up basic siggen examplefrom pymoku import Moku, ValueOutOfRangeException
from pymoku.instruments import *
import time, logging
import matplotlib
import matplotlib.pyplot as plt
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.DEBUG)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name("example")
i = m.discover_instrument()
if i is None or i.type != 'signal_generator':
print "No or wrong instrument deployed"
i = SignalGenerator()
m.attach_instrument(i)
else:
print "Attached to existing Signal Generator"
i.set_defaults()
try:
i.synth_sinewave(1, 1.0, 1000000)
i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3)
i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10)
i.commit()
finally:
m.close()
| <commit_before>from pymoku import Moku, ValueOutOfRangeException
from pymoku.instruments import *
import time, logging
import matplotlib
import matplotlib.pyplot as plt
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.DEBUG)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name("Aqua")
i = m.discover_instrument()
if i is None or i.type != 'signal_generator':
print "No or wrong instrument deployed"
i = SignalGenerator()
m.attach_instrument(i)
else:
print "Attached to existing Signal Generator"
i.set_defaults()
i.synth_sinewave(1, 1.0, 1000000)
i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3)
i.commit()
try:
while True:
try:
i.out1_offset += 0.05
except ValueOutOfRangeException:
i.out1_offset = -1
print i.out1_offset
i.commit()
finally:
m.close()
<commit_msg>Siggen: Tidy up basic siggen example<commit_after>from pymoku import Moku, ValueOutOfRangeException
from pymoku.instruments import *
import time, logging
import matplotlib
import matplotlib.pyplot as plt
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.DEBUG)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku.get_by_name("example")
i = m.discover_instrument()
if i is None or i.type != 'signal_generator':
print "No or wrong instrument deployed"
i = SignalGenerator()
m.attach_instrument(i)
else:
print "Attached to existing Signal Generator"
i.set_defaults()
try:
i.synth_sinewave(1, 1.0, 1000000)
i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3)
i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10)
i.commit()
finally:
m.close()
|
379e99a672537776ac0e160999967b5efce29305 | tweepy/media.py | tweepy/media.py | # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
| # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width", "alt_text"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
self.alt_text = data.get("alt_text")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
| Add alt_text field for Media | Add alt_text field for Media
| Python | mit | svven/tweepy,tweepy/tweepy | # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
Add alt_text field for Media | # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width", "alt_text"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
self.alt_text = data.get("alt_text")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
| <commit_before># Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
<commit_msg>Add alt_text field for Media<commit_after> | # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width", "alt_text"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
self.alt_text = data.get("alt_text")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
| # Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
Add alt_text field for Media# Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width", "alt_text"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
self.alt_text = data.get("alt_text")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
| <commit_before># Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
<commit_msg>Add alt_text field for Media<commit_after># Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.
from tweepy.mixins import DataMapping
class Media(DataMapping):
__slots__ = (
"data", "media_key", "type", "duration_ms", "height",
"non_public_metrics", "organic_metrics", "preview_image_url",
"promoted_metrics", "public_metrics", "width", "alt_text"
)
def __init__(self, data):
self.data = data
self.media_key = data["media_key"]
self.type = data["type"]
self.duration_ms = data.get("duration_ms")
self.height = data.get("height")
self.non_public_metrics = data.get("non_public_metrics")
self.organic_metrics = data.get("organic_metrics")
self.preview_image_url = data.get("preview_image_url")
self.promoted_metrics = data.get("promoted_metrics")
self.public_metrics = data.get("public_metrics")
self.width = data.get("width")
self.alt_text = data.get("alt_text")
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.media_key == other.media_key
return NotImplemented
def __hash__(self):
return hash(self.media_key)
def __repr__(self):
return f"<Media media_key={self.media_key} type={self.type}>"
|
09d78bb23ffba9d1d709a3ba5cbabbe84a9b1978 | server/macros/currency_usd_to_cad.py | server/macros/currency_usd_to_cad.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
desks = ['SPORTS DESK', 'POLITICS']
| # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
| Delete the desks settings for macro | fix(macro): Delete the desks settings for macro
| Python | agpl-3.0 | pavlovicnemanja/superdesk,amagdas/superdesk,verifiedpixel/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,plamut/superdesk,marwoodandrew/superdesk,petrjasek/superdesk,fritzSF/superdesk,petrjasek/superdesk-ntb,verifiedpixel/superdesk,marwoodandrew/superdesk,superdesk/superdesk-aap,verifiedpixel/superdesk,superdesk/superdesk,akintolga/superdesk,sivakuna-aap/superdesk,sivakuna-aap/superdesk,liveblog/superdesk,pavlovicnemanja92/superdesk,superdesk/superdesk-ntb,ancafarcas/superdesk,hlmnrmr/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,akintolga/superdesk,marwoodandrew/superdesk-aap,ioanpocol/superdesk,liveblog/superdesk,pavlovicnemanja/superdesk,darconny/superdesk,fritzSF/superdesk,pavlovicnemanja/superdesk,pavlovicnemanja92/superdesk,amagdas/superdesk,liveblog/superdesk,thnkloud9/superdesk,superdesk/superdesk,pavlovicnemanja/superdesk,plamut/superdesk,mdhaman/superdesk,darconny/superdesk,akintolga/superdesk-aap,amagdas/superdesk,liveblog/superdesk,gbbr/superdesk,petrjasek/superdesk,superdesk/superdesk-ntb,hlmnrmr/superdesk,verifiedpixel/superdesk,superdesk/superdesk-aap,superdesk/superdesk-aap,marwoodandrew/superdesk-aap,pavlovicnemanja92/superdesk,hlmnrmr/superdesk,ioanpocol/superdesk-ntb,marwoodandrew/superdesk-aap,mdhaman/superdesk-aap,ancafarcas/superdesk,verifiedpixel/superdesk,marwoodandrew/superdesk,petrjasek/superdesk-ntb,mdhaman/superdesk,fritzSF/superdesk,pavlovicnemanja92/superdesk,mdhaman/superdesk,akintolga/superdesk-aap,plamut/superdesk,petrjasek/superdesk-ntb,sjunaid/superdesk,akintolga/superdesk-aap,amagdas/superdesk,mdhaman/superdesk-aap,ioanpocol/superdesk,gbbr/superdesk,Aca-jov/superdesk,akintolga/superdesk,marwoodandrew/superdesk,plamut/superdesk,darconny/superdesk,marwoodandrew/superdesk,amagdas/superdesk,fritzSF/superdesk,ioanpocol/superdesk-ntb,sjunaid/superdesk,ancafarcas/superdesk,marwoodandrew/superdesk-aap,petrjasek/superdesk-ntb,mugurrus/superdesk,superdesk/superdesk-aap,gbbr/superdesk,Aca-jov/superdesk,thnkloud9/superdesk,superdesk/superdesk-ntb,superdesk/superdesk-ntb,Aca-jov/superdesk,superdesk/superdesk,thnkloud9/superdesk,akintolga/superdesk,ioanpocol/superdesk,akintolga/superdesk-aap,mugurrus/superdesk,sivakuna-aap/superdesk,mugurrus/superdesk,superdesk/superdesk,liveblog/superdesk,akintolga/superdesk,petrjasek/superdesk,fritzSF/superdesk,sjunaid/superdesk,plamut/superdesk,petrjasek/superdesk,pavlovicnemanja92/superdesk,ioanpocol/superdesk-ntb | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
desks = ['SPORTS DESK', 'POLITICS']
fix(macro): Delete the desks settings for macro | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
| <commit_before># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
desks = ['SPORTS DESK', 'POLITICS']
<commit_msg>fix(macro): Delete the desks settings for macro<commit_after> | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
| # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
desks = ['SPORTS DESK', 'POLITICS']
fix(macro): Delete the desks settings for macro# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
| <commit_before># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
desks = ['SPORTS DESK', 'POLITICS']
<commit_msg>fix(macro): Delete the desks settings for macro<commit_after># -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
|
153bc6edf9a450d6fb585ba73699e7b37e7bb6b8 | skimage/viewer/qt/__init__.py | skimage/viewer/qt/__init__.py | import os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
qt_api = 'none'
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
os.environ['QT_API'] = qt_api
| import os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
qt_api = None
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
os.environ['QT_API'] = qt_api
| Use None instead of 'none' for qt backend | Use None instead of 'none' for qt backend
| Python | bsd-3-clause | michaelaye/scikit-image,almarklein/scikit-image,jwiggins/scikit-image,pratapvardhan/scikit-image,ClinicalGraphics/scikit-image,paalge/scikit-image,warmspringwinds/scikit-image,vighneshbirodkar/scikit-image,newville/scikit-image,chriscrosscutler/scikit-image,ClinicalGraphics/scikit-image,blink1073/scikit-image,pratapvardhan/scikit-image,robintw/scikit-image,ajaybhat/scikit-image,rjeli/scikit-image,michaelaye/scikit-image,GaZ3ll3/scikit-image,dpshelio/scikit-image,dpshelio/scikit-image,juliusbierk/scikit-image,vighneshbirodkar/scikit-image,WarrenWeckesser/scikits-image,michaelpacer/scikit-image,emon10005/scikit-image,rjeli/scikit-image,almarklein/scikit-image,bsipocz/scikit-image,bennlich/scikit-image,chintak/scikit-image,paalge/scikit-image,blink1073/scikit-image,ajaybhat/scikit-image,keflavich/scikit-image,Midafi/scikit-image,bennlich/scikit-image,youprofit/scikit-image,Hiyorimi/scikit-image,rjeli/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,newville/scikit-image,jwiggins/scikit-image,vighneshbirodkar/scikit-image,GaZ3ll3/scikit-image,oew1v07/scikit-image,paalge/scikit-image,Hiyorimi/scikit-image,bsipocz/scikit-image,chriscrosscutler/scikit-image,almarklein/scikit-image,keflavich/scikit-image,warmspringwinds/scikit-image,almarklein/scikit-image,Midafi/scikit-image,juliusbierk/scikit-image,SamHames/scikit-image,emon10005/scikit-image,chintak/scikit-image,ofgulban/scikit-image,SamHames/scikit-image,michaelpacer/scikit-image,chintak/scikit-image,Britefury/scikit-image,Britefury/scikit-image,chintak/scikit-image,robintw/scikit-image,oew1v07/scikit-image,SamHames/scikit-image,youprofit/scikit-image,SamHames/scikit-image,ofgulban/scikit-image | import os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
qt_api = 'none'
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
os.environ['QT_API'] = qt_api
Use None instead of 'none' for qt backend | import os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
qt_api = None
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
os.environ['QT_API'] = qt_api
| <commit_before>import os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
qt_api = 'none'
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
os.environ['QT_API'] = qt_api
<commit_msg>Use None instead of 'none' for qt backend<commit_after> | import os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
qt_api = None
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
os.environ['QT_API'] = qt_api
| import os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
qt_api = 'none'
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
os.environ['QT_API'] = qt_api
Use None instead of 'none' for qt backendimport os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
qt_api = None
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
os.environ['QT_API'] = qt_api
| <commit_before>import os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
qt_api = 'none'
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
os.environ['QT_API'] = qt_api
<commit_msg>Use None instead of 'none' for qt backend<commit_after>import os
import warnings
qt_api = os.environ.get('QT_API')
if qt_api is None:
try:
import PySide
qt_api = 'pyside'
except ImportError:
try:
import PyQt4
qt_api = 'pyqt'
except ImportError:
qt_api = None
# Note that we don't want to raise an error because that would
# cause the TravisCI build to fail.
warnings.warn("Could not import PyQt4: ImageViewer not available!")
os.environ['QT_API'] = qt_api
|
a80069cb364e4802321aaba918ef671daebcff50 | elephantblog/admin.py | elephantblog/admin.py | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation
from feincms.translations import admin_translationinline, short_language_code
CategoryTranslationInline = admin_translationinline(CategoryTranslation, prepopulated_fields={
'slug': ('title',)})
class CategoryAdmin(admin.ModelAdmin):
inlines = [CategoryTranslationInline]
list_display = ['__unicode__', 'entries']
search_fields = ['translations__title']
def entries(self, obj):
if 'translations' in getattr(Entry, '_feincms_extensions', ()):
return Entry.objects.filter(categories=obj, language=short_language_code()).count()
return Entry.objects.filter(categories=obj)
entries.short_description = _('Blog entries in category')
admin.site.register(Entry, EntryAdmin)
admin.site.register(Category, CategoryAdmin)
| from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation
from feincms.translations import admin_translationinline, short_language_code
CategoryTranslationInline = admin_translationinline(CategoryTranslation, prepopulated_fields={
'slug': ('title',)})
class CategoryAdmin(admin.ModelAdmin):
inlines = [CategoryTranslationInline]
list_display = ['__unicode__', 'entries']
search_fields = ['translations__title']
def entries(self, obj):
return Entry.objects.filter(categories=obj)
entries.short_description = _('Blog entries in category')
admin.site.register(Entry, EntryAdmin)
admin.site.register(Category, CategoryAdmin)
| Remove the broken translations extension autodetection | Remove the broken translations extension autodetection
| Python | bsd-3-clause | joshuajonah/feincms-elephantblog,matthiask/feincms-elephantblog,sbaechler/feincms-elephantblog,michaelkuty/feincms-elephantblog,joshuajonah/feincms-elephantblog,matthiask/feincms-elephantblog,michaelkuty/feincms-elephantblog,michaelkuty/feincms-elephantblog,feincms/feincms-elephantblog,sbaechler/feincms-elephantblog,sbaechler/feincms-elephantblog,matthiask/feincms-elephantblog,joshuajonah/feincms-elephantblog,feincms/feincms-elephantblog | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation
from feincms.translations import admin_translationinline, short_language_code
CategoryTranslationInline = admin_translationinline(CategoryTranslation, prepopulated_fields={
'slug': ('title',)})
class CategoryAdmin(admin.ModelAdmin):
inlines = [CategoryTranslationInline]
list_display = ['__unicode__', 'entries']
search_fields = ['translations__title']
def entries(self, obj):
if 'translations' in getattr(Entry, '_feincms_extensions', ()):
return Entry.objects.filter(categories=obj, language=short_language_code()).count()
return Entry.objects.filter(categories=obj)
entries.short_description = _('Blog entries in category')
admin.site.register(Entry, EntryAdmin)
admin.site.register(Category, CategoryAdmin)
Remove the broken translations extension autodetection | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation
from feincms.translations import admin_translationinline, short_language_code
CategoryTranslationInline = admin_translationinline(CategoryTranslation, prepopulated_fields={
'slug': ('title',)})
class CategoryAdmin(admin.ModelAdmin):
inlines = [CategoryTranslationInline]
list_display = ['__unicode__', 'entries']
search_fields = ['translations__title']
def entries(self, obj):
return Entry.objects.filter(categories=obj)
entries.short_description = _('Blog entries in category')
admin.site.register(Entry, EntryAdmin)
admin.site.register(Category, CategoryAdmin)
| <commit_before>from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation
from feincms.translations import admin_translationinline, short_language_code
CategoryTranslationInline = admin_translationinline(CategoryTranslation, prepopulated_fields={
'slug': ('title',)})
class CategoryAdmin(admin.ModelAdmin):
inlines = [CategoryTranslationInline]
list_display = ['__unicode__', 'entries']
search_fields = ['translations__title']
def entries(self, obj):
if 'translations' in getattr(Entry, '_feincms_extensions', ()):
return Entry.objects.filter(categories=obj, language=short_language_code()).count()
return Entry.objects.filter(categories=obj)
entries.short_description = _('Blog entries in category')
admin.site.register(Entry, EntryAdmin)
admin.site.register(Category, CategoryAdmin)
<commit_msg>Remove the broken translations extension autodetection<commit_after> | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation
from feincms.translations import admin_translationinline, short_language_code
CategoryTranslationInline = admin_translationinline(CategoryTranslation, prepopulated_fields={
'slug': ('title',)})
class CategoryAdmin(admin.ModelAdmin):
inlines = [CategoryTranslationInline]
list_display = ['__unicode__', 'entries']
search_fields = ['translations__title']
def entries(self, obj):
return Entry.objects.filter(categories=obj)
entries.short_description = _('Blog entries in category')
admin.site.register(Entry, EntryAdmin)
admin.site.register(Category, CategoryAdmin)
| from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation
from feincms.translations import admin_translationinline, short_language_code
CategoryTranslationInline = admin_translationinline(CategoryTranslation, prepopulated_fields={
'slug': ('title',)})
class CategoryAdmin(admin.ModelAdmin):
inlines = [CategoryTranslationInline]
list_display = ['__unicode__', 'entries']
search_fields = ['translations__title']
def entries(self, obj):
if 'translations' in getattr(Entry, '_feincms_extensions', ()):
return Entry.objects.filter(categories=obj, language=short_language_code()).count()
return Entry.objects.filter(categories=obj)
entries.short_description = _('Blog entries in category')
admin.site.register(Entry, EntryAdmin)
admin.site.register(Category, CategoryAdmin)
Remove the broken translations extension autodetectionfrom django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation
from feincms.translations import admin_translationinline, short_language_code
CategoryTranslationInline = admin_translationinline(CategoryTranslation, prepopulated_fields={
'slug': ('title',)})
class CategoryAdmin(admin.ModelAdmin):
inlines = [CategoryTranslationInline]
list_display = ['__unicode__', 'entries']
search_fields = ['translations__title']
def entries(self, obj):
return Entry.objects.filter(categories=obj)
entries.short_description = _('Blog entries in category')
admin.site.register(Entry, EntryAdmin)
admin.site.register(Category, CategoryAdmin)
| <commit_before>from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation
from feincms.translations import admin_translationinline, short_language_code
CategoryTranslationInline = admin_translationinline(CategoryTranslation, prepopulated_fields={
'slug': ('title',)})
class CategoryAdmin(admin.ModelAdmin):
inlines = [CategoryTranslationInline]
list_display = ['__unicode__', 'entries']
search_fields = ['translations__title']
def entries(self, obj):
if 'translations' in getattr(Entry, '_feincms_extensions', ()):
return Entry.objects.filter(categories=obj, language=short_language_code()).count()
return Entry.objects.filter(categories=obj)
entries.short_description = _('Blog entries in category')
admin.site.register(Entry, EntryAdmin)
admin.site.register(Category, CategoryAdmin)
<commit_msg>Remove the broken translations extension autodetection<commit_after>from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from elephantblog.models import Entry, EntryAdmin, Category, CategoryTranslation
from feincms.translations import admin_translationinline, short_language_code
CategoryTranslationInline = admin_translationinline(CategoryTranslation, prepopulated_fields={
'slug': ('title',)})
class CategoryAdmin(admin.ModelAdmin):
inlines = [CategoryTranslationInline]
list_display = ['__unicode__', 'entries']
search_fields = ['translations__title']
def entries(self, obj):
return Entry.objects.filter(categories=obj)
entries.short_description = _('Blog entries in category')
admin.site.register(Entry, EntryAdmin)
admin.site.register(Category, CategoryAdmin)
|
cb48464859110d4e6ebcf59d70a59804c55d4705 | tests/QtNetwork/basic_auth_test.py | tests/QtNetwork/basic_auth_test.py | import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
| import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQCoreApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQCoreApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
| Remove the dependecy of QtGui from a test located in QtNetwork. | Remove the dependecy of QtGui from a test located in QtNetwork.
| Python | lgpl-2.1 | M4rtinK/pyside-android,enthought/pyside,IronManMark20/pyside2,IronManMark20/pyside2,M4rtinK/pyside-android,M4rtinK/pyside-android,pankajp/pyside,PySide/PySide,qtproject/pyside-pyside,M4rtinK/pyside-bb10,qtproject/pyside-pyside,enthought/pyside,enthought/pyside,RobinD42/pyside,M4rtinK/pyside-bb10,BadSingleton/pyside2,gbaty/pyside2,RobinD42/pyside,M4rtinK/pyside-android,enthought/pyside,enthought/pyside,RobinD42/pyside,M4rtinK/pyside-android,PySide/PySide,IronManMark20/pyside2,RobinD42/pyside,RobinD42/pyside,gbaty/pyside2,BadSingleton/pyside2,BadSingleton/pyside2,pankajp/pyside,M4rtinK/pyside-bb10,M4rtinK/pyside-bb10,qtproject/pyside-pyside,enthought/pyside,PySide/PySide,gbaty/pyside2,RobinD42/pyside,pankajp/pyside,gbaty/pyside2,qtproject/pyside-pyside,pankajp/pyside,enthought/pyside,gbaty/pyside2,IronManMark20/pyside2,BadSingleton/pyside2,IronManMark20/pyside2,BadSingleton/pyside2,pankajp/pyside,RobinD42/pyside,M4rtinK/pyside-bb10,M4rtinK/pyside-android,M4rtinK/pyside-bb10,PySide/PySide,qtproject/pyside-pyside,PySide/PySide | import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
Remove the dependecy of QtGui from a test located in QtNetwork. | import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQCoreApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQCoreApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
| <commit_before>import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
<commit_msg>Remove the dependecy of QtGui from a test located in QtNetwork.<commit_after> | import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQCoreApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQCoreApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
| import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
Remove the dependecy of QtGui from a test located in QtNetwork.import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQCoreApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQCoreApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
| <commit_before>import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
<commit_msg>Remove the dependecy of QtGui from a test located in QtNetwork.<commit_after>import unittest
from PySide.QtCore import *
from PySide.QtNetwork import *
from helper import UsesQCoreApplication
from httpd import TestServer
class testAuthenticationSignal(UsesQCoreApplication):
def setUp(self):
super(testAuthenticationSignal, self).setUp()
self.httpd = TestServer(secure=True)
self.httpd.start()
self._resultOk = False
def tearDown(self):
self.httpd.shutdown()
del self.httpd
super(testAuthenticationSignal, self).tearDown()
def onAuthRequest(self, hostname, port, auth):
self.assert_(isinstance(auth, QAuthenticator))
self._resultOk = True
self.app.quit()
def testwaitSignal(self):
http = QHttp()
http.setHost("localhost", self.httpd.port())
http.connect(SIGNAL("authenticationRequired(const QString&, quint16, QAuthenticator*)"), self.onAuthRequest)
path = QUrl.toPercentEncoding("/index.html", "!$&'()*+,;=:@/")
data = http.get(path)
self.app.exec_()
self.assert_(self._resultOk)
if __name__ == '__main__':
unittest.main()
|
494fd9dd3cb526682e5cb6fabc12ce4263875aea | flask_slacker/__init__.py | flask_slacker/__init__.py | """
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None, **kwargs):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app, config=None):
"""
Initialize the app in Flask.
"""
if not (config is None or isinstance(config, dict)):
raise ValueError("`config` must be an instance of dict or None")
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(**config)
| """
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker, DEFAULT_TIMEOUT
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app):
"""
Initialize the app in Flask.
"""
app.config.setdefault('SLACKER_TIMEOUT', DEFAULT_TIMEOUT)
if 'SLACKER_TOKEN' not in app.config:
raise Exception('Missing SLACKER_TOKEN in your config.')
token = app.config['SLACKER_TOKEN']
timeout = app.config['SLACKER_TIMEOUT']
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(token, timeout=timeout)
| Load app configs for Slacker | Load app configs for Slacker
| Python | mit | mdsrosa/flask-slacker | """
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None, **kwargs):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app, config=None):
"""
Initialize the app in Flask.
"""
if not (config is None or isinstance(config, dict)):
raise ValueError("`config` must be an instance of dict or None")
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(**config)
Load app configs for Slacker | """
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker, DEFAULT_TIMEOUT
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app):
"""
Initialize the app in Flask.
"""
app.config.setdefault('SLACKER_TIMEOUT', DEFAULT_TIMEOUT)
if 'SLACKER_TOKEN' not in app.config:
raise Exception('Missing SLACKER_TOKEN in your config.')
token = app.config['SLACKER_TOKEN']
timeout = app.config['SLACKER_TIMEOUT']
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(token, timeout=timeout)
| <commit_before>"""
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None, **kwargs):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app, config=None):
"""
Initialize the app in Flask.
"""
if not (config is None or isinstance(config, dict)):
raise ValueError("`config` must be an instance of dict or None")
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(**config)
<commit_msg>Load app configs for Slacker<commit_after> | """
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker, DEFAULT_TIMEOUT
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app):
"""
Initialize the app in Flask.
"""
app.config.setdefault('SLACKER_TIMEOUT', DEFAULT_TIMEOUT)
if 'SLACKER_TOKEN' not in app.config:
raise Exception('Missing SLACKER_TOKEN in your config.')
token = app.config['SLACKER_TOKEN']
timeout = app.config['SLACKER_TIMEOUT']
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(token, timeout=timeout)
| """
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None, **kwargs):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app, config=None):
"""
Initialize the app in Flask.
"""
if not (config is None or isinstance(config, dict)):
raise ValueError("`config` must be an instance of dict or None")
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(**config)
Load app configs for Slacker"""
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker, DEFAULT_TIMEOUT
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app):
"""
Initialize the app in Flask.
"""
app.config.setdefault('SLACKER_TIMEOUT', DEFAULT_TIMEOUT)
if 'SLACKER_TOKEN' not in app.config:
raise Exception('Missing SLACKER_TOKEN in your config.')
token = app.config['SLACKER_TOKEN']
timeout = app.config['SLACKER_TIMEOUT']
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(token, timeout=timeout)
| <commit_before>"""
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None, **kwargs):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app, config=None):
"""
Initialize the app in Flask.
"""
if not (config is None or isinstance(config, dict)):
raise ValueError("`config` must be an instance of dict or None")
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(**config)
<commit_msg>Load app configs for Slacker<commit_after>"""
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker, DEFAULT_TIMEOUT
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app):
"""
Initialize the app in Flask.
"""
app.config.setdefault('SLACKER_TIMEOUT', DEFAULT_TIMEOUT)
if 'SLACKER_TOKEN' not in app.config:
raise Exception('Missing SLACKER_TOKEN in your config.')
token = app.config['SLACKER_TOKEN']
timeout = app.config['SLACKER_TIMEOUT']
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(token, timeout=timeout)
|
ebfdde13ef464104b744d6eff41ebe181861603a | froide/helper/widgets.py | froide/helper/widgets.py | from django import forms
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
class EmailInput(forms.TextInput):
input_type = 'email'
class DateInput(forms.DateInput):
input_type = 'date'
class AgreeCheckboxInput(forms.CheckboxInput):
def __init__(self, attrs=None, check_test=bool, agree_to="", url_names=None):
super(AgreeCheckboxInput, self).__init__(attrs, check_test)
self.agree_to = agree_to
self.url_names = url_names
def render(self, name, value, attrs=None):
html = super(AgreeCheckboxInput, self).render(name, value, attrs)
return mark_safe(u'%s <label for="id_%s">%s</label>' % (html, name, self.agree_to %
dict([(k, reverse(v)) for k, v in self.url_names.items()])))
| from django import forms
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
class EmailInput(forms.TextInput):
input_type = 'email'
class DateInput(forms.DateInput):
input_type = 'date'
class AgreeCheckboxInput(forms.CheckboxInput):
def __init__(self, attrs=None, check_test=bool, agree_to="", url_names=None):
super(AgreeCheckboxInput, self).__init__(attrs, check_test)
self.agree_to = agree_to
self.url_names = url_names
def render(self, name, value, attrs=None):
html = super(AgreeCheckboxInput, self).render(name, value, attrs)
return mark_safe(u'<label class="checkbox">%s %s</label>' % (html, self.agree_to %
dict([(k, reverse(v)) for k, v in self.url_names.items()])))
| Change widget to Bootstrap form | Change widget to Bootstrap form | Python | mit | stefanw/froide,okfse/froide,catcosmo/froide,CodeforHawaii/froide,ryankanno/froide,okfse/froide,stefanw/froide,LilithWittmann/froide,catcosmo/froide,stefanw/froide,catcosmo/froide,ryankanno/froide,okfse/froide,LilithWittmann/froide,stefanw/froide,CodeforHawaii/froide,LilithWittmann/froide,CodeforHawaii/froide,okfse/froide,catcosmo/froide,stefanw/froide,fin/froide,fin/froide,LilithWittmann/froide,ryankanno/froide,LilithWittmann/froide,fin/froide,okfse/froide,catcosmo/froide,CodeforHawaii/froide,fin/froide,CodeforHawaii/froide,ryankanno/froide,ryankanno/froide | from django import forms
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
class EmailInput(forms.TextInput):
input_type = 'email'
class DateInput(forms.DateInput):
input_type = 'date'
class AgreeCheckboxInput(forms.CheckboxInput):
def __init__(self, attrs=None, check_test=bool, agree_to="", url_names=None):
super(AgreeCheckboxInput, self).__init__(attrs, check_test)
self.agree_to = agree_to
self.url_names = url_names
def render(self, name, value, attrs=None):
html = super(AgreeCheckboxInput, self).render(name, value, attrs)
return mark_safe(u'%s <label for="id_%s">%s</label>' % (html, name, self.agree_to %
dict([(k, reverse(v)) for k, v in self.url_names.items()])))
Change widget to Bootstrap form | from django import forms
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
class EmailInput(forms.TextInput):
input_type = 'email'
class DateInput(forms.DateInput):
input_type = 'date'
class AgreeCheckboxInput(forms.CheckboxInput):
def __init__(self, attrs=None, check_test=bool, agree_to="", url_names=None):
super(AgreeCheckboxInput, self).__init__(attrs, check_test)
self.agree_to = agree_to
self.url_names = url_names
def render(self, name, value, attrs=None):
html = super(AgreeCheckboxInput, self).render(name, value, attrs)
return mark_safe(u'<label class="checkbox">%s %s</label>' % (html, self.agree_to %
dict([(k, reverse(v)) for k, v in self.url_names.items()])))
| <commit_before>from django import forms
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
class EmailInput(forms.TextInput):
input_type = 'email'
class DateInput(forms.DateInput):
input_type = 'date'
class AgreeCheckboxInput(forms.CheckboxInput):
def __init__(self, attrs=None, check_test=bool, agree_to="", url_names=None):
super(AgreeCheckboxInput, self).__init__(attrs, check_test)
self.agree_to = agree_to
self.url_names = url_names
def render(self, name, value, attrs=None):
html = super(AgreeCheckboxInput, self).render(name, value, attrs)
return mark_safe(u'%s <label for="id_%s">%s</label>' % (html, name, self.agree_to %
dict([(k, reverse(v)) for k, v in self.url_names.items()])))
<commit_msg>Change widget to Bootstrap form<commit_after> | from django import forms
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
class EmailInput(forms.TextInput):
input_type = 'email'
class DateInput(forms.DateInput):
input_type = 'date'
class AgreeCheckboxInput(forms.CheckboxInput):
def __init__(self, attrs=None, check_test=bool, agree_to="", url_names=None):
super(AgreeCheckboxInput, self).__init__(attrs, check_test)
self.agree_to = agree_to
self.url_names = url_names
def render(self, name, value, attrs=None):
html = super(AgreeCheckboxInput, self).render(name, value, attrs)
return mark_safe(u'<label class="checkbox">%s %s</label>' % (html, self.agree_to %
dict([(k, reverse(v)) for k, v in self.url_names.items()])))
| from django import forms
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
class EmailInput(forms.TextInput):
input_type = 'email'
class DateInput(forms.DateInput):
input_type = 'date'
class AgreeCheckboxInput(forms.CheckboxInput):
def __init__(self, attrs=None, check_test=bool, agree_to="", url_names=None):
super(AgreeCheckboxInput, self).__init__(attrs, check_test)
self.agree_to = agree_to
self.url_names = url_names
def render(self, name, value, attrs=None):
html = super(AgreeCheckboxInput, self).render(name, value, attrs)
return mark_safe(u'%s <label for="id_%s">%s</label>' % (html, name, self.agree_to %
dict([(k, reverse(v)) for k, v in self.url_names.items()])))
Change widget to Bootstrap formfrom django import forms
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
class EmailInput(forms.TextInput):
input_type = 'email'
class DateInput(forms.DateInput):
input_type = 'date'
class AgreeCheckboxInput(forms.CheckboxInput):
def __init__(self, attrs=None, check_test=bool, agree_to="", url_names=None):
super(AgreeCheckboxInput, self).__init__(attrs, check_test)
self.agree_to = agree_to
self.url_names = url_names
def render(self, name, value, attrs=None):
html = super(AgreeCheckboxInput, self).render(name, value, attrs)
return mark_safe(u'<label class="checkbox">%s %s</label>' % (html, self.agree_to %
dict([(k, reverse(v)) for k, v in self.url_names.items()])))
| <commit_before>from django import forms
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
class EmailInput(forms.TextInput):
input_type = 'email'
class DateInput(forms.DateInput):
input_type = 'date'
class AgreeCheckboxInput(forms.CheckboxInput):
def __init__(self, attrs=None, check_test=bool, agree_to="", url_names=None):
super(AgreeCheckboxInput, self).__init__(attrs, check_test)
self.agree_to = agree_to
self.url_names = url_names
def render(self, name, value, attrs=None):
html = super(AgreeCheckboxInput, self).render(name, value, attrs)
return mark_safe(u'%s <label for="id_%s">%s</label>' % (html, name, self.agree_to %
dict([(k, reverse(v)) for k, v in self.url_names.items()])))
<commit_msg>Change widget to Bootstrap form<commit_after>from django import forms
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
class EmailInput(forms.TextInput):
input_type = 'email'
class DateInput(forms.DateInput):
input_type = 'date'
class AgreeCheckboxInput(forms.CheckboxInput):
def __init__(self, attrs=None, check_test=bool, agree_to="", url_names=None):
super(AgreeCheckboxInput, self).__init__(attrs, check_test)
self.agree_to = agree_to
self.url_names = url_names
def render(self, name, value, attrs=None):
html = super(AgreeCheckboxInput, self).render(name, value, attrs)
return mark_safe(u'<label class="checkbox">%s %s</label>' % (html, self.agree_to %
dict([(k, reverse(v)) for k, v in self.url_names.items()])))
|
469b7e8a83308b4ea6ad84d49d7a8aa42274a381 | projects/views.py | projects/views.py | from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import Project
from .forms import ProjectForm
@login_required
def add_project(request):
data = request.POST if request.POST else None
form = ProjectForm(data, user=request.user)
if form.is_valid():
form.save()
return render(request, 'projects/add.html', locals())
| from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from .models import Project
from .forms import ProjectForm
def can_edit_projects(user):
return user.is_authenticated() and user.has_perm('projects.change_project')
@login_required
def add_project(request):
data = request.POST if request.POST else None
form = ProjectForm(data, user=request.user)
if form.is_valid():
form.save()
return render(request, 'projects/add.html', locals())
@login_required
def edit_project(request, project_id=None):
project = get_object_or_404(Project, id=project_id)
if can_edit_projects(request.user) or request.user == project.user:
return render(request, 'projects/edit.html', locals())
else:
raise Http404
| Add restrictioins for who can edit the project and who cannot | Add restrictioins for who can edit the project and who cannot
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import Project
from .forms import ProjectForm
@login_required
def add_project(request):
data = request.POST if request.POST else None
form = ProjectForm(data, user=request.user)
if form.is_valid():
form.save()
return render(request, 'projects/add.html', locals())
Add restrictioins for who can edit the project and who cannot | from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from .models import Project
from .forms import ProjectForm
def can_edit_projects(user):
return user.is_authenticated() and user.has_perm('projects.change_project')
@login_required
def add_project(request):
data = request.POST if request.POST else None
form = ProjectForm(data, user=request.user)
if form.is_valid():
form.save()
return render(request, 'projects/add.html', locals())
@login_required
def edit_project(request, project_id=None):
project = get_object_or_404(Project, id=project_id)
if can_edit_projects(request.user) or request.user == project.user:
return render(request, 'projects/edit.html', locals())
else:
raise Http404
| <commit_before>from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import Project
from .forms import ProjectForm
@login_required
def add_project(request):
data = request.POST if request.POST else None
form = ProjectForm(data, user=request.user)
if form.is_valid():
form.save()
return render(request, 'projects/add.html', locals())
<commit_msg>Add restrictioins for who can edit the project and who cannot<commit_after> | from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from .models import Project
from .forms import ProjectForm
def can_edit_projects(user):
return user.is_authenticated() and user.has_perm('projects.change_project')
@login_required
def add_project(request):
data = request.POST if request.POST else None
form = ProjectForm(data, user=request.user)
if form.is_valid():
form.save()
return render(request, 'projects/add.html', locals())
@login_required
def edit_project(request, project_id=None):
project = get_object_or_404(Project, id=project_id)
if can_edit_projects(request.user) or request.user == project.user:
return render(request, 'projects/edit.html', locals())
else:
raise Http404
| from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import Project
from .forms import ProjectForm
@login_required
def add_project(request):
data = request.POST if request.POST else None
form = ProjectForm(data, user=request.user)
if form.is_valid():
form.save()
return render(request, 'projects/add.html', locals())
Add restrictioins for who can edit the project and who cannotfrom django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from .models import Project
from .forms import ProjectForm
def can_edit_projects(user):
return user.is_authenticated() and user.has_perm('projects.change_project')
@login_required
def add_project(request):
data = request.POST if request.POST else None
form = ProjectForm(data, user=request.user)
if form.is_valid():
form.save()
return render(request, 'projects/add.html', locals())
@login_required
def edit_project(request, project_id=None):
project = get_object_or_404(Project, id=project_id)
if can_edit_projects(request.user) or request.user == project.user:
return render(request, 'projects/edit.html', locals())
else:
raise Http404
| <commit_before>from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import Project
from .forms import ProjectForm
@login_required
def add_project(request):
data = request.POST if request.POST else None
form = ProjectForm(data, user=request.user)
if form.is_valid():
form.save()
return render(request, 'projects/add.html', locals())
<commit_msg>Add restrictioins for who can edit the project and who cannot<commit_after>from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from .models import Project
from .forms import ProjectForm
def can_edit_projects(user):
return user.is_authenticated() and user.has_perm('projects.change_project')
@login_required
def add_project(request):
data = request.POST if request.POST else None
form = ProjectForm(data, user=request.user)
if form.is_valid():
form.save()
return render(request, 'projects/add.html', locals())
@login_required
def edit_project(request, project_id=None):
project = get_object_or_404(Project, id=project_id)
if can_edit_projects(request.user) or request.user == project.user:
return render(request, 'projects/edit.html', locals())
else:
raise Http404
|
c73d6687cb9b8579cb0e36e1f971353d916ceff5 | cfgov/v1/migrations/0012_share_perms.py | cfgov/v1/migrations/0012_share_perms.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.create(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.get(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
| Fix Share page permission migration | Fix Share page permission migration
| Python | cc0-1.0 | kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.create(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
Fix Share page permission migration | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.get(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.create(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
<commit_msg>Fix Share page permission migration<commit_after> | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.get(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.create(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
Fix Share page permission migration# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.get(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.create(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
<commit_msg>Fix Share page permission migration<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_share_permissions(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')
Group = apps.get_model('auth.Group')
v1_content_type = ContentType.objects.get(app_label="v1", model="cfgovpage")
# Create share permission
share_permission = Permission.objects.create(
content_type=v1_content_type,
codename='share_page',
name='Can share pages'
)
# Assign it to Editors and Moderators groups
for group in Group.objects.all():
group.permissions.add(share_permission)
class Migration(migrations.Migration):
dependencies = [
('v1', '0011_auto_20151207_1725'),
]
operations = [
migrations.RunPython(create_share_permissions),
]
|
274f5b738386e8a7ad0a7fd5ae46719fe15712de | clowder/clowder/cli/stash_controller.py | clowder/clowder/cli/stash_controller.py | from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
class StashController(AbstractBaseController):
class Meta:
label = 'stash'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Stash current changes'
@expose(help="second-controller default command", hide=True)
def default(self):
print("Inside SecondController.default()")
| from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
from clowder.commands.util import (
filter_groups,
filter_projects_on_project_names,
run_group_command,
run_project_command
)
from clowder.util.decorators import (
print_clowder_repo_status,
valid_clowder_yaml_required
)
class StashController(AbstractBaseController):
class Meta:
label = 'stash'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Stash current changes'
@expose(help="second-controller default command", hide=True)
@valid_clowder_yaml_required
@print_clowder_repo_status
def default(self):
if not any([g.is_dirty() for g in self.clowder.groups]):
print('No changes to stash')
return
if self.app.pargs.projects is None:
groups = filter_groups(self.clowder.groups, self.app.pargs.groups)
for group in groups:
run_group_command(group, self.app.pargs.skip, 'stash')
return
projects = filter_projects_on_project_names(self.clowder.groups, self.app.pargs.projects)
for project in projects:
run_project_command(project, self.app.pargs.skip, 'stash')
| Add `clowder stash` logic to Cement controller | Add `clowder stash` logic to Cement controller
| Python | mit | JrGoodle/clowder,JrGoodle/clowder,JrGoodle/clowder | from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
class StashController(AbstractBaseController):
class Meta:
label = 'stash'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Stash current changes'
@expose(help="second-controller default command", hide=True)
def default(self):
print("Inside SecondController.default()")
Add `clowder stash` logic to Cement controller | from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
from clowder.commands.util import (
filter_groups,
filter_projects_on_project_names,
run_group_command,
run_project_command
)
from clowder.util.decorators import (
print_clowder_repo_status,
valid_clowder_yaml_required
)
class StashController(AbstractBaseController):
class Meta:
label = 'stash'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Stash current changes'
@expose(help="second-controller default command", hide=True)
@valid_clowder_yaml_required
@print_clowder_repo_status
def default(self):
if not any([g.is_dirty() for g in self.clowder.groups]):
print('No changes to stash')
return
if self.app.pargs.projects is None:
groups = filter_groups(self.clowder.groups, self.app.pargs.groups)
for group in groups:
run_group_command(group, self.app.pargs.skip, 'stash')
return
projects = filter_projects_on_project_names(self.clowder.groups, self.app.pargs.projects)
for project in projects:
run_project_command(project, self.app.pargs.skip, 'stash')
| <commit_before>from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
class StashController(AbstractBaseController):
class Meta:
label = 'stash'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Stash current changes'
@expose(help="second-controller default command", hide=True)
def default(self):
print("Inside SecondController.default()")
<commit_msg>Add `clowder stash` logic to Cement controller<commit_after> | from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
from clowder.commands.util import (
filter_groups,
filter_projects_on_project_names,
run_group_command,
run_project_command
)
from clowder.util.decorators import (
print_clowder_repo_status,
valid_clowder_yaml_required
)
class StashController(AbstractBaseController):
class Meta:
label = 'stash'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Stash current changes'
@expose(help="second-controller default command", hide=True)
@valid_clowder_yaml_required
@print_clowder_repo_status
def default(self):
if not any([g.is_dirty() for g in self.clowder.groups]):
print('No changes to stash')
return
if self.app.pargs.projects is None:
groups = filter_groups(self.clowder.groups, self.app.pargs.groups)
for group in groups:
run_group_command(group, self.app.pargs.skip, 'stash')
return
projects = filter_projects_on_project_names(self.clowder.groups, self.app.pargs.projects)
for project in projects:
run_project_command(project, self.app.pargs.skip, 'stash')
| from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
class StashController(AbstractBaseController):
class Meta:
label = 'stash'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Stash current changes'
@expose(help="second-controller default command", hide=True)
def default(self):
print("Inside SecondController.default()")
Add `clowder stash` logic to Cement controllerfrom cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
from clowder.commands.util import (
filter_groups,
filter_projects_on_project_names,
run_group_command,
run_project_command
)
from clowder.util.decorators import (
print_clowder_repo_status,
valid_clowder_yaml_required
)
class StashController(AbstractBaseController):
class Meta:
label = 'stash'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Stash current changes'
@expose(help="second-controller default command", hide=True)
@valid_clowder_yaml_required
@print_clowder_repo_status
def default(self):
if not any([g.is_dirty() for g in self.clowder.groups]):
print('No changes to stash')
return
if self.app.pargs.projects is None:
groups = filter_groups(self.clowder.groups, self.app.pargs.groups)
for group in groups:
run_group_command(group, self.app.pargs.skip, 'stash')
return
projects = filter_projects_on_project_names(self.clowder.groups, self.app.pargs.projects)
for project in projects:
run_project_command(project, self.app.pargs.skip, 'stash')
| <commit_before>from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
class StashController(AbstractBaseController):
class Meta:
label = 'stash'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Stash current changes'
@expose(help="second-controller default command", hide=True)
def default(self):
print("Inside SecondController.default()")
<commit_msg>Add `clowder stash` logic to Cement controller<commit_after>from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
from clowder.commands.util import (
filter_groups,
filter_projects_on_project_names,
run_group_command,
run_project_command
)
from clowder.util.decorators import (
print_clowder_repo_status,
valid_clowder_yaml_required
)
class StashController(AbstractBaseController):
class Meta:
label = 'stash'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Stash current changes'
@expose(help="second-controller default command", hide=True)
@valid_clowder_yaml_required
@print_clowder_repo_status
def default(self):
if not any([g.is_dirty() for g in self.clowder.groups]):
print('No changes to stash')
return
if self.app.pargs.projects is None:
groups = filter_groups(self.clowder.groups, self.app.pargs.groups)
for group in groups:
run_group_command(group, self.app.pargs.skip, 'stash')
return
projects = filter_projects_on_project_names(self.clowder.groups, self.app.pargs.projects)
for project in projects:
run_project_command(project, self.app.pargs.skip, 'stash')
|
b8de9355e0c592b1c57f91e3980544bab7cbfb0f | app/assets.py | app/assets.py | from flask_assets import Bundle, Environment
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters='jsmin',
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters='cssmin',
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
| from flask_assets import Bundle, Environment, Filter
# fixes missing semicolon in last statement of jquery.pjax.js
class ConcatFilter(Filter):
def concat(self, out, hunks, **kw):
out.write(';'.join([h.data() for h, info in hunks]))
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters=(ConcatFilter, 'jsmin'),
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters='cssmin',
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
| Add concat filter to fix issue with jquery-pjax | Add concat filter to fix issue with jquery-pjax
jquery-pjax makes use of IIFEs but does not terminate its last statement with a
semicolon, causing syntax errors after asset concatenation. See also:
https://github.com/miracle2k/webassets/issues/100#issuecomment-388461033
| Python | mit | cburmeister/flask-bones,cburmeister/flask-bones,cburmeister/flask-bones | from flask_assets import Bundle, Environment
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters='jsmin',
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters='cssmin',
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
Add concat filter to fix issue with jquery-pjax
jquery-pjax makes use of IIFEs but does not terminate its last statement with a
semicolon, causing syntax errors after asset concatenation. See also:
https://github.com/miracle2k/webassets/issues/100#issuecomment-388461033 | from flask_assets import Bundle, Environment, Filter
# fixes missing semicolon in last statement of jquery.pjax.js
class ConcatFilter(Filter):
def concat(self, out, hunks, **kw):
out.write(';'.join([h.data() for h, info in hunks]))
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters=(ConcatFilter, 'jsmin'),
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters='cssmin',
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
| <commit_before>from flask_assets import Bundle, Environment
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters='jsmin',
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters='cssmin',
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
<commit_msg>Add concat filter to fix issue with jquery-pjax
jquery-pjax makes use of IIFEs but does not terminate its last statement with a
semicolon, causing syntax errors after asset concatenation. See also:
https://github.com/miracle2k/webassets/issues/100#issuecomment-388461033<commit_after> | from flask_assets import Bundle, Environment, Filter
# fixes missing semicolon in last statement of jquery.pjax.js
class ConcatFilter(Filter):
def concat(self, out, hunks, **kw):
out.write(';'.join([h.data() for h, info in hunks]))
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters=(ConcatFilter, 'jsmin'),
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters='cssmin',
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
| from flask_assets import Bundle, Environment
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters='jsmin',
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters='cssmin',
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
Add concat filter to fix issue with jquery-pjax
jquery-pjax makes use of IIFEs but does not terminate its last statement with a
semicolon, causing syntax errors after asset concatenation. See also:
https://github.com/miracle2k/webassets/issues/100#issuecomment-388461033from flask_assets import Bundle, Environment, Filter
# fixes missing semicolon in last statement of jquery.pjax.js
class ConcatFilter(Filter):
def concat(self, out, hunks, **kw):
out.write(';'.join([h.data() for h, info in hunks]))
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters=(ConcatFilter, 'jsmin'),
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters='cssmin',
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
| <commit_before>from flask_assets import Bundle, Environment
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters='jsmin',
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters='cssmin',
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
<commit_msg>Add concat filter to fix issue with jquery-pjax
jquery-pjax makes use of IIFEs but does not terminate its last statement with a
semicolon, causing syntax errors after asset concatenation. See also:
https://github.com/miracle2k/webassets/issues/100#issuecomment-388461033<commit_after>from flask_assets import Bundle, Environment, Filter
# fixes missing semicolon in last statement of jquery.pjax.js
class ConcatFilter(Filter):
def concat(self, out, hunks, **kw):
out.write(';'.join([h.data() for h, info in hunks]))
js = Bundle(
'node_modules/jquery/dist/jquery.js',
'node_modules/jquery-pjax/jquery.pjax.js',
'node_modules/bootbox/bootbox.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'js/application.js',
filters=(ConcatFilter, 'jsmin'),
output='gen/packed.js'
)
css = Bundle(
'node_modules/bootstrap/dist/css/bootstrap.css',
'node_modules/font-awesome/css/font-awesome.css',
'css/style.css',
filters='cssmin',
output='gen/packed.css'
)
assets = Environment()
assets.register('js_all', js)
assets.register('css_all', css)
|
d1a4796ee349f7233a9c766a4162d71e598c6327 | test/expression_command/persistent_variables/TestPersistentVariables.py | test/expression_command/persistent_variables/TestPersistentVariables.py | """
Test that lldb persistent variables works correctly.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class PersistentVariablesTestCase(TestBase):
mydir = os.path.join("expression_command", "persistent_variables")
def test_persistent_variables(self):
"""Test that lldb persistent variables works correctly."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
self.runCmd("breakpoint set --name main")
self.runCmd("run", RUN_SUCCEEDED)
self.expect("expression int $i = 5; $i + 1",
startstr = "(int) $0 = 6")
# (int) $0 = 6
self.expect("expression $i + 3",
startstr = "(int) $1 = 8")
# (int) $1 = 8
self.expect("expression $1 + $0",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $2",
startstr = "(int) $3 = 14")
# (int) $3 = 14
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| """
Test that lldb persistent variables works correctly.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class PersistentVariablesTestCase(TestBase):
mydir = os.path.join("expression_command", "persistent_variables")
def test_persistent_variables(self):
"""Test that lldb persistent variables works correctly."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
self.runCmd("breakpoint set --name main")
self.runCmd("run", RUN_SUCCEEDED)
self.expect("expression int $i = 5; $i + 1",
startstr = "(int) $0 = 6")
# (int) $0 = 6
self.expect("expression $i + 3",
startstr = "(int) $1 = 8")
# (int) $1 = 8
self.expect("expression $1 + $0",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $2",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $1",
startstr = "(int) $1 = 8")
# (int) $1 = 8
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| Change the golden output so that merely evaluating an existing persistent variable does not result in a newly created persistent variable. The old one is returned, instead. | Change the golden output so that merely evaluating an existing persistent variable
does not result in a newly created persistent variable. The old one is returned,
instead.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@121775 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb | """
Test that lldb persistent variables works correctly.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class PersistentVariablesTestCase(TestBase):
mydir = os.path.join("expression_command", "persistent_variables")
def test_persistent_variables(self):
"""Test that lldb persistent variables works correctly."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
self.runCmd("breakpoint set --name main")
self.runCmd("run", RUN_SUCCEEDED)
self.expect("expression int $i = 5; $i + 1",
startstr = "(int) $0 = 6")
# (int) $0 = 6
self.expect("expression $i + 3",
startstr = "(int) $1 = 8")
# (int) $1 = 8
self.expect("expression $1 + $0",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $2",
startstr = "(int) $3 = 14")
# (int) $3 = 14
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
Change the golden output so that merely evaluating an existing persistent variable
does not result in a newly created persistent variable. The old one is returned,
instead.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@121775 91177308-0d34-0410-b5e6-96231b3b80d8 | """
Test that lldb persistent variables works correctly.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class PersistentVariablesTestCase(TestBase):
mydir = os.path.join("expression_command", "persistent_variables")
def test_persistent_variables(self):
"""Test that lldb persistent variables works correctly."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
self.runCmd("breakpoint set --name main")
self.runCmd("run", RUN_SUCCEEDED)
self.expect("expression int $i = 5; $i + 1",
startstr = "(int) $0 = 6")
# (int) $0 = 6
self.expect("expression $i + 3",
startstr = "(int) $1 = 8")
# (int) $1 = 8
self.expect("expression $1 + $0",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $2",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $1",
startstr = "(int) $1 = 8")
# (int) $1 = 8
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| <commit_before>"""
Test that lldb persistent variables works correctly.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class PersistentVariablesTestCase(TestBase):
mydir = os.path.join("expression_command", "persistent_variables")
def test_persistent_variables(self):
"""Test that lldb persistent variables works correctly."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
self.runCmd("breakpoint set --name main")
self.runCmd("run", RUN_SUCCEEDED)
self.expect("expression int $i = 5; $i + 1",
startstr = "(int) $0 = 6")
# (int) $0 = 6
self.expect("expression $i + 3",
startstr = "(int) $1 = 8")
# (int) $1 = 8
self.expect("expression $1 + $0",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $2",
startstr = "(int) $3 = 14")
# (int) $3 = 14
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
<commit_msg>Change the golden output so that merely evaluating an existing persistent variable
does not result in a newly created persistent variable. The old one is returned,
instead.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@121775 91177308-0d34-0410-b5e6-96231b3b80d8<commit_after> | """
Test that lldb persistent variables works correctly.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class PersistentVariablesTestCase(TestBase):
mydir = os.path.join("expression_command", "persistent_variables")
def test_persistent_variables(self):
"""Test that lldb persistent variables works correctly."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
self.runCmd("breakpoint set --name main")
self.runCmd("run", RUN_SUCCEEDED)
self.expect("expression int $i = 5; $i + 1",
startstr = "(int) $0 = 6")
# (int) $0 = 6
self.expect("expression $i + 3",
startstr = "(int) $1 = 8")
# (int) $1 = 8
self.expect("expression $1 + $0",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $2",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $1",
startstr = "(int) $1 = 8")
# (int) $1 = 8
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| """
Test that lldb persistent variables works correctly.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class PersistentVariablesTestCase(TestBase):
mydir = os.path.join("expression_command", "persistent_variables")
def test_persistent_variables(self):
"""Test that lldb persistent variables works correctly."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
self.runCmd("breakpoint set --name main")
self.runCmd("run", RUN_SUCCEEDED)
self.expect("expression int $i = 5; $i + 1",
startstr = "(int) $0 = 6")
# (int) $0 = 6
self.expect("expression $i + 3",
startstr = "(int) $1 = 8")
# (int) $1 = 8
self.expect("expression $1 + $0",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $2",
startstr = "(int) $3 = 14")
# (int) $3 = 14
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
Change the golden output so that merely evaluating an existing persistent variable
does not result in a newly created persistent variable. The old one is returned,
instead.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@121775 91177308-0d34-0410-b5e6-96231b3b80d8"""
Test that lldb persistent variables works correctly.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class PersistentVariablesTestCase(TestBase):
mydir = os.path.join("expression_command", "persistent_variables")
def test_persistent_variables(self):
"""Test that lldb persistent variables works correctly."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
self.runCmd("breakpoint set --name main")
self.runCmd("run", RUN_SUCCEEDED)
self.expect("expression int $i = 5; $i + 1",
startstr = "(int) $0 = 6")
# (int) $0 = 6
self.expect("expression $i + 3",
startstr = "(int) $1 = 8")
# (int) $1 = 8
self.expect("expression $1 + $0",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $2",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $1",
startstr = "(int) $1 = 8")
# (int) $1 = 8
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| <commit_before>"""
Test that lldb persistent variables works correctly.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class PersistentVariablesTestCase(TestBase):
mydir = os.path.join("expression_command", "persistent_variables")
def test_persistent_variables(self):
"""Test that lldb persistent variables works correctly."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
self.runCmd("breakpoint set --name main")
self.runCmd("run", RUN_SUCCEEDED)
self.expect("expression int $i = 5; $i + 1",
startstr = "(int) $0 = 6")
# (int) $0 = 6
self.expect("expression $i + 3",
startstr = "(int) $1 = 8")
# (int) $1 = 8
self.expect("expression $1 + $0",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $2",
startstr = "(int) $3 = 14")
# (int) $3 = 14
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
<commit_msg>Change the golden output so that merely evaluating an existing persistent variable
does not result in a newly created persistent variable. The old one is returned,
instead.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@121775 91177308-0d34-0410-b5e6-96231b3b80d8<commit_after>"""
Test that lldb persistent variables works correctly.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class PersistentVariablesTestCase(TestBase):
mydir = os.path.join("expression_command", "persistent_variables")
def test_persistent_variables(self):
"""Test that lldb persistent variables works correctly."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
self.runCmd("breakpoint set --name main")
self.runCmd("run", RUN_SUCCEEDED)
self.expect("expression int $i = 5; $i + 1",
startstr = "(int) $0 = 6")
# (int) $0 = 6
self.expect("expression $i + 3",
startstr = "(int) $1 = 8")
# (int) $1 = 8
self.expect("expression $1 + $0",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $2",
startstr = "(int) $2 = 14")
# (int) $2 = 14
self.expect("expression $1",
startstr = "(int) $1 = 8")
# (int) $1 = 8
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
|
5168d4256bdfac937be62c8dc509a79a4ba9101c | pythran/tests/rosetta/average_loop_length.py | pythran/tests/rosetta/average_loop_length.py | #from http://rosettacode.org/wiki/Average_loop_length#Python
#pythran export analytical(int)
#pythran export testing(int, int)
#runas analytical(10)
#runas testing(10, 100)
#from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
def analytical(n):
return sum(factorial(n) / pow(n, i) / float(factorial(n -i)) for i in range(1, n+1))
def testing(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
| #from http://rosettacode.org/wiki/Average_loop_length#Python
#pythran export analytical(int)
#pythran export testing(int, int)
#runas analytical(10)
#runas avg = testing(10, 10**5); theory = analytical(10); abs((avg / theory - 1) * 100) < 0.1
#from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
def analytical(n):
return sum(factorial(n) / pow(n, i) / float(factorial(n -i)) for i in range(1, n+1))
def testing(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
| Fix test to have less random result | Fix test to have less random result
| Python | bsd-3-clause | hainm/pythran,artas360/pythran,pombredanne/pythran,serge-sans-paille/pythran,artas360/pythran,pombredanne/pythran,pombredanne/pythran,pbrunet/pythran,hainm/pythran,pbrunet/pythran,pbrunet/pythran,artas360/pythran,serge-sans-paille/pythran,hainm/pythran | #from http://rosettacode.org/wiki/Average_loop_length#Python
#pythran export analytical(int)
#pythran export testing(int, int)
#runas analytical(10)
#runas testing(10, 100)
#from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
def analytical(n):
return sum(factorial(n) / pow(n, i) / float(factorial(n -i)) for i in range(1, n+1))
def testing(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
Fix test to have less random result | #from http://rosettacode.org/wiki/Average_loop_length#Python
#pythran export analytical(int)
#pythran export testing(int, int)
#runas analytical(10)
#runas avg = testing(10, 10**5); theory = analytical(10); abs((avg / theory - 1) * 100) < 0.1
#from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
def analytical(n):
return sum(factorial(n) / pow(n, i) / float(factorial(n -i)) for i in range(1, n+1))
def testing(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
| <commit_before>#from http://rosettacode.org/wiki/Average_loop_length#Python
#pythran export analytical(int)
#pythran export testing(int, int)
#runas analytical(10)
#runas testing(10, 100)
#from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
def analytical(n):
return sum(factorial(n) / pow(n, i) / float(factorial(n -i)) for i in range(1, n+1))
def testing(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
<commit_msg>Fix test to have less random result<commit_after> | #from http://rosettacode.org/wiki/Average_loop_length#Python
#pythran export analytical(int)
#pythran export testing(int, int)
#runas analytical(10)
#runas avg = testing(10, 10**5); theory = analytical(10); abs((avg / theory - 1) * 100) < 0.1
#from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
def analytical(n):
return sum(factorial(n) / pow(n, i) / float(factorial(n -i)) for i in range(1, n+1))
def testing(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
| #from http://rosettacode.org/wiki/Average_loop_length#Python
#pythran export analytical(int)
#pythran export testing(int, int)
#runas analytical(10)
#runas testing(10, 100)
#from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
def analytical(n):
return sum(factorial(n) / pow(n, i) / float(factorial(n -i)) for i in range(1, n+1))
def testing(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
Fix test to have less random result#from http://rosettacode.org/wiki/Average_loop_length#Python
#pythran export analytical(int)
#pythran export testing(int, int)
#runas analytical(10)
#runas avg = testing(10, 10**5); theory = analytical(10); abs((avg / theory - 1) * 100) < 0.1
#from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
def analytical(n):
return sum(factorial(n) / pow(n, i) / float(factorial(n -i)) for i in range(1, n+1))
def testing(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
| <commit_before>#from http://rosettacode.org/wiki/Average_loop_length#Python
#pythran export analytical(int)
#pythran export testing(int, int)
#runas analytical(10)
#runas testing(10, 100)
#from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
def analytical(n):
return sum(factorial(n) / pow(n, i) / float(factorial(n -i)) for i in range(1, n+1))
def testing(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
<commit_msg>Fix test to have less random result<commit_after>#from http://rosettacode.org/wiki/Average_loop_length#Python
#pythran export analytical(int)
#pythran export testing(int, int)
#runas analytical(10)
#runas avg = testing(10, 10**5); theory = analytical(10); abs((avg / theory - 1) * 100) < 0.1
#from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
def analytical(n):
return sum(factorial(n) / pow(n, i) / float(factorial(n -i)) for i in range(1, n+1))
def testing(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
|
bd5f6ac7a9b801b53e7f7e0d4d84301a8f8652ef | program.py | program.py | import json
import csv
import requests
import secret
base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
response = requests.get('base_url/cumulative_player_stats.json',
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
| import json
import csv
import requests
from requests.auth import HTTPBasicAuth
import secret
base_url = 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/'
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
url = base_url + 'cumulative_player_stats.json?playerstats=Yds,Sacks,Int'
response = requests.get((url),
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
| Update function to get player stats using base_url | Update function to get player stats using base_url
| Python | mit | prcutler/nflpool,prcutler/nflpool | import json
import csv
import requests
import secret
base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
response = requests.get('base_url/cumulative_player_stats.json',
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
Update function to get player stats using base_url | import json
import csv
import requests
from requests.auth import HTTPBasicAuth
import secret
base_url = 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/'
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
url = base_url + 'cumulative_player_stats.json?playerstats=Yds,Sacks,Int'
response = requests.get((url),
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
| <commit_before>import json
import csv
import requests
import secret
base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
response = requests.get('base_url/cumulative_player_stats.json',
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
<commit_msg>Update function to get player stats using base_url<commit_after> | import json
import csv
import requests
from requests.auth import HTTPBasicAuth
import secret
base_url = 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/'
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
url = base_url + 'cumulative_player_stats.json?playerstats=Yds,Sacks,Int'
response = requests.get((url),
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
| import json
import csv
import requests
import secret
base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
response = requests.get('base_url/cumulative_player_stats.json',
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
Update function to get player stats using base_urlimport json
import csv
import requests
from requests.auth import HTTPBasicAuth
import secret
base_url = 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/'
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
url = base_url + 'cumulative_player_stats.json?playerstats=Yds,Sacks,Int'
response = requests.get((url),
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
| <commit_before>import json
import csv
import requests
import secret
base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
response = requests.get('base_url/cumulative_player_stats.json',
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
<commit_msg>Update function to get player stats using base_url<commit_after>import json
import csv
import requests
from requests.auth import HTTPBasicAuth
import secret
base_url = 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/'
def main():
division_standings()
playoff_standings()
playoff_standings()
player_stats()
points_for()
tiebreaker()
player_score()
# Get Division Standings for each team
def division_standings():
pass
# Get Playoff Standings for each team (need number 5 & 6 in each conference)
def playoff_standings():
pass
# Get individual statistics for each category
def player_stats():
url = base_url + 'cumulative_player_stats.json?playerstats=Yds,Sacks,Int'
response = requests.get((url),
auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw))
all_stats = response.json()
stats = all_stats["cumulativeplayerstats"]["playerstatsentry"]
# Get points for for the number one team in each conference:
def points_for():
pass
# Get the tiebreaker information
def tiebreaker():
pass
# Calculate the player scores
def player_score():
pass
if __name__ == '__main__':
main()
|
9c4bdc15c14e430edadff8a15c7f2db8a90cd90f | src/apps/core/context_processors.py | src/apps/core/context_processors.py | from django.conf import settings
def static(request):
"""Provides a context variable that differentiates between the base
JavaScript URL when in debug mode vs. not.
"""
CSS_URL = '{}stylesheets/css/'.format(settings.STATIC_URL)
JAVASCRIPT_URL = '{}scripts/javascript/'.format(settings.STATIC_URL)
if settings.DEBUG:
JAVASCRIPT_URL += 'src/'
else:
JAVASCRIPT_URL += 'min/'
return {
'CSS_URL': CSS_URL,
'JAVASCRIPT_URL': JAVASCRIPT_URL,
}
| import os
from django.conf import settings
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
| Clean up core static context processor | Clean up core static context processor | Python | bsd-2-clause | bruth/wicked-django-template,bruth/wicked-django-template,bruth/wicked-django-template | from django.conf import settings
def static(request):
"""Provides a context variable that differentiates between the base
JavaScript URL when in debug mode vs. not.
"""
CSS_URL = '{}stylesheets/css/'.format(settings.STATIC_URL)
JAVASCRIPT_URL = '{}scripts/javascript/'.format(settings.STATIC_URL)
if settings.DEBUG:
JAVASCRIPT_URL += 'src/'
else:
JAVASCRIPT_URL += 'min/'
return {
'CSS_URL': CSS_URL,
'JAVASCRIPT_URL': JAVASCRIPT_URL,
}
Clean up core static context processor | import os
from django.conf import settings
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
| <commit_before>from django.conf import settings
def static(request):
"""Provides a context variable that differentiates between the base
JavaScript URL when in debug mode vs. not.
"""
CSS_URL = '{}stylesheets/css/'.format(settings.STATIC_URL)
JAVASCRIPT_URL = '{}scripts/javascript/'.format(settings.STATIC_URL)
if settings.DEBUG:
JAVASCRIPT_URL += 'src/'
else:
JAVASCRIPT_URL += 'min/'
return {
'CSS_URL': CSS_URL,
'JAVASCRIPT_URL': JAVASCRIPT_URL,
}
<commit_msg>Clean up core static context processor<commit_after> | import os
from django.conf import settings
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
| from django.conf import settings
def static(request):
"""Provides a context variable that differentiates between the base
JavaScript URL when in debug mode vs. not.
"""
CSS_URL = '{}stylesheets/css/'.format(settings.STATIC_URL)
JAVASCRIPT_URL = '{}scripts/javascript/'.format(settings.STATIC_URL)
if settings.DEBUG:
JAVASCRIPT_URL += 'src/'
else:
JAVASCRIPT_URL += 'min/'
return {
'CSS_URL': CSS_URL,
'JAVASCRIPT_URL': JAVASCRIPT_URL,
}
Clean up core static context processorimport os
from django.conf import settings
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
| <commit_before>from django.conf import settings
def static(request):
"""Provides a context variable that differentiates between the base
JavaScript URL when in debug mode vs. not.
"""
CSS_URL = '{}stylesheets/css/'.format(settings.STATIC_URL)
JAVASCRIPT_URL = '{}scripts/javascript/'.format(settings.STATIC_URL)
if settings.DEBUG:
JAVASCRIPT_URL += 'src/'
else:
JAVASCRIPT_URL += 'min/'
return {
'CSS_URL': CSS_URL,
'JAVASCRIPT_URL': JAVASCRIPT_URL,
}
<commit_msg>Clean up core static context processor<commit_after>import os
from django.conf import settings
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
|
e53574e699203eb36ee6f2a22539a340605b61d4 | mockthink/test/conftest.py | mockthink/test/conftest.py | # coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="class")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
load_stock_data(request.cls.get_data(), conn)
return conn
| # coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="function")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
data = request.instance.get_data()
load_stock_data(data, conn)
# request.cls.addCleanup(load_stock_data, data, conn)
return conn
| Switch pytest fixture to function scope | Switch pytest fixture to function scope
Still use the class's get_data method for fixture data
| Python | mit | scivey/mockthink,deadscivey/mockthink | # coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="class")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
load_stock_data(request.cls.get_data(), conn)
return conn
Switch pytest fixture to function scope
Still use the class's get_data method for fixture data | # coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="function")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
data = request.instance.get_data()
load_stock_data(data, conn)
# request.cls.addCleanup(load_stock_data, data, conn)
return conn
| <commit_before># coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="class")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
load_stock_data(request.cls.get_data(), conn)
return conn
<commit_msg>Switch pytest fixture to function scope
Still use the class's get_data method for fixture data<commit_after> | # coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="function")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
data = request.instance.get_data()
load_stock_data(data, conn)
# request.cls.addCleanup(load_stock_data, data, conn)
return conn
| # coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="class")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
load_stock_data(request.cls.get_data(), conn)
return conn
Switch pytest fixture to function scope
Still use the class's get_data method for fixture data# coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="function")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
data = request.instance.get_data()
load_stock_data(data, conn)
# request.cls.addCleanup(load_stock_data, data, conn)
return conn
| <commit_before># coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="class")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
load_stock_data(request.cls.get_data(), conn)
return conn
<commit_msg>Switch pytest fixture to function scope
Still use the class's get_data method for fixture data<commit_after># coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="function")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
data = request.instance.get_data()
load_stock_data(data, conn)
# request.cls.addCleanup(load_stock_data, data, conn)
return conn
|
52d9ed9c08ef0686a891e3428349b70d74a7ecf8 | scripts/munge_fah_data.py | scripts/munge_fah_data.py | import numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, str(project), "allatoms/")
protein_output_path = os.path.join(output_path, str(project), "protein/")
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
| import numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, "allatoms/", "%s/" % project)
protein_output_path = os.path.join(output_path, "protein/", "%s/" % project)
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
| Change output data structure to support faster rsync | Change output data structure to support faster rsync
| Python | lgpl-2.1 | steven-albanese/FAHMunge,kyleabeauchamp/FAHMunge,choderalab/FAHMunge | import numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, str(project), "allatoms/")
protein_output_path = os.path.join(output_path, str(project), "protein/")
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
Change output data structure to support faster rsync | import numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, "allatoms/", "%s/" % project)
protein_output_path = os.path.join(output_path, "protein/", "%s/" % project)
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
| <commit_before>import numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, str(project), "allatoms/")
protein_output_path = os.path.join(output_path, str(project), "protein/")
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
<commit_msg>Change output data structure to support faster rsync<commit_after> | import numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, "allatoms/", "%s/" % project)
protein_output_path = os.path.join(output_path, "protein/", "%s/" % project)
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
| import numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, str(project), "allatoms/")
protein_output_path = os.path.join(output_path, str(project), "protein/")
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
Change output data structure to support faster rsyncimport numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, "allatoms/", "%s/" % project)
protein_output_path = os.path.join(output_path, "protein/", "%s/" % project)
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
| <commit_before>import numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, str(project), "allatoms/")
protein_output_path = os.path.join(output_path, str(project), "protein/")
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
<commit_msg>Change output data structure to support faster rsync<commit_after>import numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, "allatoms/", "%s/" % project)
protein_output_path = os.path.join(output_path, "protein/", "%s/" % project)
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
|
5ecde010ed93f5017a15899c53dbfdfc054d907f | indra/sources/hume/api.py | indra/sources/hume/api.py | __all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
| __all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r', encoding='utf-8') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
| Add encoding parameter to open jsonld | Add encoding parameter to open jsonld
| Python | bsd-2-clause | johnbachman/belpy,sorgerlab/belpy,bgyori/indra,sorgerlab/indra,johnbachman/indra,johnbachman/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,johnbachman/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/belpy | __all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
Add encoding parameter to open jsonld | __all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r', encoding='utf-8') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
| <commit_before>__all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
<commit_msg>Add encoding parameter to open jsonld<commit_after> | __all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r', encoding='utf-8') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
| __all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
Add encoding parameter to open jsonld__all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r', encoding='utf-8') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
| <commit_before>__all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
<commit_msg>Add encoding parameter to open jsonld<commit_after>__all__ = ['process_jsonld_file', 'process_jsonld']
import json
import logging
from indra.sources.hume import processor
logger = logging.getLogger(__name__)
def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r', encoding='utf-8') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict)
def process_jsonld(jsonld):
"""Process a JSON-LD string in the new format to extract Statements.
Parameters
----------
jsonld : dict
The JSON-LD object to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
hp = processor.HumeJsonLdProcessor(jsonld)
hp.extract_relations()
hp.extract_events()
return hp
|
2ab74cdb6adc979195f6ba60d5f8e9bf9dd4b74d | scikits/learn/__init__.py | scikits/learn/__init__.py | """
Machine Learning module in python
=================================
scikits.learn is a Python module integrating classique machine
learning algorithms in the tightly-nit world of scientific Python
packages (numpy, scipy, matplotlib).
It aims to provide simple and efficient solutions to learning problems
that are accessible to everybody and reusable in various contexts:
machine-learning as a versatile tool for science and engineering.
See http://scikit-learn.sourceforge.net for complete documentation.
"""
from .base import clone
from . import cross_val
from . import ball_tree
from . import cluster
from . import covariance
from . import gmm
from . import glm
from . import logistic
from . import lda
from . import metrics
from . import svm
from . import features
__all__ = ['cross_val', 'ball_tree', 'cluster', 'covariance', 'gmm', 'glm',
'logistic', 'lda', 'metrics', 'svm', 'features', 'clone']
__version__ = '0.5-git'
| """
Machine Learning module in python
=================================
scikits.learn is a Python module integrating classique machine
learning algorithms in the tightly-nit world of scientific Python
packages (numpy, scipy, matplotlib).
It aims to provide simple and efficient solutions to learning problems
that are accessible to everybody and reusable in various contexts:
machine-learning as a versatile tool for science and engineering.
See http://scikit-learn.sourceforge.net for complete documentation.
"""
from .base import clone
from . import cross_val
from . import ball_tree
from . import cluster
from . import covariance
from . import gmm
from . import glm
from . import logistic
from . import lda
from . import metrics
from . import svm
from . import features
try:
from numpy.testing import nosetester
class NoseTester(nosetester.NoseTester):
""" Subclass numpy's NoseTester to add doctests by default
"""
def test(self, label='fast', verbose=1, extra_argv=None,
doctests=True, coverage=False):
return super(NoseTester, self).test(label=label, verbose=verbose,
extra_argv=extra_argv,
doctests=doctests, coverage=coverage)
test = NoseTester().test
del nosetester
except:
pass
__all__ = ['cross_val', 'ball_tree', 'cluster', 'covariance', 'gmm', 'glm',
'logistic', 'lda', 'metrics', 'svm', 'features', 'clone',
'test']
__version__ = '0.5-git'
| Add a tester to the scikit. | ENH: Add a tester to the scikit.
| Python | bsd-3-clause | alexsavio/scikit-learn,joernhees/scikit-learn,shikhardb/scikit-learn,poryfly/scikit-learn,costypetrisor/scikit-learn,treycausey/scikit-learn,stylianos-kampakis/scikit-learn,alexsavio/scikit-learn,bigdataelephants/scikit-learn,costypetrisor/scikit-learn,stylianos-kampakis/scikit-learn,liangz0707/scikit-learn,nmayorov/scikit-learn,frank-tancf/scikit-learn,Achuth17/scikit-learn,PatrickOReilly/scikit-learn,Titan-C/scikit-learn,spallavolu/scikit-learn,jereze/scikit-learn,lesteve/scikit-learn,h2educ/scikit-learn,toastedcornflakes/scikit-learn,shikhardb/scikit-learn,simon-pepin/scikit-learn,466152112/scikit-learn,aflaxman/scikit-learn,Jimmy-Morzaria/scikit-learn,pnedunuri/scikit-learn,sinhrks/scikit-learn,victorbergelin/scikit-learn,meduz/scikit-learn,mjudsp/Tsallis,henrykironde/scikit-learn,jorge2703/scikit-learn,ElDeveloper/scikit-learn,vybstat/scikit-learn,liberatorqjw/scikit-learn,thientu/scikit-learn,mblondel/scikit-learn,siutanwong/scikit-learn,JeanKossaifi/scikit-learn,Srisai85/scikit-learn,ChanderG/scikit-learn,nhejazi/scikit-learn,rahul-c1/scikit-learn,yonglehou/scikit-learn,khkaminska/scikit-learn,rishikksh20/scikit-learn,billy-inn/scikit-learn,espg/scikit-learn,NunoEdgarGub1/scikit-learn,adamgreenhall/scikit-learn,nesterione/scikit-learn,arjoly/scikit-learn,vybstat/scikit-learn,robbymeals/scikit-learn,rsivapr/scikit-learn,jm-begon/scikit-learn,OshynSong/scikit-learn,Barmaley-exe/scikit-learn,vermouthmjl/scikit-learn,hugobowne/scikit-learn,loli/sklearn-ensembletrees,Akshay0724/scikit-learn,equialgo/scikit-learn,moutai/scikit-learn,Achuth17/scikit-learn,Akshay0724/scikit-learn,jakirkham/scikit-learn,YinongLong/scikit-learn,lucidfrontier45/scikit-learn,B3AU/waveTree,mwv/scikit-learn,ChanChiChoi/scikit-learn,B3AU/waveTree,russel1237/scikit-learn,qifeigit/scikit-learn,MechCoder/scikit-learn,466152112/scikit-learn,sanketloke/scikit-learn,liyu1990/sklearn,vortex-ape/scikit-learn,bnaul/scikit-learn,thientu/scikit-learn,jpautom/scikit-learn,heli522/scikit-learn,hlin117/scikit-learn,kagayakidan/scikit-learn,ycaihua/scikit-learn,moutai/scikit-learn,eg-zhang/scikit-learn,Jimmy-Morzaria/scikit-learn,Jimmy-Morzaria/scikit-learn,ishanic/scikit-learn,kashif/scikit-learn,xzh86/scikit-learn,3manuek/scikit-learn,dhruv13J/scikit-learn,eg-zhang/scikit-learn,jm-begon/scikit-learn,yonglehou/scikit-learn,simon-pepin/scikit-learn,jakobworldpeace/scikit-learn,arjoly/scikit-learn,bigdataelephants/scikit-learn,ElDeveloper/scikit-learn,pypot/scikit-learn,sumspr/scikit-learn,arabenjamin/scikit-learn,huzq/scikit-learn,russel1237/scikit-learn,michigraber/scikit-learn,frank-tancf/scikit-learn,AlexRobson/scikit-learn,robin-lai/scikit-learn,RPGOne/scikit-learn,NunoEdgarGub1/scikit-learn,MechCoder/scikit-learn,jorik041/scikit-learn,russel1237/scikit-learn,Titan-C/scikit-learn,rexshihaoren/scikit-learn,IndraVikas/scikit-learn,ZENGXH/scikit-learn,rsivapr/scikit-learn,roxyboy/scikit-learn,yanlend/scikit-learn,jmetzen/scikit-learn,ky822/scikit-learn,bikong2/scikit-learn,smartscheduling/scikit-learn-categorical-tree,bnaul/scikit-learn,potash/scikit-learn,nrhine1/scikit-learn,RPGOne/scikit-learn,equialgo/scikit-learn,Barmaley-exe/scikit-learn,mjudsp/Tsallis,ogrisel/scikit-learn,cybernet14/scikit-learn,h2educ/scikit-learn,nrhine1/scikit-learn,aetilley/scikit-learn,imaculate/scikit-learn,joernhees/scikit-learn,sonnyhu/scikit-learn,glemaitre/scikit-learn,massmutual/scikit-learn,jlegendary/scikit-learn,joshloyal/scikit-learn,ycaihua/scikit-learn,ngoix/OCRF,ephes/scikit-learn,shusenl/scikit-learn,ElDeveloper/scikit-learn,waterponey/scikit-learn,btabibian/scikit-learn,aflaxman/scikit-learn,giorgiop/scikit-learn,huobaowangxi/scikit-learn,ssaeger/scikit-learn,mugizico/scikit-learn,PatrickChrist/scikit-learn,xiaoxiamii/scikit-learn,bthirion/scikit-learn,hrjn/scikit-learn,etkirsch/scikit-learn,maheshakya/scikit-learn,jorik041/scikit-learn,robbymeals/scikit-learn,justincassidy/scikit-learn,aminert/scikit-learn,gotomypc/scikit-learn,vinayak-mehta/scikit-learn,hainm/scikit-learn,zaxtax/scikit-learn,rohanp/scikit-learn,bthirion/scikit-learn,khkaminska/scikit-learn,JPFrancoia/scikit-learn,CVML/scikit-learn,mikebenfield/scikit-learn,andaag/scikit-learn,qifeigit/scikit-learn,jayflo/scikit-learn,dsullivan7/scikit-learn,lenovor/scikit-learn,toastedcornflakes/scikit-learn,devanshdalal/scikit-learn,jorik041/scikit-learn,r-mart/scikit-learn,Obus/scikit-learn,kmike/scikit-learn,samuel1208/scikit-learn,stylianos-kampakis/scikit-learn,pythonvietnam/scikit-learn,ogrisel/scikit-learn,xzh86/scikit-learn,RachitKansal/scikit-learn,lin-credible/scikit-learn,luo66/scikit-learn,jjx02230808/project0223,shangwuhencc/scikit-learn,spallavolu/scikit-learn,IshankGulati/scikit-learn,appapantula/scikit-learn,glemaitre/scikit-learn,Srisai85/scikit-learn,mwv/scikit-learn,rrohan/scikit-learn,gclenaghan/scikit-learn,amueller/scikit-learn,shahankhatch/scikit-learn,yunfeilu/scikit-learn,poryfly/scikit-learn,Lawrence-Liu/scikit-learn,JsNoNo/scikit-learn,0asa/scikit-learn,hlin117/scikit-learn,loli/sklearn-ensembletrees,carrillo/scikit-learn,nikitasingh981/scikit-learn,cainiaocome/scikit-learn,xzh86/scikit-learn,jblackburne/scikit-learn,tdhopper/scikit-learn,macks22/scikit-learn,zuku1985/scikit-learn,alexsavio/scikit-learn,HolgerPeters/scikit-learn,ilyes14/scikit-learn,petosegan/scikit-learn,qifeigit/scikit-learn,rohanp/scikit-learn,abhishekgahlot/scikit-learn,ankurankan/scikit-learn,eickenberg/scikit-learn,quheng/scikit-learn,wlamond/scikit-learn,massmutual/scikit-learn,bhargav/scikit-learn,glennq/scikit-learn,rahul-c1/scikit-learn,IssamLaradji/scikit-learn,waterponey/scikit-learn,YinongLong/scikit-learn,mhdella/scikit-learn,jereze/scikit-learn,bigdataelephants/scikit-learn,altairpearl/scikit-learn,Vimos/scikit-learn,nikitasingh981/scikit-learn,ilo10/scikit-learn,xyguo/scikit-learn,lucidfrontier45/scikit-learn,robin-lai/scikit-learn,frank-tancf/scikit-learn,ashhher3/scikit-learn,xwolf12/scikit-learn,fabioticconi/scikit-learn,AnasGhrab/scikit-learn,ChanChiChoi/scikit-learn,henrykironde/scikit-learn,cdegroc/scikit-learn,jayflo/scikit-learn,jlegendary/scikit-learn,plissonf/scikit-learn,macks22/scikit-learn,kevin-intel/scikit-learn,olologin/scikit-learn,eickenberg/scikit-learn,Barmaley-exe/scikit-learn,TomDLT/scikit-learn,Aasmi/scikit-learn,bthirion/scikit-learn,cainiaocome/scikit-learn,rsivapr/scikit-learn,MartinDelzant/scikit-learn,nesterione/scikit-learn,samuel1208/scikit-learn,pompiduskus/scikit-learn,icdishb/scikit-learn,tawsifkhan/scikit-learn,aminert/scikit-learn,samzhang111/scikit-learn,r-mart/scikit-learn,ominux/scikit-learn,yanlend/scikit-learn,JosmanPS/scikit-learn,andrewnc/scikit-learn,OshynSong/scikit-learn,ClimbsRocks/scikit-learn,OshynSong/scikit-learn,lbishal/scikit-learn,scikit-learn/scikit-learn,mhdella/scikit-learn,lazywei/scikit-learn,yunfeilu/scikit-learn,dhruv13J/scikit-learn,TomDLT/scikit-learn,bigdataelephants/scikit-learn,xuewei4d/scikit-learn,AlexRobson/scikit-learn,depet/scikit-learn,shenzebang/scikit-learn,robbymeals/scikit-learn,Sentient07/scikit-learn,DSLituiev/scikit-learn,larsmans/scikit-learn,PrashntS/scikit-learn,idlead/scikit-learn,0x0all/scikit-learn,466152112/scikit-learn,LohithBlaze/scikit-learn,elkingtonmcb/scikit-learn,belltailjp/scikit-learn,mojoboss/scikit-learn,ashhher3/scikit-learn,ngoix/OCRF,thilbern/scikit-learn,abhishekgahlot/scikit-learn,jkarnows/scikit-learn,walterreade/scikit-learn,shusenl/scikit-learn,michigraber/scikit-learn,IndraVikas/scikit-learn,r-mart/scikit-learn,tosolveit/scikit-learn,Fireblend/scikit-learn,hsuantien/scikit-learn,LiaoPan/scikit-learn,glennq/scikit-learn,jayflo/scikit-learn,RachitKansal/scikit-learn,vibhorag/scikit-learn,fabioticconi/scikit-learn,lenovor/scikit-learn,zaxtax/scikit-learn,yunfeilu/scikit-learn,h2educ/scikit-learn,kevin-intel/scikit-learn,hlin117/scikit-learn,jkarnows/scikit-learn,btabibian/scikit-learn,dingocuster/scikit-learn,cl4rke/scikit-learn,ChanChiChoi/scikit-learn,LiaoPan/scikit-learn,HolgerPeters/scikit-learn,liyu1990/sklearn,dsquareindia/scikit-learn,betatim/scikit-learn,jseabold/scikit-learn,0x0all/scikit-learn,Myasuka/scikit-learn,kaichogami/scikit-learn,lucidfrontier45/scikit-learn,kylerbrown/scikit-learn,nvoron23/scikit-learn,xiaoxiamii/scikit-learn,treycausey/scikit-learn,arjoly/scikit-learn,beepee14/scikit-learn,MartinDelzant/scikit-learn,ominux/scikit-learn,cdegroc/scikit-learn,mattgiguere/scikit-learn,alvarofierroclavero/scikit-learn,jmschrei/scikit-learn,NelisVerhoef/scikit-learn,mugizico/scikit-learn,pnedunuri/scikit-learn,mikebenfield/scikit-learn,smartscheduling/scikit-learn-categorical-tree,MohammedWasim/scikit-learn,mojoboss/scikit-learn,spallavolu/scikit-learn,PatrickOReilly/scikit-learn,ClimbsRocks/scikit-learn,anntzer/scikit-learn,dsullivan7/scikit-learn,RachitKansal/scikit-learn,aabadie/scikit-learn,clemkoa/scikit-learn,vortex-ape/scikit-learn,IssamLaradji/scikit-learn,MartinSavc/scikit-learn,raghavrv/scikit-learn,treycausey/scikit-learn,amueller/scikit-learn,jpautom/scikit-learn,nomadcube/scikit-learn,rajat1994/scikit-learn,shikhardb/scikit-learn,CVML/scikit-learn,anntzer/scikit-learn,tawsifkhan/scikit-learn,ashhher3/scikit-learn,betatim/scikit-learn,wzbozon/scikit-learn,mayblue9/scikit-learn,untom/scikit-learn,Aasmi/scikit-learn,ishanic/scikit-learn,andrewnc/scikit-learn,tosolveit/scikit-learn,Srisai85/scikit-learn,MohammedWasim/scikit-learn,bhargav/scikit-learn,chrisburr/scikit-learn,simon-pepin/scikit-learn,JsNoNo/scikit-learn,fabianp/scikit-learn,dingocuster/scikit-learn,Akshay0724/scikit-learn,pypot/scikit-learn,rexshihaoren/scikit-learn,florian-f/sklearn,andaag/scikit-learn,altairpearl/scikit-learn,RomainBrault/scikit-learn,siutanwong/scikit-learn,mattgiguere/scikit-learn,terkkila/scikit-learn,shenzebang/scikit-learn,MatthieuBizien/scikit-learn,arahuja/scikit-learn,DSLituiev/scikit-learn,pratapvardhan/scikit-learn,themrmax/scikit-learn,rahuldhote/scikit-learn,joshloyal/scikit-learn,tmhm/scikit-learn,ldirer/scikit-learn,hugobowne/scikit-learn,manhhomienbienthuy/scikit-learn,petosegan/scikit-learn,jaidevd/scikit-learn,hdmetor/scikit-learn,liberatorqjw/scikit-learn,madjelan/scikit-learn,Clyde-fare/scikit-learn,jakirkham/scikit-learn,pnedunuri/scikit-learn,PatrickOReilly/scikit-learn,adamgreenhall/scikit-learn,466152112/scikit-learn,zihua/scikit-learn,huobaowangxi/scikit-learn,ominux/scikit-learn,3manuek/scikit-learn,Achuth17/scikit-learn,kmike/scikit-learn,gclenaghan/scikit-learn,clemkoa/scikit-learn,carrillo/scikit-learn,vshtanko/scikit-learn,YinongLong/scikit-learn,mhue/scikit-learn,BiaDarkia/scikit-learn,cybernet14/scikit-learn,q1ang/scikit-learn,belltailjp/scikit-learn,andrewnc/scikit-learn,CforED/Machine-Learning,depet/scikit-learn,gotomypc/scikit-learn,manhhomienbienthuy/scikit-learn,shangwuhencc/scikit-learn,nmayorov/scikit-learn,chrisburr/scikit-learn,bhargav/scikit-learn,nvoron23/scikit-learn,terkkila/scikit-learn,hsiaoyi0504/scikit-learn,trankmichael/scikit-learn,murali-munna/scikit-learn,imaculate/scikit-learn,belltailjp/scikit-learn,glemaitre/scikit-learn,jorge2703/scikit-learn,fabioticconi/scikit-learn,PrashntS/scikit-learn,mikebenfield/scikit-learn,dsullivan7/scikit-learn,toastedcornflakes/scikit-learn,ZENGXH/scikit-learn,nhejazi/scikit-learn,MartinSavc/scikit-learn,nvoron23/scikit-learn,kashif/scikit-learn,victorbergelin/scikit-learn,loli/semisupervisedforests,huobaowangxi/scikit-learn,samuel1208/scikit-learn,quheng/scikit-learn,Titan-C/scikit-learn,ahoyosid/scikit-learn,fbagirov/scikit-learn,Akshay0724/scikit-learn,plissonf/scikit-learn,ivannz/scikit-learn,krez13/scikit-learn,NunoEdgarGub1/scikit-learn,ningchi/scikit-learn,chrsrds/scikit-learn,ZenDevelopmentSystems/scikit-learn,kagayakidan/scikit-learn,ahoyosid/scikit-learn,loli/semisupervisedforests,JPFrancoia/scikit-learn,vibhorag/scikit-learn,xiaoxiamii/scikit-learn,PatrickChrist/scikit-learn,Windy-Ground/scikit-learn,pythonvietnam/scikit-learn,0asa/scikit-learn,yask123/scikit-learn,nelson-liu/scikit-learn,evgchz/scikit-learn,lucidfrontier45/scikit-learn,thilbern/scikit-learn,poryfly/scikit-learn,raghavrv/scikit-learn,hdmetor/scikit-learn,IshankGulati/scikit-learn,pv/scikit-learn,ky822/scikit-learn,mjudsp/Tsallis,elkingtonmcb/scikit-learn,pianomania/scikit-learn,huzq/scikit-learn,CVML/scikit-learn,khkaminska/scikit-learn,schets/scikit-learn,dsquareindia/scikit-learn,shyamalschandra/scikit-learn,arabenjamin/scikit-learn,appapantula/scikit-learn,fyffyt/scikit-learn,PrashntS/scikit-learn,sgenoud/scikit-learn,liyu1990/sklearn,Lawrence-Liu/scikit-learn,andaag/scikit-learn,sonnyhu/scikit-learn,liyu1990/sklearn,ltiao/scikit-learn,sonnyhu/scikit-learn,RPGOne/scikit-learn,ZenDevelopmentSystems/scikit-learn,rahul-c1/scikit-learn,kagayakidan/scikit-learn,cwu2011/scikit-learn,jakirkham/scikit-learn,jm-begon/scikit-learn,zorojean/scikit-learn,devanshdalal/scikit-learn,zuku1985/scikit-learn,mlyundin/scikit-learn,zorroblue/scikit-learn,mrshu/scikit-learn,andrewnc/scikit-learn,RomainBrault/scikit-learn,ElDeveloper/scikit-learn,rvraghav93/scikit-learn,samzhang111/scikit-learn,djgagne/scikit-learn,jkarnows/scikit-learn,hlin117/scikit-learn,liangz0707/scikit-learn,kaichogami/scikit-learn,chrsrds/scikit-learn,scikit-learn/scikit-learn,mattilyra/scikit-learn,fbagirov/scikit-learn,Djabbz/scikit-learn,sergeyf/scikit-learn,pianomania/scikit-learn,AIML/scikit-learn,mhdella/scikit-learn,iismd17/scikit-learn,stylianos-kampakis/scikit-learn,madjelan/scikit-learn,simon-pepin/scikit-learn,MechCoder/scikit-learn,MartinDelzant/scikit-learn,smartscheduling/scikit-learn-categorical-tree,sarahgrogan/scikit-learn,wazeerzulfikar/scikit-learn,akionakamura/scikit-learn,rvraghav93/scikit-learn,vigilv/scikit-learn,PrashntS/scikit-learn,huobaowangxi/scikit-learn,0x0all/scikit-learn,lesteve/scikit-learn,cwu2011/scikit-learn,sanketloke/scikit-learn,lesteve/scikit-learn,pv/scikit-learn,Aasmi/scikit-learn,sinhrks/scikit-learn,Titan-C/scikit-learn,luo66/scikit-learn,mattgiguere/scikit-learn,arabenjamin/scikit-learn,Aasmi/scikit-learn,nelson-liu/scikit-learn,vortex-ape/scikit-learn,ssaeger/scikit-learn,abimannans/scikit-learn,zihua/scikit-learn,kjung/scikit-learn,UNR-AERIAL/scikit-learn,rsivapr/scikit-learn,siutanwong/scikit-learn,zorojean/scikit-learn,anntzer/scikit-learn,samuel1208/scikit-learn,Srisai85/scikit-learn,yyjiang/scikit-learn,jjx02230808/project0223,rrohan/scikit-learn,arahuja/scikit-learn,JosmanPS/scikit-learn,RayMick/scikit-learn,beepee14/scikit-learn,lenovor/scikit-learn,davidgbe/scikit-learn,kjung/scikit-learn,hsiaoyi0504/scikit-learn,manashmndl/scikit-learn,khkaminska/scikit-learn,zhenv5/scikit-learn,HolgerPeters/scikit-learn,mjgrav2001/scikit-learn,sinhrks/scikit-learn,larsmans/scikit-learn,Windy-Ground/scikit-learn,shangwuhencc/scikit-learn,jmetzen/scikit-learn,NunoEdgarGub1/scikit-learn,loli/semisupervisedforests,Jimmy-Morzaria/scikit-learn,rvraghav93/scikit-learn,mfjb/scikit-learn,kjung/scikit-learn,alexeyum/scikit-learn,rvraghav93/scikit-learn,waterponey/scikit-learn,giorgiop/scikit-learn,YinongLong/scikit-learn,etkirsch/scikit-learn,JsNoNo/scikit-learn,kjung/scikit-learn,Vimos/scikit-learn,tawsifkhan/scikit-learn,luo66/scikit-learn,hainm/scikit-learn,equialgo/scikit-learn,shusenl/scikit-learn,mattgiguere/scikit-learn,hsuantien/scikit-learn,yonglehou/scikit-learn,lbishal/scikit-learn,ishanic/scikit-learn,wlamond/scikit-learn,equialgo/scikit-learn,wlamond/scikit-learn,potash/scikit-learn,kaichogami/scikit-learn,xuewei4d/scikit-learn,phdowling/scikit-learn,iismd17/scikit-learn,henrykironde/scikit-learn,rohanp/scikit-learn,mhdella/scikit-learn,jseabold/scikit-learn,RomainBrault/scikit-learn,alexeyum/scikit-learn,florian-f/sklearn,nesterione/scikit-learn,Myasuka/scikit-learn,maheshakya/scikit-learn,LiaoPan/scikit-learn,abimannans/scikit-learn,ldirer/scikit-learn,loli/sklearn-ensembletrees,rexshihaoren/scikit-learn,rahul-c1/scikit-learn,billy-inn/scikit-learn,plissonf/scikit-learn,fbagirov/scikit-learn,AnasGhrab/scikit-learn,phdowling/scikit-learn,TomDLT/scikit-learn,ChanderG/scikit-learn,Nyker510/scikit-learn,bnaul/scikit-learn,alvarofierroclavero/scikit-learn,JPFrancoia/scikit-learn,marcocaccin/scikit-learn,0x0all/scikit-learn,sinhrks/scikit-learn,ky822/scikit-learn,nrhine1/scikit-learn,RayMick/scikit-learn,madjelan/scikit-learn,costypetrisor/scikit-learn,imaculate/scikit-learn,meduz/scikit-learn,glemaitre/scikit-learn,nomadcube/scikit-learn,Windy-Ground/scikit-learn,hdmetor/scikit-learn,jblackburne/scikit-learn,ndingwall/scikit-learn,RayMick/scikit-learn,henridwyer/scikit-learn,sumspr/scikit-learn,espg/scikit-learn,PatrickOReilly/scikit-learn,Garrett-R/scikit-learn,zorojean/scikit-learn,abhishekkrthakur/scikit-learn,tosolveit/scikit-learn,samzhang111/scikit-learn,heli522/scikit-learn,zuku1985/scikit-learn,aewhatley/scikit-learn,rishikksh20/scikit-learn,mjgrav2001/scikit-learn,frank-tancf/scikit-learn,CforED/Machine-Learning,chrisburr/scikit-learn,rrohan/scikit-learn,smartscheduling/scikit-learn-categorical-tree,yyjiang/scikit-learn,michigraber/scikit-learn,vivekmishra1991/scikit-learn,mjgrav2001/scikit-learn,florian-f/sklearn,PatrickChrist/scikit-learn,ldirer/scikit-learn,mayblue9/scikit-learn,hitszxp/scikit-learn,akionakamura/scikit-learn,thientu/scikit-learn,krez13/scikit-learn,Clyde-fare/scikit-learn,yanlend/scikit-learn,cl4rke/scikit-learn,sarahgrogan/scikit-learn,xyguo/scikit-learn,aewhatley/scikit-learn,mrshu/scikit-learn,adamgreenhall/scikit-learn,rishikksh20/scikit-learn,AlexanderFabisch/scikit-learn,olologin/scikit-learn,B3AU/waveTree,mrshu/scikit-learn,poryfly/scikit-learn,lbishal/scikit-learn,mehdidc/scikit-learn,ngoix/OCRF,ilyes14/scikit-learn,fredhusser/scikit-learn,clemkoa/scikit-learn,pkruskal/scikit-learn,sgenoud/scikit-learn,jakirkham/scikit-learn,adamgreenhall/scikit-learn,vortex-ape/scikit-learn,vivekmishra1991/scikit-learn,MohammedWasim/scikit-learn,harshaneelhg/scikit-learn,plissonf/scikit-learn,ilo10/scikit-learn,rahuldhote/scikit-learn,abhishekkrthakur/scikit-learn,ngoix/OCRF,arjoly/scikit-learn,ltiao/scikit-learn,aflaxman/scikit-learn,IssamLaradji/scikit-learn,ltiao/scikit-learn,vibhorag/scikit-learn,djgagne/scikit-learn,trungnt13/scikit-learn,tdhopper/scikit-learn,theoryno3/scikit-learn,xavierwu/scikit-learn,depet/scikit-learn,ominux/scikit-learn,MatthieuBizien/scikit-learn,herilalaina/scikit-learn,fengzhyuan/scikit-learn,xzh86/scikit-learn,xwolf12/scikit-learn,trungnt13/scikit-learn,alexeyum/scikit-learn,abhishekkrthakur/scikit-learn,hitszxp/scikit-learn,phdowling/scikit-learn,lazywei/scikit-learn,iismd17/scikit-learn,betatim/scikit-learn,wanggang3333/scikit-learn,Garrett-R/scikit-learn,ephes/scikit-learn,JosmanPS/scikit-learn,walterreade/scikit-learn,pratapvardhan/scikit-learn,justincassidy/scikit-learn,pkruskal/scikit-learn,florian-f/sklearn,jm-begon/scikit-learn,lin-credible/scikit-learn,gotomypc/scikit-learn,mxjl620/scikit-learn,zaxtax/scikit-learn,vigilv/scikit-learn,zorroblue/scikit-learn,schets/scikit-learn,vshtanko/scikit-learn,0asa/scikit-learn,aetilley/scikit-learn,DonBeo/scikit-learn,mayblue9/scikit-learn,IssamLaradji/scikit-learn,murali-munna/scikit-learn,anurag313/scikit-learn,liangz0707/scikit-learn,AlexRobson/scikit-learn,amueller/scikit-learn,ldirer/scikit-learn,ycaihua/scikit-learn,Adai0808/scikit-learn,herilalaina/scikit-learn,trungnt13/scikit-learn,luo66/scikit-learn,Sentient07/scikit-learn,robin-lai/scikit-learn,ssaeger/scikit-learn,xubenben/scikit-learn,appapantula/scikit-learn,glouppe/scikit-learn,roxyboy/scikit-learn,ndingwall/scikit-learn,liberatorqjw/scikit-learn,liberatorqjw/scikit-learn,Adai0808/scikit-learn,procoder317/scikit-learn,beepee14/scikit-learn,pkruskal/scikit-learn,AlexanderFabisch/scikit-learn,ZENGXH/scikit-learn,Garrett-R/scikit-learn,aabadie/scikit-learn,Lawrence-Liu/scikit-learn,huzq/scikit-learn,abimannans/scikit-learn,wazeerzulfikar/scikit-learn,arahuja/scikit-learn,pompiduskus/scikit-learn,mojoboss/scikit-learn,murali-munna/scikit-learn,larsmans/scikit-learn,zihua/scikit-learn,Adai0808/scikit-learn,fyffyt/scikit-learn,ningchi/scikit-learn,madjelan/scikit-learn,fabianp/scikit-learn,LiaoPan/scikit-learn,espg/scikit-learn,lin-credible/scikit-learn,mrshu/scikit-learn,anirudhjayaraman/scikit-learn,bnaul/scikit-learn,mattilyra/scikit-learn,alvarofierroclavero/scikit-learn,roxyboy/scikit-learn,olologin/scikit-learn,giorgiop/scikit-learn,clemkoa/scikit-learn,voxlol/scikit-learn,djgagne/scikit-learn,victorbergelin/scikit-learn,kylerbrown/scikit-learn,yyjiang/scikit-learn,mlyundin/scikit-learn,jjx02230808/project0223,jorge2703/scikit-learn,jpautom/scikit-learn,btabibian/scikit-learn,siutanwong/scikit-learn,jmschrei/scikit-learn,mehdidc/scikit-learn,BiaDarkia/scikit-learn,fabianp/scikit-learn,RayMick/scikit-learn,ahoyosid/scikit-learn,scikit-learn/scikit-learn,nelson-liu/scikit-learn,liangz0707/scikit-learn,saiwing-yeung/scikit-learn,voxlol/scikit-learn,kevin-intel/scikit-learn,fzalkow/scikit-learn,saiwing-yeung/scikit-learn,florian-f/sklearn,justincassidy/scikit-learn,AnasGhrab/scikit-learn,sanketloke/scikit-learn,mfjb/scikit-learn,DonBeo/scikit-learn,trankmichael/scikit-learn,Barmaley-exe/scikit-learn,rajat1994/scikit-learn,icdishb/scikit-learn,ephes/scikit-learn,treycausey/scikit-learn,yunfeilu/scikit-learn,ilo10/scikit-learn,larsmans/scikit-learn,andaag/scikit-learn,tomlof/scikit-learn,moutai/scikit-learn,spallavolu/scikit-learn,fabioticconi/scikit-learn,shikhardb/scikit-learn,IndraVikas/scikit-learn,jaidevd/scikit-learn,jlegendary/scikit-learn,hrjn/scikit-learn,OshynSong/scikit-learn,imaculate/scikit-learn,cdegroc/scikit-learn,cauchycui/scikit-learn,amueller/scikit-learn,procoder317/scikit-learn,dhruv13J/scikit-learn,tdhopper/scikit-learn,ashhher3/scikit-learn,petosegan/scikit-learn,evgchz/scikit-learn,ssaeger/scikit-learn,fzalkow/scikit-learn,mlyundin/scikit-learn,kmike/scikit-learn,pythonvietnam/scikit-learn,jblackburne/scikit-learn,zorroblue/scikit-learn,abhishekgahlot/scikit-learn,iismd17/scikit-learn,untom/scikit-learn,manhhomienbienthuy/scikit-learn,aminert/scikit-learn,pv/scikit-learn,ankurankan/scikit-learn,saiwing-yeung/scikit-learn,DonBeo/scikit-learn,jereze/scikit-learn,henridwyer/scikit-learn,deepesch/scikit-learn,thilbern/scikit-learn,giorgiop/scikit-learn,harshaneelhg/scikit-learn,jzt5132/scikit-learn,jmetzen/scikit-learn,BiaDarkia/scikit-learn,aminert/scikit-learn,alexsavio/scikit-learn,fengzhyuan/scikit-learn,nhejazi/scikit-learn,Myasuka/scikit-learn,idlead/scikit-learn,treycausey/scikit-learn,lazywei/scikit-learn,shyamalschandra/scikit-learn,Nyker510/scikit-learn,shenzebang/scikit-learn,Adai0808/scikit-learn,tmhm/scikit-learn,nesterione/scikit-learn,mblondel/scikit-learn,JeanKossaifi/scikit-learn,tmhm/scikit-learn,q1ang/scikit-learn,hitszxp/scikit-learn,aabadie/scikit-learn,zihua/scikit-learn,q1ang/scikit-learn,herilalaina/scikit-learn,maheshakya/scikit-learn,Sentient07/scikit-learn,MatthieuBizien/scikit-learn,huzq/scikit-learn,mikebenfield/scikit-learn,shahankhatch/scikit-learn,belltailjp/scikit-learn,anirudhjayaraman/scikit-learn,mugizico/scikit-learn,jseabold/scikit-learn,xiaoxiamii/scikit-learn,fredhusser/scikit-learn,kagayakidan/scikit-learn,glennq/scikit-learn,shahankhatch/scikit-learn,LohithBlaze/scikit-learn,xavierwu/scikit-learn,fengzhyuan/scikit-learn,davidgbe/scikit-learn,AlexandreAbraham/scikit-learn,jakobworldpeace/scikit-learn,jaidevd/scikit-learn,manashmndl/scikit-learn,aewhatley/scikit-learn,yyjiang/scikit-learn,MatthieuBizien/scikit-learn,ivannz/scikit-learn,ZENGXH/scikit-learn,mxjl620/scikit-learn,massmutual/scikit-learn,Nyker510/scikit-learn,fzalkow/scikit-learn,rohanp/scikit-learn,manhhomienbienthuy/scikit-learn,sarahgrogan/scikit-learn,krez13/scikit-learn,fredhusser/scikit-learn,wlamond/scikit-learn,jzt5132/scikit-learn,DSLituiev/scikit-learn,beepee14/scikit-learn,anirudhjayaraman/scikit-learn,ycaihua/scikit-learn,B3AU/waveTree,pratapvardhan/scikit-learn,aetilley/scikit-learn,betatim/scikit-learn,pkruskal/scikit-learn,AlexandreAbraham/scikit-learn,joshloyal/scikit-learn,Windy-Ground/scikit-learn,dsquareindia/scikit-learn,yask123/scikit-learn,mxjl620/scikit-learn,f3r/scikit-learn,meduz/scikit-learn,hrjn/scikit-learn,schets/scikit-learn,fyffyt/scikit-learn,evgchz/scikit-learn,fbagirov/scikit-learn,AIML/scikit-learn,joernhees/scikit-learn,depet/scikit-learn,icdishb/scikit-learn,jorik041/scikit-learn,vermouthmjl/scikit-learn,lbishal/scikit-learn,pythonvietnam/scikit-learn,billy-inn/scikit-learn,vibhorag/scikit-learn,elkingtonmcb/scikit-learn,nomadcube/scikit-learn,jkarnows/scikit-learn,kashif/scikit-learn,sergeyf/scikit-learn,themrmax/scikit-learn,JeanKossaifi/scikit-learn,hugobowne/scikit-learn,shahankhatch/scikit-learn,lesteve/scikit-learn,etkirsch/scikit-learn,macks22/scikit-learn,meduz/scikit-learn,bikong2/scikit-learn,Obus/scikit-learn,nikitasingh981/scikit-learn,kashif/scikit-learn,xavierwu/scikit-learn,NelisVerhoef/scikit-learn,thilbern/scikit-learn,pompiduskus/scikit-learn,abimannans/scikit-learn,xubenben/scikit-learn,appapantula/scikit-learn,Garrett-R/scikit-learn,AnasGhrab/scikit-learn,abhishekgahlot/scikit-learn,jjx02230808/project0223,mfjb/scikit-learn,larsmans/scikit-learn,JPFrancoia/scikit-learn,lucidfrontier45/scikit-learn,sgenoud/scikit-learn,cl4rke/scikit-learn,cl4rke/scikit-learn,hsiaoyi0504/scikit-learn,victorbergelin/scikit-learn,UNR-AERIAL/scikit-learn,devanshdalal/scikit-learn,mehdidc/scikit-learn,davidgbe/scikit-learn,pypot/scikit-learn,carrillo/scikit-learn,rexshihaoren/scikit-learn,Fireblend/scikit-learn,AlexandreAbraham/scikit-learn,vermouthmjl/scikit-learn,xwolf12/scikit-learn,cwu2011/scikit-learn,wzbozon/scikit-learn,altairpearl/scikit-learn,potash/scikit-learn,tomlof/scikit-learn,LohithBlaze/scikit-learn,terkkila/scikit-learn,0asa/scikit-learn,vybstat/scikit-learn,joernhees/scikit-learn,Clyde-fare/scikit-learn,untom/scikit-learn,theoryno3/scikit-learn,cainiaocome/scikit-learn,vshtanko/scikit-learn,ivannz/scikit-learn,akionakamura/scikit-learn,abhishekkrthakur/scikit-learn,kylerbrown/scikit-learn,billy-inn/scikit-learn,f3r/scikit-learn,BiaDarkia/scikit-learn,phdowling/scikit-learn,lenovor/scikit-learn,altairpearl/scikit-learn,rrohan/scikit-learn,ZenDevelopmentSystems/scikit-learn,petosegan/scikit-learn,AlexanderFabisch/scikit-learn,ephes/scikit-learn,xubenben/scikit-learn,samzhang111/scikit-learn,Nyker510/scikit-learn,glennq/scikit-learn,fzalkow/scikit-learn,hitszxp/scikit-learn,cwu2011/scikit-learn,ankurankan/scikit-learn,russel1237/scikit-learn,vigilv/scikit-learn,harshaneelhg/scikit-learn,shyamalschandra/scikit-learn,vermouthmjl/scikit-learn,LohithBlaze/scikit-learn,h2educ/scikit-learn,sanketloke/scikit-learn,vivekmishra1991/scikit-learn,mhue/scikit-learn,jblackburne/scikit-learn,btabibian/scikit-learn,robbymeals/scikit-learn,AIML/scikit-learn,eickenberg/scikit-learn,etkirsch/scikit-learn,vigilv/scikit-learn,JsNoNo/scikit-learn,tomlof/scikit-learn,Lawrence-Liu/scikit-learn,robin-lai/scikit-learn,devanshdalal/scikit-learn,eg-zhang/scikit-learn,yask123/scikit-learn,kaichogami/scikit-learn,shusenl/scikit-learn,depet/scikit-learn,loli/sklearn-ensembletrees,mblondel/scikit-learn,glouppe/scikit-learn,hsuantien/scikit-learn,gotomypc/scikit-learn,espg/scikit-learn,mattilyra/scikit-learn,JeanKossaifi/scikit-learn,hainm/scikit-learn,rajat1994/scikit-learn,lazywei/scikit-learn,jayflo/scikit-learn,arahuja/scikit-learn,heli522/scikit-learn,marcocaccin/scikit-learn,tdhopper/scikit-learn,Obus/scikit-learn,IshankGulati/scikit-learn,mehdidc/scikit-learn,ltiao/scikit-learn,sergeyf/scikit-learn,quheng/scikit-learn,hsiaoyi0504/scikit-learn,eg-zhang/scikit-learn,q1ang/scikit-learn,zaxtax/scikit-learn,alvarofierroclavero/scikit-learn,wanggang3333/scikit-learn,ogrisel/scikit-learn,cauchycui/scikit-learn,glouppe/scikit-learn,djgagne/scikit-learn,chrisburr/scikit-learn,ningchi/scikit-learn,aewhatley/scikit-learn,cainiaocome/scikit-learn,gclenaghan/scikit-learn,sumspr/scikit-learn,chrsrds/scikit-learn,joshloyal/scikit-learn,wazeerzulfikar/scikit-learn,mojoboss/scikit-learn,zorroblue/scikit-learn,hsuantien/scikit-learn,3manuek/scikit-learn,jmetzen/scikit-learn,IshankGulati/scikit-learn,henrykironde/scikit-learn,justincassidy/scikit-learn,roxyboy/scikit-learn,kevin-intel/scikit-learn,vinayak-mehta/scikit-learn,PatrickChrist/scikit-learn,sarahgrogan/scikit-learn,walterreade/scikit-learn,loli/semisupervisedforests,mjudsp/Tsallis,heli522/scikit-learn,potash/scikit-learn,yask123/scikit-learn,dhruv13J/scikit-learn,Fireblend/scikit-learn,eickenberg/scikit-learn,Djabbz/scikit-learn,wanggang3333/scikit-learn,sgenoud/scikit-learn,Vimos/scikit-learn,fabianp/scikit-learn,3manuek/scikit-learn,jmschrei/scikit-learn,xyguo/scikit-learn,0asa/scikit-learn,xwolf12/scikit-learn,ChanChiChoi/scikit-learn,ilyes14/scikit-learn,dingocuster/scikit-learn,mhue/scikit-learn,fyffyt/scikit-learn,jakobworldpeace/scikit-learn,bthirion/scikit-learn,jmschrei/scikit-learn,deepesch/scikit-learn,vinayak-mehta/scikit-learn,macks22/scikit-learn,manashmndl/scikit-learn,procoder317/scikit-learn,Garrett-R/scikit-learn,rajat1994/scikit-learn,jlegendary/scikit-learn,loli/sklearn-ensembletrees,scikit-learn/scikit-learn,MartinDelzant/scikit-learn,cauchycui/scikit-learn,xavierwu/scikit-learn,evgchz/scikit-learn,icdishb/scikit-learn,Sentient07/scikit-learn,mattilyra/scikit-learn,arabenjamin/scikit-learn,DonBeo/scikit-learn,jzt5132/scikit-learn,f3r/scikit-learn,sumspr/scikit-learn,olologin/scikit-learn,mxjl620/scikit-learn,hainm/scikit-learn,harshaneelhg/scikit-learn,cybernet14/scikit-learn,jakobworldpeace/scikit-learn,rishikksh20/scikit-learn,michigraber/scikit-learn,saiwing-yeung/scikit-learn,DSLituiev/scikit-learn,ivannz/scikit-learn,idlead/scikit-learn,costypetrisor/scikit-learn,thientu/scikit-learn,jereze/scikit-learn,RPGOne/scikit-learn,trankmichael/scikit-learn,zhenv5/scikit-learn,raghavrv/scikit-learn,HolgerPeters/scikit-learn,ChanderG/scikit-learn,pnedunuri/scikit-learn,zhenv5/scikit-learn,waterponey/scikit-learn,nelson-liu/scikit-learn,ClimbsRocks/scikit-learn,shyamalschandra/scikit-learn,murali-munna/scikit-learn,manashmndl/scikit-learn,anirudhjayaraman/scikit-learn,Achuth17/scikit-learn,hdmetor/scikit-learn,xuewei4d/scikit-learn,mjgrav2001/scikit-learn,MartinSavc/scikit-learn,kmike/scikit-learn,theoryno3/scikit-learn,krez13/scikit-learn,ClimbsRocks/scikit-learn,sgenoud/scikit-learn,mblondel/scikit-learn,gclenaghan/scikit-learn,RomainBrault/scikit-learn,herilalaina/scikit-learn,vybstat/scikit-learn,pratapvardhan/scikit-learn,untom/scikit-learn,ilyes14/scikit-learn,nomadcube/scikit-learn,ankurankan/scikit-learn,CforED/Machine-Learning,mrshu/scikit-learn,mwv/scikit-learn,nhejazi/scikit-learn,mlyundin/scikit-learn,wanggang3333/scikit-learn,f3r/scikit-learn,chrsrds/scikit-learn,mjudsp/Tsallis,B3AU/waveTree,deepesch/scikit-learn,zhenv5/scikit-learn,shangwuhencc/scikit-learn,rahuldhote/scikit-learn,jpautom/scikit-learn,quheng/scikit-learn,henridwyer/scikit-learn,nmayorov/scikit-learn,TomDLT/scikit-learn,jaidevd/scikit-learn,moutai/scikit-learn,Vimos/scikit-learn,CforED/Machine-Learning,IndraVikas/scikit-learn,xubenben/scikit-learn,henridwyer/scikit-learn,cauchycui/scikit-learn,0x0all/scikit-learn,fengzhyuan/scikit-learn,voxlol/scikit-learn,mhue/scikit-learn,vinayak-mehta/scikit-learn,dsquareindia/scikit-learn,themrmax/scikit-learn,Clyde-fare/scikit-learn,tosolveit/scikit-learn,rsivapr/scikit-learn,tawsifkhan/scikit-learn,toastedcornflakes/scikit-learn,procoder317/scikit-learn,aflaxman/scikit-learn,pypot/scikit-learn,mattilyra/scikit-learn,nvoron23/scikit-learn,AIML/scikit-learn,bikong2/scikit-learn,zorojean/scikit-learn,maheshakya/scikit-learn,alexeyum/scikit-learn,kmike/scikit-learn,hugobowne/scikit-learn,terkkila/scikit-learn,aabadie/scikit-learn,ogrisel/scikit-learn,idlead/scikit-learn,yonglehou/scikit-learn,MartinSavc/scikit-learn,dsullivan7/scikit-learn,AlexanderFabisch/scikit-learn,marcocaccin/scikit-learn,jorge2703/scikit-learn,shenzebang/scikit-learn,r-mart/scikit-learn,jzt5132/scikit-learn,hitszxp/scikit-learn,ishanic/scikit-learn,ngoix/OCRF,xyguo/scikit-learn,xuewei4d/scikit-learn,fredhusser/scikit-learn,ky822/scikit-learn,pompiduskus/scikit-learn,cybernet14/scikit-learn,walterreade/scikit-learn,aetilley/scikit-learn,tmhm/scikit-learn,mayblue9/scikit-learn,tomlof/scikit-learn,mugizico/scikit-learn,glouppe/scikit-learn,wzbozon/scikit-learn,ahoyosid/scikit-learn,RachitKansal/scikit-learn,dingocuster/scikit-learn,Obus/scikit-learn,pianomania/scikit-learn,ningchi/scikit-learn,zuku1985/scikit-learn,ngoix/OCRF,Djabbz/scikit-learn,themrmax/scikit-learn,ndingwall/scikit-learn,NelisVerhoef/scikit-learn,qifeigit/scikit-learn,wzbozon/scikit-learn,voxlol/scikit-learn,nikitasingh981/scikit-learn,MohammedWasim/scikit-learn,bikong2/scikit-learn,maheshakya/scikit-learn,anntzer/scikit-learn,davidgbe/scikit-learn,cdegroc/scikit-learn,bhargav/scikit-learn,sergeyf/scikit-learn,Djabbz/scikit-learn,ZenDevelopmentSystems/scikit-learn,CVML/scikit-learn,ndingwall/scikit-learn,vivekmishra1991/scikit-learn,Fireblend/scikit-learn,AlexRobson/scikit-learn,pianomania/scikit-learn,deepesch/scikit-learn,rahuldhote/scikit-learn,kylerbrown/scikit-learn,ilo10/scikit-learn,theoryno3/scikit-learn,Myasuka/scikit-learn,massmutual/scikit-learn,NelisVerhoef/scikit-learn,raghavrv/scikit-learn,sonnyhu/scikit-learn,carrillo/scikit-learn,nmayorov/scikit-learn,JosmanPS/scikit-learn,mwv/scikit-learn,evgchz/scikit-learn,anurag313/scikit-learn,ChanderG/scikit-learn,anurag313/scikit-learn,pv/scikit-learn,lin-credible/scikit-learn,jseabold/scikit-learn,AlexandreAbraham/scikit-learn,schets/scikit-learn,yanlend/scikit-learn,akionakamura/scikit-learn,anurag313/scikit-learn,trungnt13/scikit-learn,abhishekgahlot/scikit-learn,ankurankan/scikit-learn,nrhine1/scikit-learn,hrjn/scikit-learn,elkingtonmcb/scikit-learn,mfjb/scikit-learn,vshtanko/scikit-learn,marcocaccin/scikit-learn,ycaihua/scikit-learn,MechCoder/scikit-learn,eickenberg/scikit-learn,UNR-AERIAL/scikit-learn,wazeerzulfikar/scikit-learn,trankmichael/scikit-learn,UNR-AERIAL/scikit-learn | """
Machine Learning module in python
=================================
scikits.learn is a Python module integrating classique machine
learning algorithms in the tightly-nit world of scientific Python
packages (numpy, scipy, matplotlib).
It aims to provide simple and efficient solutions to learning problems
that are accessible to everybody and reusable in various contexts:
machine-learning as a versatile tool for science and engineering.
See http://scikit-learn.sourceforge.net for complete documentation.
"""
from .base import clone
from . import cross_val
from . import ball_tree
from . import cluster
from . import covariance
from . import gmm
from . import glm
from . import logistic
from . import lda
from . import metrics
from . import svm
from . import features
__all__ = ['cross_val', 'ball_tree', 'cluster', 'covariance', 'gmm', 'glm',
'logistic', 'lda', 'metrics', 'svm', 'features', 'clone']
__version__ = '0.5-git'
ENH: Add a tester to the scikit. | """
Machine Learning module in python
=================================
scikits.learn is a Python module integrating classique machine
learning algorithms in the tightly-nit world of scientific Python
packages (numpy, scipy, matplotlib).
It aims to provide simple and efficient solutions to learning problems
that are accessible to everybody and reusable in various contexts:
machine-learning as a versatile tool for science and engineering.
See http://scikit-learn.sourceforge.net for complete documentation.
"""
from .base import clone
from . import cross_val
from . import ball_tree
from . import cluster
from . import covariance
from . import gmm
from . import glm
from . import logistic
from . import lda
from . import metrics
from . import svm
from . import features
try:
from numpy.testing import nosetester
class NoseTester(nosetester.NoseTester):
""" Subclass numpy's NoseTester to add doctests by default
"""
def test(self, label='fast', verbose=1, extra_argv=None,
doctests=True, coverage=False):
return super(NoseTester, self).test(label=label, verbose=verbose,
extra_argv=extra_argv,
doctests=doctests, coverage=coverage)
test = NoseTester().test
del nosetester
except:
pass
__all__ = ['cross_val', 'ball_tree', 'cluster', 'covariance', 'gmm', 'glm',
'logistic', 'lda', 'metrics', 'svm', 'features', 'clone',
'test']
__version__ = '0.5-git'
| <commit_before>"""
Machine Learning module in python
=================================
scikits.learn is a Python module integrating classique machine
learning algorithms in the tightly-nit world of scientific Python
packages (numpy, scipy, matplotlib).
It aims to provide simple and efficient solutions to learning problems
that are accessible to everybody and reusable in various contexts:
machine-learning as a versatile tool for science and engineering.
See http://scikit-learn.sourceforge.net for complete documentation.
"""
from .base import clone
from . import cross_val
from . import ball_tree
from . import cluster
from . import covariance
from . import gmm
from . import glm
from . import logistic
from . import lda
from . import metrics
from . import svm
from . import features
__all__ = ['cross_val', 'ball_tree', 'cluster', 'covariance', 'gmm', 'glm',
'logistic', 'lda', 'metrics', 'svm', 'features', 'clone']
__version__ = '0.5-git'
<commit_msg>ENH: Add a tester to the scikit.<commit_after> | """
Machine Learning module in python
=================================
scikits.learn is a Python module integrating classique machine
learning algorithms in the tightly-nit world of scientific Python
packages (numpy, scipy, matplotlib).
It aims to provide simple and efficient solutions to learning problems
that are accessible to everybody and reusable in various contexts:
machine-learning as a versatile tool for science and engineering.
See http://scikit-learn.sourceforge.net for complete documentation.
"""
from .base import clone
from . import cross_val
from . import ball_tree
from . import cluster
from . import covariance
from . import gmm
from . import glm
from . import logistic
from . import lda
from . import metrics
from . import svm
from . import features
try:
from numpy.testing import nosetester
class NoseTester(nosetester.NoseTester):
""" Subclass numpy's NoseTester to add doctests by default
"""
def test(self, label='fast', verbose=1, extra_argv=None,
doctests=True, coverage=False):
return super(NoseTester, self).test(label=label, verbose=verbose,
extra_argv=extra_argv,
doctests=doctests, coverage=coverage)
test = NoseTester().test
del nosetester
except:
pass
__all__ = ['cross_val', 'ball_tree', 'cluster', 'covariance', 'gmm', 'glm',
'logistic', 'lda', 'metrics', 'svm', 'features', 'clone',
'test']
__version__ = '0.5-git'
| """
Machine Learning module in python
=================================
scikits.learn is a Python module integrating classique machine
learning algorithms in the tightly-nit world of scientific Python
packages (numpy, scipy, matplotlib).
It aims to provide simple and efficient solutions to learning problems
that are accessible to everybody and reusable in various contexts:
machine-learning as a versatile tool for science and engineering.
See http://scikit-learn.sourceforge.net for complete documentation.
"""
from .base import clone
from . import cross_val
from . import ball_tree
from . import cluster
from . import covariance
from . import gmm
from . import glm
from . import logistic
from . import lda
from . import metrics
from . import svm
from . import features
__all__ = ['cross_val', 'ball_tree', 'cluster', 'covariance', 'gmm', 'glm',
'logistic', 'lda', 'metrics', 'svm', 'features', 'clone']
__version__ = '0.5-git'
ENH: Add a tester to the scikit."""
Machine Learning module in python
=================================
scikits.learn is a Python module integrating classique machine
learning algorithms in the tightly-nit world of scientific Python
packages (numpy, scipy, matplotlib).
It aims to provide simple and efficient solutions to learning problems
that are accessible to everybody and reusable in various contexts:
machine-learning as a versatile tool for science and engineering.
See http://scikit-learn.sourceforge.net for complete documentation.
"""
from .base import clone
from . import cross_val
from . import ball_tree
from . import cluster
from . import covariance
from . import gmm
from . import glm
from . import logistic
from . import lda
from . import metrics
from . import svm
from . import features
try:
from numpy.testing import nosetester
class NoseTester(nosetester.NoseTester):
""" Subclass numpy's NoseTester to add doctests by default
"""
def test(self, label='fast', verbose=1, extra_argv=None,
doctests=True, coverage=False):
return super(NoseTester, self).test(label=label, verbose=verbose,
extra_argv=extra_argv,
doctests=doctests, coverage=coverage)
test = NoseTester().test
del nosetester
except:
pass
__all__ = ['cross_val', 'ball_tree', 'cluster', 'covariance', 'gmm', 'glm',
'logistic', 'lda', 'metrics', 'svm', 'features', 'clone',
'test']
__version__ = '0.5-git'
| <commit_before>"""
Machine Learning module in python
=================================
scikits.learn is a Python module integrating classique machine
learning algorithms in the tightly-nit world of scientific Python
packages (numpy, scipy, matplotlib).
It aims to provide simple and efficient solutions to learning problems
that are accessible to everybody and reusable in various contexts:
machine-learning as a versatile tool for science and engineering.
See http://scikit-learn.sourceforge.net for complete documentation.
"""
from .base import clone
from . import cross_val
from . import ball_tree
from . import cluster
from . import covariance
from . import gmm
from . import glm
from . import logistic
from . import lda
from . import metrics
from . import svm
from . import features
__all__ = ['cross_val', 'ball_tree', 'cluster', 'covariance', 'gmm', 'glm',
'logistic', 'lda', 'metrics', 'svm', 'features', 'clone']
__version__ = '0.5-git'
<commit_msg>ENH: Add a tester to the scikit.<commit_after>"""
Machine Learning module in python
=================================
scikits.learn is a Python module integrating classique machine
learning algorithms in the tightly-nit world of scientific Python
packages (numpy, scipy, matplotlib).
It aims to provide simple and efficient solutions to learning problems
that are accessible to everybody and reusable in various contexts:
machine-learning as a versatile tool for science and engineering.
See http://scikit-learn.sourceforge.net for complete documentation.
"""
from .base import clone
from . import cross_val
from . import ball_tree
from . import cluster
from . import covariance
from . import gmm
from . import glm
from . import logistic
from . import lda
from . import metrics
from . import svm
from . import features
try:
from numpy.testing import nosetester
class NoseTester(nosetester.NoseTester):
""" Subclass numpy's NoseTester to add doctests by default
"""
def test(self, label='fast', verbose=1, extra_argv=None,
doctests=True, coverage=False):
return super(NoseTester, self).test(label=label, verbose=verbose,
extra_argv=extra_argv,
doctests=doctests, coverage=coverage)
test = NoseTester().test
del nosetester
except:
pass
__all__ = ['cross_val', 'ball_tree', 'cluster', 'covariance', 'gmm', 'glm',
'logistic', 'lda', 'metrics', 'svm', 'features', 'clone',
'test']
__version__ = '0.5-git'
|
ce2c22fb3616fbfdaf3a5c1f1de3f2fa1fc9f76f | proselint/checks/lilienfeld/terms_to_avoid.py | proselint/checks/lilienfeld/terms_to_avoid.py | # -*- coding: utf-8 -*-
"""Psychological and psychiatric terms to avoid.
---
layout: post
source: Scott O. Lilienfeld, et al.
source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100
title: psychological and psychiatric terms to avoid
date: 2014-06-10 12:31:19
categories: writing
---
Psychological and psychiatric terms to avoid.
"""
from tools import preferred_forms_check, memoize
@memoize
def check_lie_detector_test(text):
"""Suggest the preferred forms."""
err = "lilienfeld.terms_to_avoid.lie_detector"
msg = "Polygraph machines measure arousal, not lying per se. Try {}."
list = [
["polygraph test", ["lie detector test"]],
["polygraph machine", ["lie detector machine"]],
]
return preferred_forms_check(text, list, err, msg)
| # -*- coding: utf-8 -*-
"""Psychological and psychiatric terms to avoid.
---
layout: post
source: Scott O. Lilienfeld, et al.
source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100
title: psychological and psychiatric terms to avoid
date: 2014-06-10 12:31:19
categories: writing
---
Psychological and psychiatric terms to avoid.
"""
from tools import preferred_forms_check, existence_check, memoize
@memoize
def check_lie_detector_test(text):
"""Suggest the preferred forms."""
err = "lilienfeld.terms_to_avoid.lie_detector"
msg = "Polygraph machines measure arousal, not lying per se. Try {}."
list = [
["polygraph test", ["lie detector test"]],
["polygraph machine", ["lie detector machine"]],
]
return preferred_forms_check(text, list, err, msg)
@memoize
def check_p_equals_zero(text):
"""Check for p = 0.000."""
err = "lilienfeld.terms_to_avoid.p_equals_zero"
msg = "Unless p really equals zero, you should use more decimal places."
list = [
"p = 0.00",
"p = 0.000",
"p = 0.0000",
]
return existence_check(text, list, err, msg, join=True)
| Check for p = 0.00 | Check for p = 0.00
#149
| Python | bsd-3-clause | jstewmon/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint | # -*- coding: utf-8 -*-
"""Psychological and psychiatric terms to avoid.
---
layout: post
source: Scott O. Lilienfeld, et al.
source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100
title: psychological and psychiatric terms to avoid
date: 2014-06-10 12:31:19
categories: writing
---
Psychological and psychiatric terms to avoid.
"""
from tools import preferred_forms_check, memoize
@memoize
def check_lie_detector_test(text):
"""Suggest the preferred forms."""
err = "lilienfeld.terms_to_avoid.lie_detector"
msg = "Polygraph machines measure arousal, not lying per se. Try {}."
list = [
["polygraph test", ["lie detector test"]],
["polygraph machine", ["lie detector machine"]],
]
return preferred_forms_check(text, list, err, msg)
Check for p = 0.00
#149 | # -*- coding: utf-8 -*-
"""Psychological and psychiatric terms to avoid.
---
layout: post
source: Scott O. Lilienfeld, et al.
source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100
title: psychological and psychiatric terms to avoid
date: 2014-06-10 12:31:19
categories: writing
---
Psychological and psychiatric terms to avoid.
"""
from tools import preferred_forms_check, existence_check, memoize
@memoize
def check_lie_detector_test(text):
"""Suggest the preferred forms."""
err = "lilienfeld.terms_to_avoid.lie_detector"
msg = "Polygraph machines measure arousal, not lying per se. Try {}."
list = [
["polygraph test", ["lie detector test"]],
["polygraph machine", ["lie detector machine"]],
]
return preferred_forms_check(text, list, err, msg)
@memoize
def check_p_equals_zero(text):
"""Check for p = 0.000."""
err = "lilienfeld.terms_to_avoid.p_equals_zero"
msg = "Unless p really equals zero, you should use more decimal places."
list = [
"p = 0.00",
"p = 0.000",
"p = 0.0000",
]
return existence_check(text, list, err, msg, join=True)
| <commit_before># -*- coding: utf-8 -*-
"""Psychological and psychiatric terms to avoid.
---
layout: post
source: Scott O. Lilienfeld, et al.
source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100
title: psychological and psychiatric terms to avoid
date: 2014-06-10 12:31:19
categories: writing
---
Psychological and psychiatric terms to avoid.
"""
from tools import preferred_forms_check, memoize
@memoize
def check_lie_detector_test(text):
"""Suggest the preferred forms."""
err = "lilienfeld.terms_to_avoid.lie_detector"
msg = "Polygraph machines measure arousal, not lying per se. Try {}."
list = [
["polygraph test", ["lie detector test"]],
["polygraph machine", ["lie detector machine"]],
]
return preferred_forms_check(text, list, err, msg)
<commit_msg>Check for p = 0.00
#149<commit_after> | # -*- coding: utf-8 -*-
"""Psychological and psychiatric terms to avoid.
---
layout: post
source: Scott O. Lilienfeld, et al.
source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100
title: psychological and psychiatric terms to avoid
date: 2014-06-10 12:31:19
categories: writing
---
Psychological and psychiatric terms to avoid.
"""
from tools import preferred_forms_check, existence_check, memoize
@memoize
def check_lie_detector_test(text):
"""Suggest the preferred forms."""
err = "lilienfeld.terms_to_avoid.lie_detector"
msg = "Polygraph machines measure arousal, not lying per se. Try {}."
list = [
["polygraph test", ["lie detector test"]],
["polygraph machine", ["lie detector machine"]],
]
return preferred_forms_check(text, list, err, msg)
@memoize
def check_p_equals_zero(text):
"""Check for p = 0.000."""
err = "lilienfeld.terms_to_avoid.p_equals_zero"
msg = "Unless p really equals zero, you should use more decimal places."
list = [
"p = 0.00",
"p = 0.000",
"p = 0.0000",
]
return existence_check(text, list, err, msg, join=True)
| # -*- coding: utf-8 -*-
"""Psychological and psychiatric terms to avoid.
---
layout: post
source: Scott O. Lilienfeld, et al.
source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100
title: psychological and psychiatric terms to avoid
date: 2014-06-10 12:31:19
categories: writing
---
Psychological and psychiatric terms to avoid.
"""
from tools import preferred_forms_check, memoize
@memoize
def check_lie_detector_test(text):
"""Suggest the preferred forms."""
err = "lilienfeld.terms_to_avoid.lie_detector"
msg = "Polygraph machines measure arousal, not lying per se. Try {}."
list = [
["polygraph test", ["lie detector test"]],
["polygraph machine", ["lie detector machine"]],
]
return preferred_forms_check(text, list, err, msg)
Check for p = 0.00
#149# -*- coding: utf-8 -*-
"""Psychological and psychiatric terms to avoid.
---
layout: post
source: Scott O. Lilienfeld, et al.
source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100
title: psychological and psychiatric terms to avoid
date: 2014-06-10 12:31:19
categories: writing
---
Psychological and psychiatric terms to avoid.
"""
from tools import preferred_forms_check, existence_check, memoize
@memoize
def check_lie_detector_test(text):
"""Suggest the preferred forms."""
err = "lilienfeld.terms_to_avoid.lie_detector"
msg = "Polygraph machines measure arousal, not lying per se. Try {}."
list = [
["polygraph test", ["lie detector test"]],
["polygraph machine", ["lie detector machine"]],
]
return preferred_forms_check(text, list, err, msg)
@memoize
def check_p_equals_zero(text):
"""Check for p = 0.000."""
err = "lilienfeld.terms_to_avoid.p_equals_zero"
msg = "Unless p really equals zero, you should use more decimal places."
list = [
"p = 0.00",
"p = 0.000",
"p = 0.0000",
]
return existence_check(text, list, err, msg, join=True)
| <commit_before># -*- coding: utf-8 -*-
"""Psychological and psychiatric terms to avoid.
---
layout: post
source: Scott O. Lilienfeld, et al.
source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100
title: psychological and psychiatric terms to avoid
date: 2014-06-10 12:31:19
categories: writing
---
Psychological and psychiatric terms to avoid.
"""
from tools import preferred_forms_check, memoize
@memoize
def check_lie_detector_test(text):
"""Suggest the preferred forms."""
err = "lilienfeld.terms_to_avoid.lie_detector"
msg = "Polygraph machines measure arousal, not lying per se. Try {}."
list = [
["polygraph test", ["lie detector test"]],
["polygraph machine", ["lie detector machine"]],
]
return preferred_forms_check(text, list, err, msg)
<commit_msg>Check for p = 0.00
#149<commit_after># -*- coding: utf-8 -*-
"""Psychological and psychiatric terms to avoid.
---
layout: post
source: Scott O. Lilienfeld, et al.
source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100
title: psychological and psychiatric terms to avoid
date: 2014-06-10 12:31:19
categories: writing
---
Psychological and psychiatric terms to avoid.
"""
from tools import preferred_forms_check, existence_check, memoize
@memoize
def check_lie_detector_test(text):
"""Suggest the preferred forms."""
err = "lilienfeld.terms_to_avoid.lie_detector"
msg = "Polygraph machines measure arousal, not lying per se. Try {}."
list = [
["polygraph test", ["lie detector test"]],
["polygraph machine", ["lie detector machine"]],
]
return preferred_forms_check(text, list, err, msg)
@memoize
def check_p_equals_zero(text):
"""Check for p = 0.000."""
err = "lilienfeld.terms_to_avoid.p_equals_zero"
msg = "Unless p really equals zero, you should use more decimal places."
list = [
"p = 0.00",
"p = 0.000",
"p = 0.0000",
]
return existence_check(text, list, err, msg, join=True)
|
2abf0e6b9009abd7c34b459ad9e3f2c6223bb043 | polyaxon/db/getters/experiment_groups.py | polyaxon/db/getters/experiment_groups.py | import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
| import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group or not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
| Add condition to check if experiment group exists before checking status | Add condition to check if experiment group exists before checking status
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
Add condition to check if experiment group exists before checking status | import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group or not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
| <commit_before>import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
<commit_msg>Add condition to check if experiment group exists before checking status<commit_after> | import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group or not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
| import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
Add condition to check if experiment group exists before checking statusimport logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group or not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
| <commit_before>import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
<commit_msg>Add condition to check if experiment group exists before checking status<commit_after>import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group or not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
|
fbf25d0e190e660c0be31b615c0753d62358ad46 | settings/settings.py | settings/settings.py | from django.utils import timezone
from settings.models import Setting
from utils.dates import string_to_datetime
class Settings:
def __init__(self, values=None):
if values is None:
return
settings = Setting.objects.filter(name__in=values)
self.__dict__['settings'] = dict((o.name, o.value) for o in settings)
def __getattr__(self, item):
return str(self.__dict__['settings'].get(item))
def __setattr__(self, key, value):
Setting.objects.update_or_create(name=key, defaults={'value': str(value)})
def is_sell_available():
try:
settings = Settings(['start_sell', 'end_sell'])
start_sell = string_to_datetime(settings.start_sell)
end_sell = string_to_datetime(settings.end_sell)
now = timezone.now()
if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
def is_purchase_available():
try:
settings = Settings(['start_purchase', 'end_purchase'])
start_purchase = string_to_datetime(settings.start_purchase)
end_purchase = string_to_datetime(settings.end_purchase)
now = timezone.now()
if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
| from django.utils import timezone
from settings.models import Setting
from utils.dates import string_to_datetime
class Settings:
def __init__(self, values=None):
if values is None:
return
settings = Setting.objects.filter(name__in=values)
self.__dict__['settings'] = dict((o.name, o.value) for o in settings)
def __getattr__(self, item):
return self.__dict__['settings'][item]
def __setattr__(self, key, value):
Setting.objects.update_or_create(name=key, defaults={'value': value})
def is_sell_available():
try:
settings = Settings(['start_sell', 'end_sell'])
start_sell = string_to_datetime(settings.start_sell)
end_sell = string_to_datetime(settings.end_sell)
now = timezone.now()
if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
def is_purchase_available():
try:
settings = Settings(['start_purchase', 'end_purchase'])
start_purchase = string_to_datetime(settings.start_purchase)
end_purchase = string_to_datetime(settings.end_purchase)
now = timezone.now()
if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
| Simplify Settings code a little bit | Simplify Settings code a little bit
- Fixes error 500 on homepage with clean database
| Python | agpl-3.0 | m4tx/egielda,m4tx/egielda,m4tx/egielda | from django.utils import timezone
from settings.models import Setting
from utils.dates import string_to_datetime
class Settings:
def __init__(self, values=None):
if values is None:
return
settings = Setting.objects.filter(name__in=values)
self.__dict__['settings'] = dict((o.name, o.value) for o in settings)
def __getattr__(self, item):
return str(self.__dict__['settings'].get(item))
def __setattr__(self, key, value):
Setting.objects.update_or_create(name=key, defaults={'value': str(value)})
def is_sell_available():
try:
settings = Settings(['start_sell', 'end_sell'])
start_sell = string_to_datetime(settings.start_sell)
end_sell = string_to_datetime(settings.end_sell)
now = timezone.now()
if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
def is_purchase_available():
try:
settings = Settings(['start_purchase', 'end_purchase'])
start_purchase = string_to_datetime(settings.start_purchase)
end_purchase = string_to_datetime(settings.end_purchase)
now = timezone.now()
if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
Simplify Settings code a little bit
- Fixes error 500 on homepage with clean database | from django.utils import timezone
from settings.models import Setting
from utils.dates import string_to_datetime
class Settings:
def __init__(self, values=None):
if values is None:
return
settings = Setting.objects.filter(name__in=values)
self.__dict__['settings'] = dict((o.name, o.value) for o in settings)
def __getattr__(self, item):
return self.__dict__['settings'][item]
def __setattr__(self, key, value):
Setting.objects.update_or_create(name=key, defaults={'value': value})
def is_sell_available():
try:
settings = Settings(['start_sell', 'end_sell'])
start_sell = string_to_datetime(settings.start_sell)
end_sell = string_to_datetime(settings.end_sell)
now = timezone.now()
if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
def is_purchase_available():
try:
settings = Settings(['start_purchase', 'end_purchase'])
start_purchase = string_to_datetime(settings.start_purchase)
end_purchase = string_to_datetime(settings.end_purchase)
now = timezone.now()
if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
| <commit_before>from django.utils import timezone
from settings.models import Setting
from utils.dates import string_to_datetime
class Settings:
def __init__(self, values=None):
if values is None:
return
settings = Setting.objects.filter(name__in=values)
self.__dict__['settings'] = dict((o.name, o.value) for o in settings)
def __getattr__(self, item):
return str(self.__dict__['settings'].get(item))
def __setattr__(self, key, value):
Setting.objects.update_or_create(name=key, defaults={'value': str(value)})
def is_sell_available():
try:
settings = Settings(['start_sell', 'end_sell'])
start_sell = string_to_datetime(settings.start_sell)
end_sell = string_to_datetime(settings.end_sell)
now = timezone.now()
if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
def is_purchase_available():
try:
settings = Settings(['start_purchase', 'end_purchase'])
start_purchase = string_to_datetime(settings.start_purchase)
end_purchase = string_to_datetime(settings.end_purchase)
now = timezone.now()
if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
<commit_msg>Simplify Settings code a little bit
- Fixes error 500 on homepage with clean database<commit_after> | from django.utils import timezone
from settings.models import Setting
from utils.dates import string_to_datetime
class Settings:
def __init__(self, values=None):
if values is None:
return
settings = Setting.objects.filter(name__in=values)
self.__dict__['settings'] = dict((o.name, o.value) for o in settings)
def __getattr__(self, item):
return self.__dict__['settings'][item]
def __setattr__(self, key, value):
Setting.objects.update_or_create(name=key, defaults={'value': value})
def is_sell_available():
try:
settings = Settings(['start_sell', 'end_sell'])
start_sell = string_to_datetime(settings.start_sell)
end_sell = string_to_datetime(settings.end_sell)
now = timezone.now()
if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
def is_purchase_available():
try:
settings = Settings(['start_purchase', 'end_purchase'])
start_purchase = string_to_datetime(settings.start_purchase)
end_purchase = string_to_datetime(settings.end_purchase)
now = timezone.now()
if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
| from django.utils import timezone
from settings.models import Setting
from utils.dates import string_to_datetime
class Settings:
def __init__(self, values=None):
if values is None:
return
settings = Setting.objects.filter(name__in=values)
self.__dict__['settings'] = dict((o.name, o.value) for o in settings)
def __getattr__(self, item):
return str(self.__dict__['settings'].get(item))
def __setattr__(self, key, value):
Setting.objects.update_or_create(name=key, defaults={'value': str(value)})
def is_sell_available():
try:
settings = Settings(['start_sell', 'end_sell'])
start_sell = string_to_datetime(settings.start_sell)
end_sell = string_to_datetime(settings.end_sell)
now = timezone.now()
if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
def is_purchase_available():
try:
settings = Settings(['start_purchase', 'end_purchase'])
start_purchase = string_to_datetime(settings.start_purchase)
end_purchase = string_to_datetime(settings.end_purchase)
now = timezone.now()
if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
Simplify Settings code a little bit
- Fixes error 500 on homepage with clean databasefrom django.utils import timezone
from settings.models import Setting
from utils.dates import string_to_datetime
class Settings:
def __init__(self, values=None):
if values is None:
return
settings = Setting.objects.filter(name__in=values)
self.__dict__['settings'] = dict((o.name, o.value) for o in settings)
def __getattr__(self, item):
return self.__dict__['settings'][item]
def __setattr__(self, key, value):
Setting.objects.update_or_create(name=key, defaults={'value': value})
def is_sell_available():
try:
settings = Settings(['start_sell', 'end_sell'])
start_sell = string_to_datetime(settings.start_sell)
end_sell = string_to_datetime(settings.end_sell)
now = timezone.now()
if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
def is_purchase_available():
try:
settings = Settings(['start_purchase', 'end_purchase'])
start_purchase = string_to_datetime(settings.start_purchase)
end_purchase = string_to_datetime(settings.end_purchase)
now = timezone.now()
if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
| <commit_before>from django.utils import timezone
from settings.models import Setting
from utils.dates import string_to_datetime
class Settings:
def __init__(self, values=None):
if values is None:
return
settings = Setting.objects.filter(name__in=values)
self.__dict__['settings'] = dict((o.name, o.value) for o in settings)
def __getattr__(self, item):
return str(self.__dict__['settings'].get(item))
def __setattr__(self, key, value):
Setting.objects.update_or_create(name=key, defaults={'value': str(value)})
def is_sell_available():
try:
settings = Settings(['start_sell', 'end_sell'])
start_sell = string_to_datetime(settings.start_sell)
end_sell = string_to_datetime(settings.end_sell)
now = timezone.now()
if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
def is_purchase_available():
try:
settings = Settings(['start_purchase', 'end_purchase'])
start_purchase = string_to_datetime(settings.start_purchase)
end_purchase = string_to_datetime(settings.end_purchase)
now = timezone.now()
if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
<commit_msg>Simplify Settings code a little bit
- Fixes error 500 on homepage with clean database<commit_after>from django.utils import timezone
from settings.models import Setting
from utils.dates import string_to_datetime
class Settings:
def __init__(self, values=None):
if values is None:
return
settings = Setting.objects.filter(name__in=values)
self.__dict__['settings'] = dict((o.name, o.value) for o in settings)
def __getattr__(self, item):
return self.__dict__['settings'][item]
def __setattr__(self, key, value):
Setting.objects.update_or_create(name=key, defaults={'value': value})
def is_sell_available():
try:
settings = Settings(['start_sell', 'end_sell'])
start_sell = string_to_datetime(settings.start_sell)
end_sell = string_to_datetime(settings.end_sell)
now = timezone.now()
if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
def is_purchase_available():
try:
settings = Settings(['start_purchase', 'end_purchase'])
start_purchase = string_to_datetime(settings.start_purchase)
end_purchase = string_to_datetime(settings.end_purchase)
now = timezone.now()
if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0:
return True
except KeyError:
return False
return False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.