input
stringlengths 0
2.17k
| instruction
stringlengths 18
2.94k
| output
stringlengths 47
3.36k
|
---|---|---|
from setuptools import setup, find_packages
setup(
name = "django-waitinglist",
version = "1.0b8",
author = "Brian Rosner",
author_email = "brosner@gmail.com",
description = "a Django waiting list app for running a private beta with cohorts support",
long_description = open("README.rst").read(),
license = "MIT",
url = "http://github.com/pinax/django-waitinglist",
packages = find_packages(),
install_requires = [
"django-appconf==0.5",
],
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Framework :: Django",
]
) | Fix packaging (again) - 1.0b9
| from setuptools import setup, find_packages
setup(
name = "django-waitinglist",
version = "1.0b9",
author = "Brian Rosner",
author_email = "brosner@gmail.com",
description = "a Django waiting list app for running a private beta with cohorts support",
long_description = open("README.rst").read(),
license = "MIT",
url = "http://github.com/pinax/django-waitinglist",
packages = find_packages(),
package_data = {"waitinglist": ["waitinglist/templates/*"]},
install_requires = [
"django-appconf==0.5",
],
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Framework :: Django",
]
) |
# -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
with open('README.rst', 'rb') as readme:
readme_text = readme.read().decode('utf-8')
setup(
name='django-bootstrap-pagination',
version='1.5.2',
keywords="django bootstrap pagination templatetag",
author=u'Jason McClellan',
author_email='jason@jasonmccllelan.net',
packages=find_packages(),
url='https://github.com/jmcclell/django-bootstrap-pagination',
license='MIT licence, see LICENCE',
description='Render Django Page objects as Bootstrap 3.x Pagination compatible HTML',
long_description=readme_text,
zip_safe=False,
include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
]
)
| Prepare for 1.6.0 on pypi
| # -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
with open('README.rst', 'rb') as readme:
readme_text = readme.read().decode('utf-8')
setup(
name='django-bootstrap-pagination',
version='1.6.0',
keywords="django bootstrap pagination templatetag",
author=u'Jason McClellan',
author_email='jason@jasonmccllelan.net',
packages=find_packages(),
url='https://github.com/jmcclell/django-bootstrap-pagination',
license='MIT licence, see LICENCE',
description='Render Django Page objects as Bootstrap 3.x Pagination compatible HTML',
long_description=readme_text,
zip_safe=False,
include_package_data=True,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Framework :: Django",
"Framework :: Django :: 1.4",
"Framework :: Django :: 1.5",
"Framework :: Django :: 1.6",
"Framework :: Django :: 1.7",
"Framework :: Django :: 1.8",
"Framework :: Django :: 1.9",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
]
)
|
import store_fixture
import groundstation.store
class TestGitStore(store_fixture.StoreTestCase):
storeClass = groundstation.store.git_store.GitStore
| Add testcase for database initialization
| import os
import store_fixture
import groundstation.store
class TestGitStore(store_fixture.StoreTestCase):
storeClass = groundstation.store.git_store.GitStore
def test_creates_required_dirs(self):
for d in groundstation.store.git_store.GitStore.required_dirs:
path = os.path.join(self.path, d)
self.assertTrue(os.path.exists(path))
self.assertTrue(os.path.isdir(path))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 Google LLC
#
# 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
#
# https://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 re
from setuptools import setup, find_packages
import sys
import warnings
dynamic_requires = []
version = 0.10
setup(
name='lakeside',
version="0.10",
author='Matthew Garrett',
author_email='mjg59@google.com',
url='http://github.com/google/python-lakeside',
packages=find_packages(),
scripts=[],
description='Python API for controlling Eufy LED bulbs',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=[
"protobuf",
"pycrypto",
"requests",
]
)
| Switch to pycryptodome rather than pycrypto
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 Google LLC
#
# 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
#
# https://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 re
from setuptools import setup, find_packages
import sys
import warnings
dynamic_requires = []
version = 0.10
setup(
name='lakeside',
version="0.10",
author='Matthew Garrett',
author_email='mjg59@google.com',
url='http://github.com/google/python-lakeside',
packages=find_packages(),
scripts=[],
description='Python API for controlling Eufy LED bulbs',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=[
"protobuf",
"pycryptodome",
"requests",
]
)
|
#!/usr/bin/env python
import sys, os
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
# Hack to prevent "TypeError: 'NoneType' object is not callable" error
# in multiprocessing/util.py _exit_function when setup.py exits
# (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
import multiprocessing
except ImportError:
pass
setup(
name='Willow',
version='1.1',
description='A Python image library that sits on top of Pillow, Wand and OpenCV',
author='Karl Hobley',
author_email='karl@kaed.uk',
url='',
packages=find_packages(exclude=['tests']),
include_package_data=True,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Topic :: Multimedia :: Graphics',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=[],
zip_safe=False,
)
| Change "Development Status" classifier to "5 - Production/Stable" | #!/usr/bin/env python
import sys, os
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
# Hack to prevent "TypeError: 'NoneType' object is not callable" error
# in multiprocessing/util.py _exit_function when setup.py exits
# (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
import multiprocessing
except ImportError:
pass
setup(
name='Willow',
version='1.1',
description='A Python image library that sits on top of Pillow, Wand and OpenCV',
author='Karl Hobley',
author_email='karl@kaed.uk',
url='',
packages=find_packages(exclude=['tests']),
include_package_data=True,
license='BSD',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Topic :: Multimedia :: Graphics',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=[],
zip_safe=False,
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'cityhall',
packages = ['cityhall'], # this must be the same as the name above
version = '0.0.10',
description = 'A library for accessing City Hall Setting Server',
license = 'AGPL',
author = 'Alex Popa',
author_email = 'alex.popa@digitalborderlands.com',
url = 'https://github.com/f00f-nyc/cityhall-python',
download_url = 'https://codeload.github.com/f00f-nyc/cityhall-python/legacy.tar.gz/v0.0.6',
install_requires=['requests==2.7.0','six==1.9.0'],
keywords = ['cityhall', 'enterprise settings', 'settings', 'settings server', 'cityhall', 'City Hall'],
test_suite='test',
tests_require=['requests==2.7.0','six==1.9.0','mock==1.0.1'],
classifiers = [],
) | Update package to have the tag/release match
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'cityhall',
packages = ['cityhall'], # this must be the same as the name above
version = '0.0.10',
description = 'A library for accessing City Hall Setting Server',
license = 'AGPL',
author = 'Alex Popa',
author_email = 'alex.popa@digitalborderlands.com',
url = 'https://github.com/f00f-nyc/cityhall-python',
download_url = 'https://codeload.github.com/f00f-nyc/cityhall-python/legacy.tar.gz/v0.0.10',
install_requires=['requests==2.7.0','six==1.9.0'],
keywords = ['cityhall', 'enterprise settings', 'settings', 'settings server', 'cityhall', 'City Hall'],
test_suite='test',
tests_require=['requests==2.7.0','six==1.9.0','mock==1.0.1'],
classifiers = [],
) |
from distutils.core import setup
setup(name='nikeplus',
version='0.1',
description='Export nikeplus data to CSV format',
author='Luke Lee',
author_email='durdenmisc@gmail.com',
url='http://www.lukelee.me',
packages=['nikeplus'],
entry_points={
"console_scripts": [
"nikeplus = nikeplus.export:main",
]
},
)
| Change package name for pypi, nikeplus was taken :(
| from distutils.core import setup
setup(name='nikeplusapi',
version='0.1',
description='Export nikeplus data to CSV format',
author='Luke Lee',
author_email='durdenmisc@gmail.com',
url='http://www.lukelee.me',
packages=['nikeplus'],
entry_points={
"console_scripts": [
"nikeplus = nikeplus.export:main",
]
},
)
|
from setuptools import setup
setup(
name='chainpoint', version='1.0',
description='Federated server for building blockchain notarized Merkle trees.',
author='Shawn Wilkinson', author_email='shawn+chainpoint@storj.io',
url='http://storj.io',
# Uncomment one or more lines below in the install_requires section
# for the specific client drivers/modules your application needs.
install_requires=['Flask == 0.10.1', 'Flask-SQLAlchemy == 2.0', 'btctxstore == 3.0.0'],
tests_require=['coverage', 'coveralls'],
test_suite="tests",
)
| Remove Storj and Trigger Travis | from setuptools import setup
setup(
name='chainpoint', version='1.0',
description='Federated server for building blockchain notarized Merkle trees.',
author='Shawn Wilkinson', author_email='shawn+chainpoint@storj.io',
# Uncomment one or more lines below in the install_requires section
# for the specific client drivers/modules your application needs.
install_requires=['Flask == 0.10.1', 'Flask-SQLAlchemy == 2.0', 'btctxstore == 3.0.0'],
tests_require=['coverage', 'coveralls'],
test_suite="tests",
)
|
from os import path
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(path.join(path.dirname(__file__), fname)).read()
setup(
name="pconf",
version="1.9.1",
author="Andras Maroy",
author_email="andras@maroy.hu",
description=("Hierarchical python configuration with files, environment variables, command-line arguments."),
license="MIT",
keywords="configuration hierarchical",
url="https://github.com/andrasmaroy/pconf",
packages=['pconf', 'pconf.store'],
long_description=read('README.rst'),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10'
],
install_requires=['pyyaml', 'deepmerge'],
extras_require={
'test': ['pytest', 'mock'],
},
)
| Add Python 3.11 support as of version 1.10.0
| from os import path
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(path.join(path.dirname(__file__), fname)).read()
setup(
name="pconf",
version="1.10.0",
author="Andras Maroy",
author_email="andras@maroy.hu",
description=("Hierarchical python configuration with files, environment variables, command-line arguments."),
license="MIT",
keywords="configuration hierarchical",
url="https://github.com/andrasmaroy/pconf",
packages=['pconf', 'pconf.store'],
long_description=read('README.rst'),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11'
],
install_requires=['pyyaml', 'deepmerge'],
extras_require={
'test': ['pytest', 'mock'],
},
)
|
#!/usr/bin/env python
from setuptools import setup,find_packages
METADATA = dict(
name='django-socialregistration',
version='0.4.3',
author='Alen Mujezinovic',
author_email='alen@caffeinehit.com',
description='Django application enabling registration through a variety of APIs',
long_description=open('README.rst').read(),
url='http://github.com/flashingpumpkin/django-socialregistration',
keywords='django facebook twitter oauth openid registration',
install_requires=['django', 'oauth2', 'python-openid'],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Environment :: Web Environment',
'Topic :: Internet',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
packages=find_packages(),
package_data={'socialregistration': ['templates/socialregistration/*.html'], }
)
if __name__ == '__main__':
setup(**METADATA)
| Remove django requirement to prevent version conflicts when using pip
| #!/usr/bin/env python
from setuptools import setup,find_packages
METADATA = dict(
name='django-socialregistration',
version='0.4.3',
author='Alen Mujezinovic',
author_email='alen@caffeinehit.com',
description='Django application enabling registration through a variety of APIs',
long_description=open('README.rst').read(),
url='http://github.com/flashingpumpkin/django-socialregistration',
keywords='django facebook twitter oauth openid registration',
install_requires=['oauth2', 'python-openid'],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Environment :: Web Environment',
'Topic :: Internet',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
packages=find_packages(),
package_data={'socialregistration': ['templates/socialregistration/*.html'], }
)
if __name__ == '__main__':
setup(**METADATA)
|
from setuptools import setup
setup(
name='tangled.website',
version='0.1.dev0',
description='tangledframework.org',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.website/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.website',
],
include_package_data=True,
install_requires=[
'tangled.auth>=0.1a3',
'tangled.session>=0.1a2',
'tangled.site>=0.1a2',
'SQLAlchemy>=1.1.6',
],
extras_require={
'dev': ['coverage'],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| Use the pg8000 pure-Python Postgres DBAPI module
| from setuptools import setup
setup(
name='tangled.website',
version='0.1.dev0',
description='tangledframework.org',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.website/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.website',
],
include_package_data=True,
install_requires=[
'pg8000>=1.10.6',
'tangled.auth>=0.1a3',
'tangled.session>=0.1a2',
'tangled.site>=0.1a2',
'SQLAlchemy>=1.1.6',
],
extras_require={
'dev': ['coverage'],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
from django.core.management import BaseCommand
from corehq.apps.domain.forms import DimagiOnlyEnterpriseForm
from corehq.apps.domain.models import Domain
from corehq.util.decorators import require_debug_true
class Command(BaseCommand):
help = ('Create a billing account and an enterprise level subscription '
'for the given domain')
args = ['domain']
@require_debug_true()
def handle(self, domain, **kwargs):
assert Domain.get_by_name(domain) is not None
DimagiOnlyEnterpriseForm(domain, 'management@command.com').process_subscription_management()
| Use parser to add command line arg
| from django.core.management import BaseCommand
from corehq.apps.domain.forms import DimagiOnlyEnterpriseForm
from corehq.apps.domain.models import Domain
from corehq.util.decorators import require_debug_true
class Command(BaseCommand):
help = ('Create a billing account and an enterprise level subscription '
'for the given domain')
def add_arguments(self, parser):
parser.add_argument('domain')
@require_debug_true()
def handle(self, domain, **kwargs):
assert Domain.get_by_name(domain) is not None
DimagiOnlyEnterpriseForm(domain, 'management@command.com').process_subscription_management()
|
import numpy as np
import rasterio
def test_reshape():
with rasterio.open('tests/data/RGB.byte.tif') as src:
im_data = rasterio.plot.reshape_as_image(src)
assert im_data.shape == (718, 791, 3)
def test_toundtrip_reshape():
with rasterio.open('tests/data/RGB.byte.tif') as src:
data = src.read()
im_data = rasterio.plot.reshape_as_image(data)
assert np.array_equal(data, rasterio.plot.reshape_as_raster(im_data))
| Update reshape_image test for new decoupled io function
| import numpy as np
import rasterio
def test_reshape():
with rasterio.open('tests/data/RGB.byte.tif') as src:
im_data = rasterio.plot.reshape_as_image(src.read())
assert im_data.shape == (718, 791, 3)
def test_toundtrip_reshape():
with rasterio.open('tests/data/RGB.byte.tif') as src:
data = src.read()
im_data = rasterio.plot.reshape_as_image(data)
assert np.array_equal(data, rasterio.plot.reshape_as_raster(im_data))
|
r'''
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import subprocess
import re
def get_interface_addresses():
"""Get all ip addresses assigned to interfaces.
Returns a tuple of (v4 addresses, v6 addresses)
"""
try:
output = subprocess.check_output("ifconfig")
except subprocess.CalledProcessError:
# Couldn't call ifconfig. Best guess it.
return (["127.0.0.1"], [])
# Parse out the results.
v4 = re.findall("inet addr:([^ ]*)", output)
v6 = re.findall("inet6 addr: ([^ ]*)", output)
return v4, v6
| Fix local interface addr parsing
On Fedora 21 the format of ifconfig is a little different.
Fixes #17
| r'''
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import subprocess
import re
def get_interface_addresses():
"""Get all ip addresses assigned to interfaces.
Returns a tuple of (v4 addresses, v6 addresses)
"""
try:
output = subprocess.check_output("ifconfig")
except subprocess.CalledProcessError:
# Couldn't call ifconfig. Best guess it.
return (["127.0.0.1"], [])
# Parse out the results.
v4 = re.findall("inet (addr:)?([^ ]*)", output)
v6 = re.findall("inet6 (addr: )?([^ ]*)", output)
v4 = [e[1] for e in v4]
v6 = [e[1] for e in v6]
return v4, v6
|
# Copyright 2015 Internap.
#
# 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 netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = members or []
| Support deprecated use of the interface property of Bond.
| # Copyright 2015 Internap.
#
# 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 warnings
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = members or []
@property
def interface(self):
warnings.warn('Deprecated: Use directly the members of Bond instead.',
category=DeprecationWarning)
return self
|
# Module: __init__
# Date: 3rd October 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Circuits Library - Web
circuits.web contains the circuits full stack web server that is HTTP
and WSGI compliant.
"""
from loggers import Logger
from core import Controller
from sessions import Sessions
from events import Request, Response
from servers import BaseServer, Server
from errors import HTTPError, Forbidden, NotFound, Redirect
from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC
try:
from dispatchers import JSONRPC
except ImportError:
pass
| circuits.web: Add url and expose to this namesapce
| # Module: __init__
# Date: 3rd October 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Circuits Library - Web
circuits.web contains the circuits full stack web server that is HTTP
and WSGI compliant.
"""
from utils import url
from loggers import Logger
from sessions import Sessions
from core import expose, Controller
from events import Request, Response
from servers import BaseServer, Server
from errors import HTTPError, Forbidden, NotFound, Redirect
from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC
try:
from dispatchers import JSONRPC
except ImportError:
pass
|
from test.test_support import vereq, TestFailed
import symtable
symbols = symtable.symtable("def f(x): return x", "?", "exec")
## XXX
## Test disabled because symtable module needs to be rewritten for new compiler
##vereq(symbols[0].name, "global")
##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1)
### Bug tickler: SyntaxError file name correct whether error raised
### while parsing or building symbol table.
##def checkfilename(brokencode):
## try:
## _symtable.symtable(brokencode, "spam", "exec")
## except SyntaxError, e:
## vereq(e.filename, "spam")
## else:
## raise TestFailed("no SyntaxError for %r" % (brokencode,))
##checkfilename("def f(x): foo)(") # parse-time
##checkfilename("def f(x): global x") # symtable-build-time
| Use unittest and make sure a few other cases don't crash
| from test import test_support
import symtable
import unittest
## XXX
## Test disabled because symtable module needs to be rewritten for new compiler
##vereq(symbols[0].name, "global")
##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1)
### Bug tickler: SyntaxError file name correct whether error raised
### while parsing or building symbol table.
##def checkfilename(brokencode):
## try:
## _symtable.symtable(brokencode, "spam", "exec")
## except SyntaxError, e:
## vereq(e.filename, "spam")
## else:
## raise TestFailed("no SyntaxError for %r" % (brokencode,))
##checkfilename("def f(x): foo)(") # parse-time
##checkfilename("def f(x): global x") # symtable-build-time
class SymtableTest(unittest.TestCase):
def test_invalid_args(self):
self.assertRaises(TypeError, symtable.symtable, "42")
self.assertRaises(ValueError, symtable.symtable, "42", "?", "")
def test_eval(self):
symbols = symtable.symtable("42", "?", "eval")
def test_single(self):
symbols = symtable.symtable("42", "?", "single")
def test_exec(self):
symbols = symtable.symtable("def f(x): return x", "?", "exec")
def test_main():
test_support.run_unittest(SymtableTest)
if __name__ == '__main__':
test_main()
|
from os import getenv
class Config(object):
DEBUG = False
TESTING = False
SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL')
STRIP_WWW_PREFIX = True
API_KEY = getenv('API_KEY')
class ProductionConfig(Config):
DEBUG = False
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db'
class TestingConfig(Config):
TESTING = True
| Allow overriding the DATABASE_URL with an environment varible if in development mode
| from os import getenv
class Config(object):
DEBUG = False
TESTING = False
SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL', 'sqlite:///app.db')
STRIP_WWW_PREFIX = True
API_KEY = getenv('API_KEY')
class ProductionConfig(Config):
DEBUG = False
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division configuration file
create_divisions(simulation=True)
| Include player data migration in setup
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
from setup.create_players import migrate_players
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division configuration file
create_divisions(simulation=True)
# migrating players from json file to database
migrate_players(simulation=True)
|
from .nn_solver import NNSolver
from .lstm_solver import LSTMSolver
from .tree_lstm_solver import TreeLSTMSolver
from .memory_network import MemoryNetworkSolver
from .differentiable_search import DifferentiableSearchSolver
concrete_solvers = { # pylint: disable=invalid-name
'LSTMSolver': LSTMSolver,
'TreeLSTMSolver': TreeLSTMSolver,
'MemoryNetworkSolver': MemoryNetworkSolver,
'DifferentiableSearchSolver': DifferentiableSearchSolver,
}
| Add MCMemoryNetwork as a usable solver
| from .nn_solver import NNSolver
from .lstm_solver import LSTMSolver
from .tree_lstm_solver import TreeLSTMSolver
from .memory_network import MemoryNetworkSolver
from .differentiable_search import DifferentiableSearchSolver
from .multiple_choice_memory_network import MultipleChoiceMemoryNetworkSolver
concrete_solvers = { # pylint: disable=invalid-name
'LSTMSolver': LSTMSolver,
'TreeLSTMSolver': TreeLSTMSolver,
'MemoryNetworkSolver': MemoryNetworkSolver,
'DifferentiableSearchSolver': DifferentiableSearchSolver,
'MultipleChoiceMemoryNetworkSolver': MultipleChoiceMemoryNetworkSolver,
}
|
# Copyright 2018 The TensorFlow Authors. 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.
# ==============================================================================
"""Ragged Tensors.
This package defines ops for manipulating ragged tensors (`tf.RaggedTensor`),
which are tensors with non-uniform shapes. In particular, each `RaggedTensor`
has one or more *ragged dimensions*, which are dimensions whose slices may have
different lengths. For example, the inner (column) dimension of
`rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` is ragged, since the column slices
(`rt[0, :]`, ..., `rt[4, :]`) have different lengths. For a more detailed
description of ragged tensors, see the `tf.RaggedTensor` class documentation
and the [Ragged Tensor Guide](/guide/ragged_tensors).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| Fix broken link to ragged tensor guide
PiperOrigin-RevId: 368443422
Change-Id: I69818413b7ed8cf2f372580878860a469b9735a8
| # Copyright 2018 The TensorFlow Authors. 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.
# ==============================================================================
"""Ragged Tensors.
This package defines ops for manipulating ragged tensors (`tf.RaggedTensor`),
which are tensors with non-uniform shapes. In particular, each `RaggedTensor`
has one or more *ragged dimensions*, which are dimensions whose slices may have
different lengths. For example, the inner (column) dimension of
`rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` is ragged, since the column slices
(`rt[0, :]`, ..., `rt[4, :]`) have different lengths. For a more detailed
description of ragged tensors, see the `tf.RaggedTensor` class documentation
and the [Ragged Tensor Guide](/guide/ragged_tensor).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
|
from django import forms
from .models import Tutorial
class TutorialForm(forms.ModelForm):
# ToDO: Set required fields??
class Meta:
model = Tutorial
fields = ('title', 'html', 'markdown') | Add new model fields to form
| from django import forms
from .models import Tutorial
class TutorialForm(forms.ModelForm):
# ToDO: Set required fields??
class Meta:
model = Tutorial
fields = ('category', 'title', 'markdown', 'level')
|
# -*- coding: utf-8 -*-
from flask import current_app, g
from flask.ext.script import Manager, Server, prompt_bool
from massa import create_app
manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config', required=False)
manager.add_command('runserver', Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0',
port = 8080,
))
@manager.command
def db_create_tables():
"""Create all the db tables."""
current_app.preprocess_request()
db = g.sl('db')
db.create_tables()
@manager.command
def db_drop_tables():
"""Drop all the db tables."""
if prompt_bool('Are you sure you want to drop all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
if __name__ == '__main__':
manager.run()
| Add a reset task to drop and recreate the db tables with one command. | # -*- coding: utf-8 -*-
from flask import current_app, g
from flask.ext.script import Manager, Server, prompt_bool
from massa import create_app
manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config', required=False)
manager.add_command('runserver', Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0',
port = 8080,
))
@manager.command
def db_create_tables():
"""Create all the db tables."""
current_app.preprocess_request()
db = g.sl('db')
db.create_tables()
@manager.command
def db_drop_tables():
"""Drop all the db tables."""
if prompt_bool('Are you sure you want to drop all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
@manager.command
def db_reset_tables():
"""Drop and (re)create all the db tables."""
if prompt_bool('Are you sure you want to reset all the db tables?'):
current_app.preprocess_request()
db = g.sl('db')
db.drop_tables()
db.create_tables()
if __name__ == '__main__':
manager.run()
|
from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
fields = ('name',)
extra = 0
class BackdropUserAdmin(reversion.VersionAdmin):
search_fields = ['email']
list_display = ('email', 'numer_of_datasets_user_has_access_to',)
list_per_page = 30
filter_horizontal = ('data_sets',)
def queryset(self, request):
return BackdropUser.objects.annotate(
dataset_count=models.Count('data_sets')
)
def numer_of_datasets_user_has_access_to(self, obj):
return obj.dataset_count
numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count'
admin.site.register(BackdropUser, BackdropUserAdmin)
| Fix typo in BackdropUser admin model
| from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
fields = ('name',)
extra = 0
class BackdropUserAdmin(reversion.VersionAdmin):
search_fields = ['email']
list_display = ('email', 'number_of_datasets_user_has_access_to',)
list_per_page = 30
filter_horizontal = ('data_sets',)
def queryset(self, request):
return BackdropUser.objects.annotate(
dataset_count=models.Count('data_sets')
)
def number_of_datasets_user_has_access_to(self, obj):
return obj.dataset_count
number_of_datasets_user_has_access_to.admin_order_field = 'dataset_count'
admin.site.register(BackdropUser, BackdropUserAdmin)
|
from django.test import TestCase
from django.urls import reverse
from wagtail.tests.utils import WagtailTestUtils
class TestContentTypeUse(TestCase, WagtailTestUtils):
fixtures = ['test.json']
def setUp(self):
self.user = self.login()
def test_content_type_use(self):
# Get use of event page
response = self.client.get(reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage')))
# Check response
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html')
self.assertContains(response, "Christmas")
| Add test for button URLs including a 'next' parameter
| from django.test import TestCase
from django.urls import reverse
from django.utils.http import urlencode
from wagtail.tests.testapp.models import EventPage
from wagtail.tests.utils import WagtailTestUtils
class TestContentTypeUse(TestCase, WagtailTestUtils):
fixtures = ['test.json']
def setUp(self):
self.user = self.login()
self.christmas_page = EventPage.objects.get(title="Christmas")
def test_content_type_use(self):
# Get use of event page
request_url = reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage'))
response = self.client.get(request_url)
# Check response
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html')
self.assertContains(response, "Christmas")
# Links to 'delete' etc should include a 'next' URL parameter pointing back here
delete_url = (
reverse('wagtailadmin_pages:delete', args=(self.christmas_page.id,))
+ '?' + urlencode({'next': request_url})
)
self.assertContains(response, delete_url)
|
"""
byceps.util.irc
~~~~~~~~~~~~~~~
Send IRC messages to a bot via HTTP.
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from time import sleep
from typing import List
from flask import current_app
import requests
DEFAULT_BOT_URL = 'http://127.0.0.1:12345/'
DEFAULT_ENABLED = False
DELAY_IN_SECONDS = 2
DEFAULT_TEXT_PREFIX = '[BYCEPS] '
def send_message(channels: List[str], text: str) -> None:
"""Write the text to the channels by sending it to the bot via HTTP."""
enabled = current_app.config.get('ANNOUNCE_IRC_ENABLED', DEFAULT_ENABLED)
if not enabled:
current_app.logger.warning('Announcements on IRC are disabled.')
return
text_prefix = current_app.config.get(
'ANNOUNCE_IRC_TEXT_PREFIX', DEFAULT_TEXT_PREFIX
)
text = text_prefix + text
url = current_app.config.get('IRC_BOT_URL', DEFAULT_BOT_URL)
data = {'channels': channels, 'text': text}
# Delay a bit as an attempt to avoid getting kicked from server
# because of flooding.
sleep(DELAY_IN_SECONDS)
requests.post(url, json=data) # Ignore response code for now.
| Make IRC message delay configurable
| """
byceps.util.irc
~~~~~~~~~~~~~~~
Send IRC messages to a bot via HTTP.
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from time import sleep
from typing import List
from flask import current_app
import requests
DEFAULT_BOT_URL = 'http://127.0.0.1:12345/'
DEFAULT_ENABLED = False
DEFAULT_DELAY_IN_SECONDS = 2
DEFAULT_TEXT_PREFIX = '[BYCEPS] '
def send_message(channels: List[str], text: str) -> None:
"""Write the text to the channels by sending it to the bot via HTTP."""
enabled = current_app.config.get('ANNOUNCE_IRC_ENABLED', DEFAULT_ENABLED)
if not enabled:
current_app.logger.warning('Announcements on IRC are disabled.')
return
text_prefix = current_app.config.get(
'ANNOUNCE_IRC_TEXT_PREFIX', DEFAULT_TEXT_PREFIX
)
text = text_prefix + text
url = current_app.config.get('IRC_BOT_URL', DEFAULT_BOT_URL)
data = {'channels': channels, 'text': text}
# Delay a bit as an attempt to avoid getting kicked from server
# because of flooding.
delay = int(
current_app.config.get('ANNOUNCE_IRC_DELAY', DEFAULT_DELAY_IN_SECONDS)
)
sleep(delay)
requests.post(url, json=data) # Ignore response code for now.
|
#!/usr/bin/env python
"""
Autocompletion example.
Press [Tab] to complete the current word.
- The first Tab press fills in the common part of all completions
and shows all the completions. (In the menu)
- Any following tab press cycles through all the possible completions.
"""
from __future__ import unicode_literals
from prompt_toolkit.contrib.completers import WordCompleter
from prompt_toolkit import prompt
animal_completer = WordCompleter([
'alligator',
'ant',
'ape',
'bat',
'bear',
'beaver',
'bee',
'bison',
'butterfly',
'cat',
'chicken',
'crocodile',
'dinosaur',
'dog',
'dolphine',
'dove',
'duck',
'eagle',
'elephant',
'fish',
'goat',
'gorilla',
'kangaroo',
'leopard',
'lion',
'mouse',
'rabbit',
'rat',
'snake',
'spider',
'turkey',
'turtle',
], ignore_case=True)
def main():
text = prompt('Give some animals: ', completer=animal_completer,
complete_while_typing=False)
print('You said: %s' % text)
if __name__ == '__main__':
main()
| Fix typo: `dolphine` -> `dolphin`
| #!/usr/bin/env python
"""
Autocompletion example.
Press [Tab] to complete the current word.
- The first Tab press fills in the common part of all completions
and shows all the completions. (In the menu)
- Any following tab press cycles through all the possible completions.
"""
from __future__ import unicode_literals
from prompt_toolkit.contrib.completers import WordCompleter
from prompt_toolkit import prompt
animal_completer = WordCompleter([
'alligator',
'ant',
'ape',
'bat',
'bear',
'beaver',
'bee',
'bison',
'butterfly',
'cat',
'chicken',
'crocodile',
'dinosaur',
'dog',
'dolphin',
'dove',
'duck',
'eagle',
'elephant',
'fish',
'goat',
'gorilla',
'kangaroo',
'leopard',
'lion',
'mouse',
'rabbit',
'rat',
'snake',
'spider',
'turkey',
'turtle',
], ignore_case=True)
def main():
text = prompt('Give some animals: ', completer=animal_completer,
complete_while_typing=False)
print('You said: %s' % text)
if __name__ == '__main__':
main()
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 abc
import six
from st2common.runners.utils import get_logger_for_python_runner_action
@six.add_metaclass(abc.ABCMeta)
class Action(object):
"""
Base action class other Python actions should inherit from.
"""
description = None
def __init__(self, config=None, action_service=None):
"""
:param config: Action config.
:type config: ``dict``
:param action_service: ActionService object.
:type action_service: :class:`ActionService~
"""
self.config = config or {}
self.action_service = action_service
self.logger = get_logger_for_python_runner_action(action_name=self.__class__.__name__)
@abc.abstractmethod
def run(self, **kwargs):
pass
| Add _all__ to the module.
| # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 abc
import six
from st2common.runners.utils import get_logger_for_python_runner_action
__all__ = [
'Action'
]
@six.add_metaclass(abc.ABCMeta)
class Action(object):
"""
Base action class other Python actions should inherit from.
"""
description = None
def __init__(self, config=None, action_service=None):
"""
:param config: Action config.
:type config: ``dict``
:param action_service: ActionService object.
:type action_service: :class:`ActionService~
"""
self.config = config or {}
self.action_service = action_service
self.logger = get_logger_for_python_runner_action(action_name=self.__class__.__name__)
@abc.abstractmethod
def run(self, **kwargs):
pass
|
import json
import os
import sys
import dateparser
__DATA_DIR = '../data/'
def harmonize_data( data ):
## make dates as date objects
data2 = []
for d in data:
if 'created_time' in d:
d['date'] = dateparser.parse( d['created_time'] ) ## should take care of the various formats
d['creator'] = d['from']['name']
data2.append( d )
return data2
def load_facebook( terms = ['data_'] ): ## todo: better filtering
data = []
for f in os.listdir( __DATA_DIR ):
if any( term in f for term in terms ):
print json.load( open( __DATA_DIR + f ) ).keys()
data += json.load( open( __DATA_DIR + f ) )['feed']
return harmonize_data( data )
| Change dateparser to datetime to use with Jupyter
| import json
import os
import sys
#import dateparser
from datetime import datetime
__DATA_DIR = '../data/'
def harmonize_data( data ):
## make dates as date objects
data2 = []
for d in data:
if 'created_time' in d:
#d['date'] = dateparser.parse( d['created_time'] ) ## should take care of the various formats
d['date'] = datetime.strptime( d['created_time'].replace( 'T', ' ' ).replace( '+0000', '' ), '%Y-%m-%d %H:%M:%S' )
d['creator'] = d['from']['name']
data2.append( d )
return data2
def load_facebook( terms = ['data_'] ): ## todo: better filtering
data = []
for f in os.listdir( __DATA_DIR ):
if any( term in f for term in terms ):
print json.load( open( __DATA_DIR + f ) ).keys()
data += json.load( open( __DATA_DIR + f ) )['feed']
return harmonize_data( data )
|
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Post
class PostListView(ListView):
model = Post
context_object_name = 'posts'
class PostDetailView(DetailView):
model = Post
context_object_name = 'post'
| posts: Order posts from newest to oldest
| from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Post
class PostListView(ListView):
model = Post
context_object_name = 'posts'
def get_queryset(self):
"""
Order posts by the day they were added, from newest, to oldest.
"""
queryset = super(PostListView, self).get_queryset()
return queryset.order_by('-added_at')
class PostDetailView(DetailView):
model = Post
context_object_name = 'post'
|
"""
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Avoid connection errors after database becomes temporarily
# unreachable, then becomes reachable again.
SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True}
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_DASHBOARD_POLL_INTERVAL = 2500
RQ_DASHBOARD_WEB_BACKGROUND = 'white'
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
TIMEZONE = 'Europe/Berlin'
# static content files path
PATH_DATA = Path('./data')
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# shop
SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
| Remove superseded config default for `ROOT_REDIRECT_STATUS_CODE`
| """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Avoid connection errors after database becomes temporarily
# unreachable, then becomes reachable again.
SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True}
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_DASHBOARD_POLL_INTERVAL = 2500
RQ_DASHBOARD_WEB_BACKGROUND = 'white'
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
TIMEZONE = 'Europe/Berlin'
# static content files path
PATH_DATA = Path('./data')
# home page
ROOT_REDIRECT_TARGET = None
# shop
SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
|
import logging
from Acquisition import aq_base
from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def addBatches(tool):
"""
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
setup = portal.portal_setup
# reimport Types Tool to add BatchFolder and Batch
setup.runImportStepFromProfile('profile-bika.lims:default', 'typeinfo')
# reimport Workflows to add bika_batch_workflow
setup.runImportStepFromProfile('profile-bika.lims:default', 'workflow')
typestool = getToolByName(portal, 'portal_types')
workflowtool = getToolByName(portal, 'portal_workflow')
# Add the BatchFolder at /batches
typestool.constructContent(type_name="BatchFolder",
container=portal,
id='batches',
title='Batches')
obj = portal['batches']
obj.unmarkCreationFlag()
obj.reindexObject()
# and place it after ClientFolder
portal.moveObjectToPosition('batches', portal.objectIds().index('clients'))
# add BatchID to all AnalysisRequest objects.
# When the objects are reindexed, BatchUID will also be populated
proxies = portal_catalog(portal_type="AnalysiRequest")
ars = (proxy.getObject() for proxy in proxies)
for ar in ars:
ar.setBatchID(None)
return True
| Fix 1010 upgrade step (setBatchID -> setBatch)
| import logging
from Acquisition import aq_base
from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
def addBatches(tool):
"""
"""
portal = aq_parent(aq_inner(tool))
portal_catalog = getToolByName(portal, 'portal_catalog')
setup = portal.portal_setup
# reimport Types Tool to add BatchFolder and Batch
setup.runImportStepFromProfile('profile-bika.lims:default', 'typeinfo')
# reimport Workflows to add bika_batch_workflow
setup.runImportStepFromProfile('profile-bika.lims:default', 'workflow')
typestool = getToolByName(portal, 'portal_types')
workflowtool = getToolByName(portal, 'portal_workflow')
# Add the BatchFolder at /batches
typestool.constructContent(type_name="BatchFolder",
container=portal,
id='batches',
title='Batches')
obj = portal['batches']
obj.unmarkCreationFlag()
obj.reindexObject()
# and place it after ClientFolder
portal.moveObjectToPosition('batches', portal.objectIds().index('clients'))
# add Batch to all AnalysisRequest objects.
# When the objects are reindexed, BatchUID will also be populated
proxies = portal_catalog(portal_type="AnalysiRequest")
ars = (proxy.getObject() for proxy in proxies)
for ar in ars:
ar.setBatch(None)
return True
|
from fabric.api import cd, run, task
try:
import fabfile_local
_pyflakes = fabfile_local
except ImportError:
pass
@task
def update():
with cd("~/vagrant-installers"):
run("git pull")
| Allow the targetting of specific roles with fabric
| from fabric.api import cd, env, run, task
try:
import fabfile_local
_pyflakes = fabfile_local
except ImportError:
pass
@task
def update():
with cd("~/vagrant-installers"):
run("git pull")
@task
def all():
"Run the task against all hosts."
for _, value in env.roledefs.iteritems():
env.hosts.extend(value)
@task
def role(name):
"Set the hosts to a specific role."
env.hosts = env.roledefs[name]
|
import os
import logging
from optparse import OptionParser
from pegasus.service import app, em
from pegasus.service.command import Command
class ServerCommand(Command):
usage = "%prog [options]"
description = "Start Pegasus Service"
def __init__(self):
Command.__init__(self)
self.parser.add_option("-d", "--debug", action="store_true", dest="debug",
default=None, help="Enable debugging")
def run(self):
if self.options.debug:
app.config.update(DEBUG=True)
logging.basicConfig(level=logging.INFO)
# Make sure the environment is OK for the ensemble manager
em.check_environment()
# We only start the ensemble manager if we are not debugging
# or if we are debugging and Werkzeug is restarting. This
# prevents us from having two ensemble managers running in
# the debug case.
WERKZEUG_RUN_MAIN = os.environ.get('WERKZEUG_RUN_MAIN') == 'true'
DEBUG = app.config.get("DEBUG", False)
if (not DEBUG) or WERKZEUG_RUN_MAIN:
mgr = em.EnsembleManager()
mgr.start()
app.run(port=app.config["SERVER_PORT"], host=app.config["SERVER_HOST"])
def main():
ServerCommand().main()
| Allow service to start without EM if Condor and Pegasus are missing
| import os
import logging
from optparse import OptionParser
from pegasus.service import app, em
from pegasus.service.command import Command
log = logging.getLogger("server")
class ServerCommand(Command):
usage = "%prog [options]"
description = "Start Pegasus Service"
def __init__(self):
Command.__init__(self)
self.parser.add_option("-d", "--debug", action="store_true", dest="debug",
default=None, help="Enable debugging")
def run(self):
if self.options.debug:
app.config.update(DEBUG=True)
logging.basicConfig(level=logging.INFO)
# We only start the ensemble manager if we are not debugging
# or if we are debugging and Werkzeug is restarting. This
# prevents us from having two ensemble managers running in
# the debug case.
WERKZEUG_RUN_MAIN = os.environ.get('WERKZEUG_RUN_MAIN') == 'true'
DEBUG = app.config.get("DEBUG", False)
if (not DEBUG) or WERKZEUG_RUN_MAIN:
# Make sure the environment is OK for the ensemble manager
try:
em.check_environment()
except em.EMException, e:
log.warning("%s: Ensemble manager disabled" % e.message)
else:
mgr = em.EnsembleManager()
mgr.start()
app.run(port=app.config["SERVER_PORT"], host=app.config["SERVER_HOST"])
def main():
ServerCommand().main()
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "/Cell:" + AdminControl.getCell() + "/"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
dbs = dbs.split('(')
print dbs
for db in dbs.splitlines():
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ) | : Create documentation of DataSource Settings
Task-Url: | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check
for db in dbs.splitlines():
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ) |
# Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import json
from odoo.http import request, route
from odoo.addons.web.controllers import main as report
class ReportController(report.ReportController):
@route()
def report_routes(self, reportname, docids=None, converter=None, **data):
report = request.env["ir.actions.report"]._get_report_from_name(reportname)
original_context = json.loads(data.get("context", "{}"))
data["context"] = json.dumps(
report.with_context(original_context)._get_context()
)
return super().report_routes(
reportname, docids=docids, converter=converter, **data
)
| Fix json.loads when context is None
Co-authored-by: Pierre Verkest <94ea506e1738fc492d3f7a19e812079abcde2af1@gmail.com> | # Copyright 2019 Creu Blanca
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import json
from odoo.http import request, route
from odoo.addons.web.controllers import main as report
class ReportController(report.ReportController):
@route()
def report_routes(self, reportname, docids=None, converter=None, **data):
report = request.env["ir.actions.report"]._get_report_from_name(reportname)
original_context = json.loads(data.get("context", "{}") or "{}")
data["context"] = json.dumps(
report.with_context(original_context)._get_context()
)
return super().report_routes(
reportname, docids=docids, converter=converter, **data
)
|
import datetime
import mongoengine
from mongoengine.django import auth
from piplmesh.account import fields
class User(auth.User):
birthdate = fields.LimitedDateTimeField(upper_limit=datetime.datetime.today(), lower_limit=datetime.datetime.today() - datetime.timedelta(366 * 120))
gender = fields.GenderField()
language = fields.LanguageField()
facebook_id = mongoengine.IntField()
facebook_token = mongoengine.StringField(max_length=150)
| Change date's limits format to datetime.date.
| import datetime
import mongoengine
from mongoengine.django import auth
from piplmesh.account import fields
class User(auth.User):
birthdate = fields.LimitedDateTimeField(upper_limit=datetime.date.today(), lower_limit=datetime.date.today() - datetime.timedelta(366 * 120))
gender = fields.GenderField()
language = fields.LanguageField()
facebook_id = mongoengine.IntField()
facebook_token = mongoengine.StringField(max_length=150)
|
from paver.easy import task, needs, path, sh, cmdopts
from paver.setuputils import setup, install_distutils_tasks, find_package_data
from distutils.extension import Extension
from optparse import make_option
from Cython.Build import cythonize
import version
pyx_files = ['si_prefix/si_prefix.pyx']
ext_modules = [Extension(f[:-4].replace('/', '.'), [f],
extra_compile_args=['-O3'],
include_dirs=['cythrust'])
for f in pyx_files]
ext_modules = cythonize(ext_modules)
setup(name='si_prefix',
version=version.getVersion(),
description='Functions for formatting numbers according to SI standards.',
keywords='si prefix format number precision',
author='Christian Fobel',
url='https://github.com/cfobel/si_prefix',
license='GPL',
packages=['si_prefix'],
package_data=find_package_data('si_prefix', package='si_prefix',
only_in_packages=False),
ext_modules=ext_modules)
@task
@needs('build_ext', 'generate_setup', 'minilib', 'setuptools.command.sdist')
def sdist():
"""Overrides sdist to make sure that our setup.py is generated."""
pass
| Rename package "si_prefix" to "si-prefix"
| from paver.easy import task, needs, path, sh, cmdopts
from paver.setuputils import setup, install_distutils_tasks, find_package_data
from distutils.extension import Extension
from optparse import make_option
from Cython.Build import cythonize
import version
pyx_files = ['si_prefix/si_prefix.pyx']
ext_modules = [Extension(f[:-4].replace('/', '.'), [f],
extra_compile_args=['-O3'],
include_dirs=['cythrust'])
for f in pyx_files]
ext_modules = cythonize(ext_modules)
setup(name='si-prefix',
version=version.getVersion(),
description='Functions for formatting numbers according to SI standards.',
keywords='si prefix format number precision',
author='Christian Fobel',
url='https://github.com/cfobel/si_prefix',
license='GPL',
packages=['si_prefix'],
package_data=find_package_data('si_prefix', package='si_prefix',
only_in_packages=False),
ext_modules=ext_modules)
@task
@needs('build_ext', 'generate_setup', 'minilib', 'setuptools.command.sdist')
def sdist():
"""Overrides sdist to make sure that our setup.py is generated."""
pass
|
#!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import subprocess
class PasswdChange_Test(TestCase):
def setUp(self):
"""
Preconditions
"""
subprocess.call(['mkdir', 'test'])
subprocess.call(['touch', 'test/rvv', 'test/max',
'test/bdv', 'test/mail'])
#TODO create passwd test file
#TODO create shadow test file
#TODO create keys.txt file
def test_passwd_change(self):
shadow_change(*passwd_change())
mails_delete(maildir_path='test')
def test_passwd_change_2(self):
shadow_change(*passwd_change())
mails_delete(maildir_path='test/')
suite = TestLoader().loadTestsFromTestCase(PasswdChange_Test)
TextTestRunner(verbosity=2).run(suite)
| Add tearDown() - remove test dir, test files existing and not existing.
| #!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import os
import subprocess
class PasswdChange_Test(TestCase):
def setUp(self):
"""
Preconditions
"""
subprocess.call(['mkdir', 'test'])
subprocess.call(['touch', 'test/rvv', 'test/max',
'test/bdv', 'test/mail'])
#TODO create passwd test file
#TODO create shadow test file
#TODO create keys.txt file
def tearDown(self):
if os.path.exists('test/rvv'):
raise Exception('test/rvv must not exist')
if not (os.path.exists('test/max') and
os.path.exists('test/bdv') and
os.path.exists('test/mail')):
raise Exception('File max, bdv or mail must exist!')
subprocess.call(['rm', '-r', 'test/'])
def test_passwd_change(self):
shadow_change(*passwd_change())
mails_delete(maildir_path='test')
if os.path.exists('test/rvv'):
raise Exception('test/rvv must not exist')
if not (os.path.exists('test/max') and
os.path.exists('test/bdv') and
os.path.exists('test/mail')):
raise Exception('File max, bdv or mail must exist!')
def test_passwd_change_2(self):
shadow_change(*passwd_change())
mails_delete(maildir_path='test/')
suite = TestLoader().loadTestsFromTestCase(PasswdChange_Test)
TextTestRunner(verbosity=2).run(suite)
|
from django import template
from django.conf import settings
from socialregistration.utils import _https
register = template.Library()
@register.inclusion_tag('socialregistration/facebook_js.html')
def facebook_js():
return {'facebook_api_key' : settings.FACEBOOK_API_KEY, 'is_https' : bool(_https())}
@register.inclusion_tag('socialregistration/facebook_button.html', takes_context=True)
def facebook_button(context):
if not 'request' in context:
raise AttributeError, 'Please add the ``django.core.context_processors.request`` context processors to your settings.TEMPLATE_CONTEXT_PROCESSORS set'
logged_in = context['request'].user.is_authenticated()
next = context['next'] if 'next' in context else None
return dict(next=next, logged_in=logged_in) | Use syntax compatible with Python 2.4
| from django import template
from django.conf import settings
from socialregistration.utils import _https
register = template.Library()
@register.inclusion_tag('socialregistration/facebook_js.html')
def facebook_js():
return {'facebook_api_key' : settings.FACEBOOK_API_KEY, 'is_https' : bool(_https())}
@register.inclusion_tag('socialregistration/facebook_button.html', takes_context=True)
def facebook_button(context):
if not 'request' in context:
raise AttributeError, 'Please add the ``django.core.context_processors.request`` context processors to your settings.TEMPLATE_CONTEXT_PROCESSORS set'
logged_in = context['request'].user.is_authenticated()
if 'next' in context:
next = context['next']
else:
next = None
return dict(next=next, logged_in=logged_in) |
# coding: utf-8
from pathlib import Path
from typing import Callable, Optional, List, Union
from il2fb.parsers.events.events import Event
EventOrNone = Optional[Event]
EventHandler = Callable[[Event], None]
IntOrNone = Optional[int]
StringProducer = Callable[[], str]
StringHandler = Callable[[str], None]
StringOrNone = Optional[str]
StringOrNoneProducer = Callable[[], StringOrNone]
StringOrPath = Union[str, Path]
StringList = List[str]
| Update import of Event class
| # coding: utf-8
from pathlib import Path
from typing import Callable, Optional, List, Union
from il2fb.commons.events import Event
EventOrNone = Optional[Event]
EventHandler = Callable[[Event], None]
IntOrNone = Optional[int]
StringProducer = Callable[[], str]
StringHandler = Callable[[str], None]
StringOrNone = Optional[str]
StringOrNoneProducer = Callable[[], StringOrNone]
StringOrPath = Union[str, Path]
StringList = List[str]
|
"""Aligner for texts and their segmentations.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
__all__ = ['AlignmentFailed', 'Aligner']
class AlignmentFailed(Exception): pass
class Aligner(object):
"""Align a text with its tokenization.
"""
def align(self, text, tokens):
"""Align text with its tokeniation.
Parameters
----------
text : str
Text.
tokens : list of str
Tokenization of ``text``.
Returns
-------
spans : list of tuple
List of (``onset``, ``offset``) pairs, where ``spans[i]`` gives the
onseta and offset in characters of ``tokens[i]`` relative to the
beginning of ``text`` (0-indexed).
"""
spans = []
bi = 0
for token in tokens:
try:
token_len = len(token)
token_bi = bi + txt[bi:].index(token)
token_ei = token_bi + token_len - 1
spans.append([token_bi, token_ei])
bi = token_ei + 1
except ValueError:
raise AlignmentFailed(token)
return spans
| BUG: Fix typo in variable name.
| """Aligner for texts and their segmentations.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
__all__ = ['AlignmentFailed', 'Aligner']
class AlignmentFailed(Exception): pass
class Aligner(object):
"""Align a text with its tokenization.
"""
def align(self, text, tokens):
"""Align text with its tokeniation.
Parameters
----------
text : str
Text.
tokens : list of str
Tokenization of ``text``.
Returns
-------
spans : list of tuple
List of (``onset``, ``offset``) pairs, where ``spans[i]`` gives the
onseta and offset in characters of ``tokens[i]`` relative to the
beginning of ``text`` (0-indexed).
"""
spans = []
bi = 0
for token in tokens:
try:
token_len = len(token)
token_bi = bi + text[bi:].index(token)
token_ei = token_bi + token_len - 1
spans.append([token_bi, token_ei])
bi = token_ei + 1
except ValueError:
raise AlignmentFailed(token)
return spans
|
from django import template
from .. import perms
from ..settings import get_user_attr
register = template.Library()
@register.filter
def is_masquerading(user):
info = getattr(user, get_user_attr())
return info['is_masquerading']
@register.filter
def can_masquerade(user):
return perms.can_masquerade(user)
@register.filter
def can_masquerade_as(user, masquerade_user):
return perms.can_masquerade_as(user, masquerade_user)
| Make is_masquerading template tag more robust
When masquerading is not enabled, immediately return False to avoid
checking for a request attribute that won't be present.
| from django import template
from .. import perms
from ..settings import get_user_attr, is_enabled
register = template.Library()
@register.filter
def is_masquerading(user):
if not is_enabled():
return False
info = getattr(user, get_user_attr(), None)
return info['is_masquerading']
@register.filter
def can_masquerade(user):
return perms.can_masquerade(user)
@register.filter
def can_masquerade_as(user, masquerade_user):
return perms.can_masquerade_as(user, masquerade_user)
|
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from server import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^$', views.index),
url(r'^api/auth/', include('rest_auth.urls')),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^admin/', admin.site.urls),
]
| Fix to use react-router for all unmatched routes.
| from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from server import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^api/auth/', include('rest_auth.urls')),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^admin/', admin.site.urls),
url(r'^', views.index),
]
|
from django.contrib.admin import StackedInline, TabularInline
from django.template.defaultfilters import slugify
class OrderableInlineMixin(object):
class Media:
js = (
'js/jquery.browser.min.js',
'js/orderable-inline-jquery-ui.js',
'js/orderable-inline.js',
)
css = {
'all': [
'css/orderable-inline.css'
]
}
def get_fieldsets(self, request, obj=None):
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_formset(request, obj, fields=None).form
fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj))
return [
(None, {
'fields': fields,
'classes': self.fieldset_css_classes + ['orderable-field-%s' % self.orderable_field]
})
]
class OrderableStackedInline(OrderableInlineMixin, StackedInline):
fieldset_css_classes = ['orderable-stacked']
class OrderableTabularInline(OrderableInlineMixin, TabularInline):
fieldset_css_classes = ['orderable-tabular']
template = 'orderable_inlines/edit_inline/tabular.html'
| Make this hack compatible with Django 1.9
| from django.contrib.admin import StackedInline, TabularInline
from django.template.defaultfilters import slugify
class OrderableInlineMixin(object):
class Media:
js = (
'js/jquery.browser.min.js',
'js/orderable-inline-jquery-ui.js',
'js/orderable-inline.js',
)
css = {
'all': [
'css/orderable-inline.css'
]
}
def get_fieldsets(self, request, obj=None):
form = self.get_formset(request, obj, fields=None).form
fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj))
return [
(None, {
'fields': fields,
'classes': self.fieldset_css_classes + ['orderable-field-%s' % self.orderable_field]
})
]
class OrderableStackedInline(OrderableInlineMixin, StackedInline):
fieldset_css_classes = ['orderable-stacked']
class OrderableTabularInline(OrderableInlineMixin, TabularInline):
fieldset_css_classes = ['orderable-tabular']
template = 'orderable_inlines/edit_inline/tabular.html'
|
"""Example of integration between Fabric and Datadog.
"""
from fabric.api import *
from fabric.colors import *
from dogapi.fab import setup, notify
setup(api_key = "YOUR API KEY HERE")
# Make sure @notify is just above @task
@notify
@task(default=True, alias="success")
def sweet_task(some_arg, other_arg):
"""Always succeeds"""
print(green("My sweet task always runs properly."))
@notify
@task(alias="failure")
def boring_task(some_arg):
"""Always fails"""
print(red("My boring task is designed to fail."))
raise Exception("failure!!!")
| Update fabric examples to reflect changes.
| """Example of integration between Fabric and Datadog.
"""
from fabric.api import *
from fabric.colors import *
from dogapi.fab import setup, notify
setup(api_key = "YOUR API KEY HERE")
# Make sure @notify is just below @task
@task(default=True, alias="success")
@notify
def sweet_task(some_arg, other_arg):
"""Always succeeds"""
print(green("My sweet task always runs properly."))
@task(alias="failure")
@notify
def boring_task(some_arg):
"""Always fails"""
print(red("My boring task is designed to fail."))
raise Exception("failure!!!")
env.roledefs.update({
'webserver': ['localhost']
})
@task(alias="has_roles")
@notify
@roles('webserver')
@hosts('localhost')
def roles_task(arg_1, arg_2):
run('touch /tmp/fab_test')
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-22 23:41
from __future__ import unicode_literals
from django.db import migrations
def add_billing_address(apps, schema_editor):
''' Data migration add billing_address in Bill from user billing_address
field
'''
Bill = apps.get_model('billjobs', 'Bill')
for bill in Bill.objects.all():
bill.billing_address = bill.user.billing_address
bill.save()
class Migration(migrations.Migration):
dependencies = [
('billjobs', '0002_service_is_available_squashed_0005_bill_issuer_address_default'),
]
operations = [
migrations.RunPython(add_billing_address),
]
| Add billing_address and migrate data
| # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-22 23:41
from __future__ import unicode_literals
from django.db import migrations, models
def add_billing_address(apps, schema_editor):
''' Data migration add billing_address in Bill from user billing_address
field
'''
Bill = apps.get_model('billjobs', 'Bill')
for bill in Bill.objects.all():
bill.billing_address = bill.user.userprofile.billing_address
bill.save()
class Migration(migrations.Migration):
dependencies = [
('billjobs', '0002_service_is_available_squashed_0005_bill_issuer_address_default'),
]
operations = [
migrations.AddField(
model_name='bill',
name='billing_address',
field=models.CharField(max_length=1024),
),
migrations.RunPython(add_billing_address),
]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import django
from django.conf import settings
from django.core.management import call_command
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
opts = {'INSTALLED_APPS': ['widget_tweaks']}
if django.VERSION[:2] < (1, 5):
opts['DATABASES'] = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':MEMORY:',
}
}
if django.VERSION[:2] >= (1, 10):
opts['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
},
]
settings.configure(**opts)
if django.VERSION[:2] >= (1, 7):
django.setup()
if __name__ == "__main__":
call_command('test', 'widget_tweaks')
| :lipstick: Add more verbosity on test running
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import django
from django.conf import settings
from django.core.management import call_command
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
opts = {'INSTALLED_APPS': ['widget_tweaks']}
if django.VERSION[:2] < (1, 5):
opts['DATABASES'] = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':MEMORY:',
}
}
if django.VERSION[:2] >= (1, 10):
opts['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
},
]
settings.configure(**opts)
if django.VERSION[:2] >= (1, 7):
django.setup()
if __name__ == "__main__":
call_command('test', 'widget_tweaks', verbosity=2)
|
# expose the most frequently used functions in the top level.
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
| Add in the init the newly introduced function
| # expose the most frequently used functions in the top level.
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images,
check_if_greyscale_values)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
|
import sys
from java.lang import String
from java.util import HashSet
from java.util import HashMap
import java
globdict = globals()
def loadFilesService():
global globdict
execfile("filesAdmin.py", globdict)
| Customize scripts to work with menu
|
import sys
from java.lang import String
from java.util import HashSet
from java.util import HashMap
import java
globdict = globals()
def loadFilesService():
global globdict
exec open("filesAdmin.py").read()
|
import os
from raven import Client
def generate_event(msg, dsn):
client = Client(dsn)
client.captureMessage(msg)
def clear_inbox(maildir):
print('Clearing inbox at {}'.format(maildir))
for fname in os.listdir(maildir):
os.remove(os.path.join(maildir, fname))
def inbox_should_contain_num_mails(maildir, count):
print('Testing if inbox at {} has {} items.'.format(maildir, count))
count = int(count)
nmails = len(os.listdir(maildir))
if nmails != count:
raise AssertionError(
'Inbox should contain {} messages, but has {}.'.format(
count, nmails)
)
def mail_should_contain_text(maildir, num, text):
print('Testing if mail {} in {} contains text {}.'.format(
num, maildir, text))
mails = os.listdir(maildir)
num = int(num)
if len(mails) < num:
raise AssertionError('Not enough mails in inbox (found {}).'.format(len(mails)))
fname = mails[num - 1]
with open(os.path.join(maildir, fname)) as f:
content = f.read()
if not text in content:
raise AssertionError('Mail does not contain text.')
| Make Clear Inbox keyword more robust.
| import os
from raven import Client
def generate_event(msg, dsn):
client = Client(dsn)
client.captureMessage(msg)
def clear_inbox(maildir):
print('Clearing inbox at {}'.format(maildir))
if not os.path.isdir(maildir):
return
for fname in os.listdir(maildir):
os.remove(os.path.join(maildir, fname))
def inbox_should_contain_num_mails(maildir, count):
print('Testing if inbox at {} has {} items.'.format(maildir, count))
count = int(count)
nmails = len(os.listdir(maildir))
if nmails != count:
raise AssertionError(
'Inbox should contain {} messages, but has {}.'.format(
count, nmails)
)
def mail_should_contain_text(maildir, num, text):
print('Testing if mail {} in {} contains text {}.'.format(
num, maildir, text))
mails = os.listdir(maildir)
num = int(num)
if len(mails) < num:
raise AssertionError('Not enough mails in inbox (found {}).'.format(len(mails)))
fname = mails[num - 1]
with open(os.path.join(maildir, fname)) as f:
content = f.read()
if not text in content:
raise AssertionError('Mail does not contain text.')
|
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import Library, Context, loader
register = Library()
@register.simple_tag( takes_context = True )
def jfu(
context,
template_name = 'jfu/upload_form.html',
upload_handler_name = 'jfu_upload'
):
"""
Displays a form for uploading files using jQuery File Upload.
A user may supply both a custom template or a custom upload-handling URL
name by supplying values for template_name and upload_handler_name
respectively.
"""
context.update( {
'JQ_OPEN' : '{%',
'JQ_CLOSE' : '%}',
'upload_handler_url': reverse( upload_handler_name ),
} )
# Use the request context variable, injected
# by django.core.context_processors.request
# to generate the CSRF token.
context.update( csrf( context.get('request') ) )
t = loader.get_template( template_name )
return t.render( Context( context ) )
| Allow args and kwargs to upload_handler_name
Now can use args and kwargs for reverse url. Example in template:
{% jfu 'core/core_fileuploader.html' 'core_upload' object_id=1 content_type_str='app.model' %} | from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import Library, Context, loader
register = Library()
@register.simple_tag( takes_context = True )
def jfu(
context,
template_name = 'jfu/upload_form.html',
upload_handler_name = 'jfu_upload',
*args, **kwargs
):
"""
Displays a form for uploading files using jQuery File Upload.
A user may supply both a custom template or a custom upload-handling URL
name by supplying values for template_name and upload_handler_name
respectively.
"""
context.update( {
'JQ_OPEN' : '{%',
'JQ_CLOSE' : '%}',
'upload_handler_url': reverse( upload_handler_name, kwargs=kwargs, args=args ),
} )
# Use the request context variable, injected
# by django.core.context_processors.request
# to generate the CSRF token.
context.update( csrf( context.get('request') ) )
t = loader.get_template( template_name )
return t.render( Context( context ) )
|
import os
import logging
from decouple import config
FOLDER = 'public'
FOLDER = FOLDER.strip('/')
log = logging.getLogger('deploy')
def deploy():
import boto
from boto.s3.connection import S3Connection
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
BUCKET_NAME = config('AWS_BUCKET_NAME')
conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.get_bucket(BUCKET_NAME)
key = boto.s3.key.Key(bucket)
for dirpath, dirnames, filenames in os.walk(FOLDER):
# do not use the FOLDER prefix
destpath = dirpath[len(FOLDER):]
destpath = destpath.strip('/')
log.info("Uploading {0} files from {1} to {2} ...".format(len(filenames),
dirpath,
BUCKET_NAME))
for filename in filenames:
key.name = os.path.relpath(os.path.join(destpath, filename)
).replace('\\', '/')
key.set_contents_from_filename(os.path.join(dirpath, filename))
| Change to use logging and set log level to INFO
|
import os
import logging
from decouple import config
FOLDER = 'public'
FOLDER = FOLDER.strip('/')
logging.basicConfig(level=logging.INFO)
def deploy():
import boto
from boto.s3.connection import S3Connection
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
BUCKET_NAME = config('AWS_BUCKET_NAME')
conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.get_bucket(BUCKET_NAME)
key = boto.s3.key.Key(bucket)
for dirpath, dirnames, filenames in os.walk(FOLDER):
# do not use the FOLDER prefix
destpath = dirpath[len(FOLDER):]
destpath = destpath.strip('/')
logging.info("Uploading %s files from %s to %s", len(filenames),
dirpath, BUCKET_NAME)
for filename in filenames:
key.name = os.path.relpath(os.path.join(destpath, filename)
).replace('\\', '/')
key.set_contents_from_filename(os.path.join(dirpath, filename))
logging.debug("Sending %s", key.name)
logging.info("done :)")
|
from tornado import testing
from qotr.server import make_application
from qotr.config import config
class TestChannelHandler(testing.AsyncHTTPTestCase):
'''
Test the channel creation handler.
'''
port = None
application = None
def get_app(self):
return make_application()
def test_index(self):
response = self.fetch('/')
self.assertEqual(200, response.code)
def test_channel(self):
response = self.fetch('/c/foo')
self.assertEqual(200, response.code)
def test_arbitrary(self):
response = self.fetch('/arbitrary-page')
self.assertEqual(404, response.code)
def test_https_redirect(self):
_old_cfg = config.redirect_to_https
config.redirect_to_https = True
response = self.fetch('/c/foo', follow_redirects=False)
config.redirect_to_https = _old_cfg
self.assertEqual(301, response.code)
| Disable testing for index.html, needs ember build
Signed-off-by: Rohan Jain <f3a935f2cb7c3d75d1446a19169b923809d6e623@gmail.com>
| from tornado import testing
from qotr.server import make_application
from qotr.config import config
class TestChannelHandler(testing.AsyncHTTPTestCase):
'''
Test the channel creation handler.
'''
port = None
application = None
def get_app(self):
return make_application()
# def test_index(self):
# response = self.fetch('/')
# self.assertEqual(200, response.code)
# def test_channel(self):
# response = self.fetch('/c/foo')
# self.assertEqual(200, response.code)
# def test_arbitrary(self):
# response = self.fetch('/arbitrary-page')
# self.assertEqual(404, response.code)
def test_https_redirect(self):
_old_cfg = config.redirect_to_https
config.redirect_to_https = True
response = self.fetch('/c/foo', follow_redirects=False)
config.redirect_to_https = _old_cfg
self.assertEqual(301, response.code)
|
from urllib import urlencode
from urllib2 import urlopen
from rapidsms.backends.base import BackendBase
class TropoBackend(BackendBase):
"""A RapidSMS threadless backend for Tropo"""
def configure(self, config=None, **kwargs):
self.config = config
super(TropoBackend, self).configure(**kwargs)
def send(self, message):
base_url = 'http://api.tropo.com/1.0/sessions'
token = self.config['auth_token']
action = 'create'
number = self.config['number']
params = urlencode([('action', action), ('token', token), ('numberToDial', message.connection.identity), ('msg', message.text)])
self.debug("%s?%s" % (base_url, params))
data = urlopen('%s?%s' % (base_url, params)).read()
self.debug(data)
| Fix indentation; override old-style start() from BackendBase
| from urllib import urlencode
from urllib2 import urlopen
from rapidsms.backends.base import BackendBase
class TropoBackend(BackendBase):
"""A RapidSMS threadless backend for Tropo"""
def configure(self, config=None, **kwargs):
self.config = config
def start(self):
"""Override BackendBase.start(), which never returns"""
self._running = True
def send(self, message):
self.debug("send(%s)" % message)
base_url = 'http://api.tropo.com/1.0/sessions'
token = self.config['auth_token']
action = 'create'
number = self.config['number']
params = urlencode([('action', action), ('token', token), ('numberToDial', message.connection.identity), ('msg', message.text)])
self.debug("%s?%s" % (base_url, params))
data = urlopen('%s?%s' % (base_url, params)).read()
self.debug(data)
return True
|
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
| Split the start_date for better data entry (and Javascript date pickers).
| import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
|
# -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
# Bot module contains bot's main class - Sheldon
from sheldon.bot import *
# Hooks module contains hooks for plugins
from sheldon.hooks import *
# Utils folder contains scripts for more
# comfortable work with sending and parsing
# messages. For example, script for downloading
# files by url.
from sheldon.utils import *
__author__ = 'Seva Zhidkov'
__version__ = '0.0.1#dev'
__email__ = 'zhidkovseva@gmail.com'
| Add adapter module to init file
| # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
# Bot module contains bot's main class - Sheldon
from sheldon.bot import *
# Hooks module contains hooks for plugins
from sheldon.hooks import *
# Adapter module contains classes and tools
# for plugins sending messages
from sheldon.adapter import *
# Utils folder contains scripts for more
# comfortable work with sending and parsing
# messages. For example, script for downloading
# files by url.
from sheldon.utils import *
__author__ = 'Seva Zhidkov'
__version__ = '0.0.1#dev'
__email__ = 'zhidkovseva@gmail.com'
|
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Story(models.Model):
url = models.URLField(_('URL'))
title = models.CharField(_('Title'), max_length=64)
excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True)
created_at = models.TimeField(_('Created at'), auto_now_add=True)
is_unread = models.BooleanField(_('Is unread?'), default=True)
| Order stories by descending creation time
| from django.db import models
from django.utils.translation import ugettext_lazy as _
class Story(models.Model):
url = models.URLField(_('URL'))
title = models.CharField(_('Title'), max_length=64)
excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True)
created_at = models.TimeField(_('Created at'), auto_now_add=True)
is_unread = models.BooleanField(_('Is unread?'), default=True)
class Meta:
ordering = ['-created_at']
|
from flask import jsonify
from soundem import app
def json_error_handler(e):
return jsonify({
'status_code': e.code,
'error': 'Bad Request',
'detail': e.description
}), e.code
@app.errorhandler(400)
def bad_request_handler(e):
return json_error_handler(e)
@app.errorhandler(401)
def unauthorized_handler(e):
return json_error_handler(e)
@app.errorhandler(404)
def not_found_handler(e):
return json_error_handler(e)
@app.errorhandler(405)
def method_not_allowed_handler(e):
return json_error_handler(e)
| Fix json error handler name | from flask import jsonify
from soundem import app
def json_error_handler(e):
return jsonify({
'status_code': e.code,
'error': e.name,
'detail': e.description
}), e.code
@app.errorhandler(400)
def bad_request_handler(e):
return json_error_handler(e)
@app.errorhandler(401)
def unauthorized_handler(e):
return json_error_handler(e)
@app.errorhandler(404)
def not_found_handler(e):
return json_error_handler(e)
@app.errorhandler(405)
def method_not_allowed_handler(e):
return json_error_handler(e)
|
import math
import numpy
from demodulate.cfg import *
def gen_tone(pattern, WPM):
cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ
radians_per_sample = cycles_per_sample * 2 * math.pi
elements_per_second = WPM * 50.0 / 60.0
samples_per_element = int(SAMPLE_FREQ/elements_per_second)
length = samples_per_element * len(pattern)
# Empty returns array containing random stuff, so we NEED to overwrite it
data = numpy.empty(length, dtype=numpy.float32)
for i in xrange(length):
keyed = pattern[int(i/samples_per_element)]
#keyed = 1
data[i] = 0 if not keyed else (radians_per_sample * i)
data = numpy.sin(data)
return data
| Use 16 bit samples instead of float
| import math
import numpy
from demodulate.cfg import *
def gen_tone(pattern, WPM):
cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ
radians_per_sample = cycles_per_sample * 2 * math.pi
elements_per_second = WPM * 50.0 / 60.0
samples_per_element = int(SAMPLE_FREQ/elements_per_second)
length = samples_per_element * len(pattern)
# Empty returns array containing random stuff, so we NEED to overwrite it
data = numpy.empty(length, dtype=numpy.float32)
for i in xrange(length):
keyed = pattern[int(i/samples_per_element)]
#keyed = 1
data[i] = 0 if not keyed else (radians_per_sample * i)
data = numpy.sin(data)
data *= 2**16-1
data = numpy.array(data, dtype=numpy.int16)
return data
|
from django.utils.simplejson import simplejson
from oembed.exceptions import OEmbedException
class OEmbedResource(object):
"""
OEmbed resource, as well as a factory for creating resource instances
from response json
"""
_data = {}
content_object = None
def __getattr__(self, name):
return self._data.get(name)
def get_data(self):
return self._data
def load_data(self, data):
self._data = data
@property
def json(self):
return simplejson.dumps(self._data)
@classmethod
def create(cls, data):
if not 'type' in data or not 'version' in data:
raise OEmbedException('Missing required fields on OEmbed response.')
data['width'] = data.get('width') and int(data['width']) or None
data['height'] = data.get('height') and int(data['height']) or None
filtered_data = dict([(k, v) for k, v in data.items() if v])
resource = cls()
resource.load_data(filtered_data)
return resource
@classmethod
def create_json(cls, raw):
data = simplejson.loads(raw)
return cls.create(data)
| Use the simplejson bundled with django
| from django.utils import simplejson
from oembed.exceptions import OEmbedException
class OEmbedResource(object):
"""
OEmbed resource, as well as a factory for creating resource instances
from response json
"""
_data = {}
content_object = None
def __getattr__(self, name):
return self._data.get(name)
def get_data(self):
return self._data
def load_data(self, data):
self._data = data
@property
def json(self):
return simplejson.dumps(self._data)
@classmethod
def create(cls, data):
if not 'type' in data or not 'version' in data:
raise OEmbedException('Missing required fields on OEmbed response.')
data['width'] = data.get('width') and int(data['width']) or None
data['height'] = data.get('height') and int(data['height']) or None
filtered_data = dict([(k, v) for k, v in data.items() if v])
resource = cls()
resource.load_data(filtered_data)
return resource
@classmethod
def create_json(cls, raw):
data = simplejson.loads(raw)
return cls.create(data)
|
import json
from flask import request, current_app, redirect
from flaskext.bcrypt import generate_password_hash
def get_ip():
ip = request.remote_addr
if ip == '127.0.0.1' or ip == '127.0.0.2' and "X-Real-IP" in request.headers:
ip = request.headers.get("X-Real-IP")
return ip
def makeMask(n):
"return a mask of n bits as a long integer"
return (2 << n - 1) - 1
def dottedQuadToNum(ip):
"convert decimal dotted quad string to long integer"
parts = ip.split(".")
return int(parts[0]) | (int(parts[1]) << 8) | (int(parts[2]) << 16) | (int(parts[3]) << 24)
def networkMask(ip, bits):
"Convert a network address to a long integer"
return dottedQuadToNum(ip) & makeMask(bits)
def addressInNetwork(ip, net):
"Is an address in a network"
return ip & net == net
def secure_ip():
ip = get_ip()
if ip == '127.0.0.3' and not current_app.debug:
return 'anonymous_user'
return generate_password_hash(ip)
def is_tor():
return get_ip() == '127.0.0.3'
| Update IP address Tor traffic comes from
| import json
from flask import request, current_app, redirect
from flaskext.bcrypt import generate_password_hash
def get_ip():
ip = request.remote_addr
if ip == '127.0.0.1' or ip == '127.0.0.2' and "X-Real-IP" in request.headers:
ip = request.headers.get("X-Real-IP")
return ip
def makeMask(n):
"return a mask of n bits as a long integer"
return (2 << n - 1) - 1
def dottedQuadToNum(ip):
"convert decimal dotted quad string to long integer"
parts = ip.split(".")
return int(parts[0]) | (int(parts[1]) << 8) | (int(parts[2]) << 16) | (int(parts[3]) << 24)
def networkMask(ip, bits):
"Convert a network address to a long integer"
return dottedQuadToNum(ip) & makeMask(bits)
def addressInNetwork(ip, net):
"Is an address in a network"
return ip & net == net
def secure_ip():
ip = get_ip()
if ip == '127.0.0.3' and not current_app.debug:
return 'anonymous_user'
return generate_password_hash(ip)
def is_tor():
return get_ip() == '5.254.104.62'
|
# 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.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
# TODO(vmpstr): Memory drops and increases again, and this
# particular bot happens to catch it when its low. Remove
# once the bug is fixed.
self.Fail('Memory.CSS3D', ['win'], bug=373098)
| Add a failure expectation to Linux memory.css3d test.
BUG=373098
NOTRY=true
R=kbr@chromium.org
Review URL: https://codereview.chromium.org/303503009
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@273109 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.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
# TODO(vmpstr): Memory drops and increases again, and this
# particular bot happens to catch it when its low. Remove
# once the bug is fixed.
self.Fail('Memory.CSS3D', ['win'], bug=373098)
# Test has turned flaky on Linux also. Remove once the bug is fixed.
self.Fail('Memory.CSS3D', ['linux'], bug=373098)
|
# -*- coding: utf-8 -*-
import pytest
from marshmallow import validate, ValidationError
def test_invalid_email():
invalid1 = "user@example"
with pytest.raises(ValidationError):
validate.email(invalid1)
invalid2 = "example.com"
with pytest.raises(ValidationError):
validate.email(invalid2)
invalid3 = "user"
with pytest.raises(ValidationError):
validate.email(invalid3)
with pytest.raises(ValidationError):
validate.email('@nouser.com')
def test_validate_email_none():
assert validate.email(None) is None
def test_validate_url_none():
assert validate.url(None) is None
| Add length validator unit tests | # -*- coding: utf-8 -*-
import pytest
from marshmallow import validate, ValidationError
def test_invalid_email():
invalid1 = "user@example"
with pytest.raises(ValidationError):
validate.email(invalid1)
invalid2 = "example.com"
with pytest.raises(ValidationError):
validate.email(invalid2)
invalid3 = "user"
with pytest.raises(ValidationError):
validate.email(invalid3)
with pytest.raises(ValidationError):
validate.email('@nouser.com')
def test_validate_email_none():
assert validate.email(None) is None
def test_validate_url_none():
assert validate.url(None) is None
def test_min_length():
with pytest.raises(ValidationError):
validate.length('foo', 4, 5)
assert validate.length('foo', 3, 5) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 4, 5)
assert validate.length([1, 2, 3], 3, 5) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', 5)
def test_max_length():
with pytest.raises(ValidationError):
validate.length('foo', 1, 2)
assert validate.length('foo', 1, 3) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 1, 2)
assert validate.length([1, 2, 3], 1, 3) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', None, 2)
def test_validate_length_none():
assert validate.length(None) is None
|
import unittest
from simplejson import dumps
from twisted.trial.unittest import TestCase
from twisted.internet import defer
from mock import patch, Mock
from van.contactology import Contactology
class TestProxy(TestCase):
@defer.inlineCallbacks
def test_list_return(self):
patcher = patch('van.contactology.getPage')
getPage = patcher.start()
try:
proxy = Contactology('API Key')
getPage.return_value = dumps([])
out = yield proxy.Campaign_Find()
yield self.assertEquals(out, [])
finally:
patcher.stop()
| Test for exception raising on API error.
| import unittest
from simplejson import dumps
from twisted.trial.unittest import TestCase
from twisted.internet import defer
from mock import patch, Mock
from van.contactology import Contactology, APIError
class TestProxy(TestCase):
@defer.inlineCallbacks
def test_list_return(self):
patcher = patch('van.contactology.getPage')
getPage = patcher.start()
try:
proxy = Contactology('API Key')
getPage.return_value = dumps([])
out = yield proxy.Campaign_Find()
yield self.assertEquals(out, [])
finally:
patcher.stop()
@defer.inlineCallbacks
def test_api_error(self):
patcher = patch('van.contactology.getPage')
getPage = patcher.start()
try:
proxy = Contactology('API Key')
getPage.return_value = dumps({'code': 221, 'message': 'Key not found', 'result': 'error'})
yield self.failUnlessFailure(proxy.List_Get_Active_Lists(), APIError)
finally:
patcher.stop()
|
# coding: utf8
from __future__ import unicode_literals
from .stop_words import STOP_WORDS
from .lex_attrs import LEX_ATTRS
from .punctuation import TOKENIZER_SUFFIXES
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class ArabicDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters.update(LEX_ATTRS)
lex_attr_getters[LANG] = lambda text: "ar"
lex_attr_getters[NORM] = add_lookups(
Language.Defaults.lex_attr_getters[NORM], BASE_NORMS
)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
stop_words = STOP_WORDS
suffixes = TOKENIZER_SUFFIXES
class Arabic(Language):
lang = "ar"
Defaults = ArabicDefaults
__all__ = ["Arabic"]
| Add writing_system to ArabicDefaults (experimental)
| # coding: utf8
from __future__ import unicode_literals
from .stop_words import STOP_WORDS
from .lex_attrs import LEX_ATTRS
from .punctuation import TOKENIZER_SUFFIXES
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
class ArabicDefaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters.update(LEX_ATTRS)
lex_attr_getters[LANG] = lambda text: "ar"
lex_attr_getters[NORM] = add_lookups(
Language.Defaults.lex_attr_getters[NORM], BASE_NORMS
)
tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
stop_words = STOP_WORDS
suffixes = TOKENIZER_SUFFIXES
writing_system = {"direction": "rtl", "has_case": False, "has_letters": True}
class Arabic(Language):
lang = "ar"
Defaults = ArabicDefaults
__all__ = ["Arabic"]
|
#!/usr/bin/python
# Copyright (c) 2006 rPath, Inc
# All rights reserved
import sys
import os
import pwd
from conary.server import schema
from conary.lib import cfgtypes, tracelog
from conary.repository.netrepos.netserver import ServerConfig
from conary import dbstore
class SimpleFileLog(tracelog.FileLog):
def printLog(self, level, msg):
self.fd.write("%s\n" % msg)
cnrPath = '/srv/conary/repository.cnr'
cfg = ServerConfig()
tracelog.FileLog = SimpleFileLog
tracelog.initLog(filename='stderr', level=2)
try:
cfg.read(cnrPath)
except cfgtypes.CfgEnvironmentError:
print "Error reading %s" % cnrPath
sys.exit(1)
db = dbstore.connect(cfg.repositoryDB[1], cfg.repositoryDB[0])
schema.loadSchema(db, doMigrate=True)
if cfg.repositoryDB[0] == 'sqlite':
os.chown(cfg.repositoryDB[1], pwd.getpwnam('apache')[2],
pwd.getpwnam('apache')[3])
| Update conary migration script to deal with extended config
| #!/usr/bin/python
#
# Copyright (c) SAS Institute Inc.
#
import sys
import os
import pwd
from conary.server import schema
from conary.lib import cfgtypes, tracelog
from conary import dbstore
from .config import UpsrvConfig
class SimpleFileLog(tracelog.FileLog):
def printLog(self, level, msg):
self.fd.write("%s\n" % msg)
try:
cfg = UpsrvConfig.load()
except cfgtypes.CfgEnvironmentError:
print "Error reading config file"
sys.exit(1)
tracelog.FileLog = SimpleFileLog
tracelog.initLog(filename='stderr', level=2)
db = dbstore.connect(cfg.repositoryDB[1], cfg.repositoryDB[0])
schema.loadSchema(db, doMigrate=True)
if cfg.repositoryDB[0] == 'sqlite':
os.chown(cfg.repositoryDB[1], pwd.getpwnam('apache')[2],
pwd.getpwnam('apache')[3])
|
#!/usr/local/bin/python
# Code Fights Add Border Problem
def arrayReplace(inputArray, elemToReplace, substitutionElem):
pass
def main():
pass
if __name__ == '__main__':
main()
| Solve Code Fights array replace problem
| #!/usr/local/bin/python
# Code Fights Add Border Problem
def arrayReplace(inputArray, elemToReplace, substitutionElem):
return [x if x != elemToReplace else substitutionElem for x in inputArray]
def main():
tests = [
[[1, 2, 1], 1, 3, [3, 2, 3]],
[[1, 2, 3, 4, 5], 3, 0, [1, 2, 0, 4, 5]],
[[1, 1, 1], 1, 10, [10, 10, 10]]
]
for t in tests:
res = arrayReplace(t[0], t[1], t[2])
if t[3] == res:
print("PASSED: arrayReplace({}, {}, {}) returned {}"
.format(t[0], t[1], t[2], res))
else:
print("FAILED: arrayReplace({}, {}, {}) returned {}, should have returned {}"
.format(t[0], t[1], t[2], res, t[3]))
if __name__ == '__main__':
main()
|
# stdlib
from typing import Any
from typing import Dict
# third party
from pandas import DataFrame
# syft relative
from ...messages.infra_messages import CreateWorkerMessage
from ...messages.infra_messages import DeleteWorkerMessage
from ...messages.infra_messages import GetWorkerMessage
from ...messages.infra_messages import GetWorkersMessage
from ...messages.infra_messages import UpdateWorkerMessage
from .request_api import GridRequestAPI
class WorkerRequestAPI(GridRequestAPI):
response_key = "worker"
def __init__(self, send):
super().__init__(
create_msg=CreateWorkerMessage,
get_msg=GetWorkerMessage,
get_all_msg=GetWorkersMessage,
update_msg=UpdateWorkerMessage,
delete_msg=DeleteWorkerMessage,
send=send,
response_key=WorkerRequestAPI.response_key,
)
def __getitem__(self, key):
return self.get(worker_id=key)
def __delitem__(self, key):
self.delete(worker_id=key)
| Update Worker API
- ADD type hints
- Remove unused imports
| # stdlib
from typing import Callable
# syft relative
from ...messages.infra_messages import CreateWorkerMessage
from ...messages.infra_messages import DeleteWorkerMessage
from ...messages.infra_messages import GetWorkerMessage
from ...messages.infra_messages import GetWorkersMessage
from ...messages.infra_messages import UpdateWorkerMessage
from .request_api import GridRequestAPI
class WorkerRequestAPI(GridRequestAPI):
response_key = "worker"
def __init__(self, send: Callable):
super().__init__(
create_msg=CreateWorkerMessage,
get_msg=GetWorkerMessage,
get_all_msg=GetWorkersMessage,
update_msg=UpdateWorkerMessage,
delete_msg=DeleteWorkerMessage,
send=send,
response_key=WorkerRequestAPI.response_key,
)
def __getitem__(self, key: int) -> object:
return self.get(worker_id=key)
def __delitem__(self, key: int) -> None:
self.delete(worker_id=key)
|
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext
from django.contrib.sites.models import Site
from notification import backends
from notification.message import message_to_text
# favour django-mailer but fall back to django.core.mail
try:
from mailer import send_mail
except ImportError:
from django.core.mail import send_mail
class EmailBackend(backends.BaseBackend):
def can_send(self, user, notice_type):
if should_send(user, notice_type, "1") and user.email:
return True
return False
def deliver(self, recipients, notice_type, message):
notices_url = u"http://%s%s" % (
unicode(Site.objects.get_current()),
reverse("notification_notices"),
)
subject = render_to_string("notification/notification_subject.txt", {
"display": ugettext(notice_type.display),
})
message_body = render_to_string("notification/notification_body.txt", {
"message": message_to_text(message),
"notices_url": notices_url,
"contact_email": settings.CONTACT_EMAIL,
})
send_mail(subject, message_body,
settings.DEFAULT_FROM_EMAIL, recipients)
| pluggable-backends: Use get_app over to include django-mailer support over a standard import and ImportError exception handling.
git-svn-id: 12265af7f62f437cb19748843ef653b20b846039@130 590c3fc9-4838-0410-bb95-17a0c9b37ca9
|
from django.conf import settings
from django.db.models.loading import get_app
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
from notification import backends
from notification.message import message_to_text
# favour django-mailer but fall back to django.core.mail
try:
mailer = get_app("mailer")
from mailer import send_mail
except ImproperlyConfigured:
from django.core.mail import send_mail
class EmailBackend(backends.BaseBackend):
def can_send(self, user, notice_type):
if should_send(user, notice_type, "1") and user.email:
return True
return False
def deliver(self, recipients, notice_type, message):
notices_url = u"http://%s%s" % (
unicode(Site.objects.get_current()),
reverse("notification_notices"),
)
subject = render_to_string("notification/notification_subject.txt", {
"display": ugettext(notice_type.display),
})
message_body = render_to_string("notification/notification_body.txt", {
"message": message_to_text(message),
"notices_url": notices_url,
"contact_email": settings.CONTACT_EMAIL,
})
send_mail(subject, message_body,
settings.DEFAULT_FROM_EMAIL, recipients)
|
#!/usr/bin/env python
import sys
print("argv: %d" % len(sys.argv))
# Object related test
print(type(sys.argv))
print(id(sys.argv))
print(type(sys.argv) is list)
if len(sys.argv) != 2:
print("%s filename" % sys.argv[0])
raise SystemExit(1)
file = open(sys.argv[1], "w")
line = []
while True:
line = sys.stdin.readline()
if line == "quit\n":
break
file.write(line)
file.close()
print("\nok. start to dump %s:" % sys.argv[1])
for line in open(sys.argv[1]):
print line.rstrip()
file = open(sys.argv[1])
lines = file.readlines()
file.close()
print(lines)
fval = [float(line) for line in lines]
print(fval)
print("len: %d" % len(fval))
for i in range(len(fval)):
print i, " ", fval[i]
| Add comment for object types
| #!/usr/bin/env python
import sys
print("argv: %d" % len(sys.argv))
# Object related test
# type and id are unique
# ref: https://docs.python.org/2/reference/datamodel.html
# mutable object: value can be changed
# immutable object: value can NOT be changed after created
# This means readonly
# ex: string, numbers, tuple
print(type(sys.argv))
print(id(sys.argv))
print(type(sys.argv) is list)
if len(sys.argv) != 2:
print("%s filename" % sys.argv[0])
raise SystemExit(1)
file = open(sys.argv[1], "w")
line = []
while True:
line = sys.stdin.readline()
if line == "quit\n":
break
file.write(line)
file.close()
print("\nok. start to dump %s:" % sys.argv[1])
for line in open(sys.argv[1]):
print line.rstrip()
file = open(sys.argv[1])
lines = file.readlines()
file.close()
print(lines)
fval = [float(line) for line in lines]
print(fval)
print("len: %d" % len(fval))
for i in range(len(fval)):
print i, " ", fval[i]
|
import warnings
from haystack import indexes
from avocado.conf import settings
from avocado.models import DataConcept, DataField
# Warn if either of the settings are set to false
if not getattr(settings, 'CONCEPT_SEARCH_ENABLED', True) or \
not getattr(settings, 'FIELD_SEARCH_ENABLED', True):
warnings.warn('CONCEPT_SEARCH_ENABLED and FIELD_SEARCH_ENABLED have been '
'deprecated due to changes in Haystack 2.x API. To exclude '
'an index from being discovered, add the path to the class '
'to EXCLUDED_INDEXES in the appropriate '
'HAYSTACK_CONNECTIONS entry in settings.')
class DataIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
text_auto = indexes.EdgeNgramField(use_template=True)
def index_queryset(self, using=None):
return self.get_model().objects.published()
def load_all_queryset(self):
return self.index_queryset()
class DataConceptIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataConcept
class DataFieldIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataField
| Change DataIndex to restrict on published and archived flags only
In addition, the warnings of the deprecated settings have been removed.
Fix #290
Signed-off-by: Byron Ruth <e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98@devel.io>
| from haystack import indexes
from avocado.models import DataConcept, DataField
class DataIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
text_auto = indexes.EdgeNgramField(use_template=True)
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True, archived=False)
def read_queryset(self, using=None):
return self.index_queryset()
def load_all_queryset(self):
return self.index_queryset()
class DataConceptIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataConcept
class DataFieldIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataField
|
# -*- coding: utf-8 -*-# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_DIR, 'test.sqlite3'),
}
}
TEMPLATE_CONTEXT_PROCESSORS += (
"django.core.context_processors.debug",
)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
INSTALLED_APPS += ('django_extensions',)
DEVICE_VERIFICATION_CODE = 11111
# DEBUG TOOLBAR
INSTALLED_APPS += ('debug_toolbar',)
| Remove debug toolbar in test settings
| # -*- coding: utf-8 -*-# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_DIR, 'test.sqlite3'),
}
}
TEMPLATE_CONTEXT_PROCESSORS += (
"django.core.context_processors.debug",
)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
INSTALLED_APPS += ('django_extensions',)
DEVICE_VERIFICATION_CODE = 11111
|
from flask import render_template, g, redirect, request
from db import connect_db, get_all_sum
from statistics import app
@app.before_request
def before_request():
g.db = connect_db()
g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"]
@app.route("/")
def main_page():
sort_by = request.args.get('sort_by', None)
data = get_all_sum(g.db)
if sort_by:
data = sorted(data, key=lambda row: row[sort_by])
return render_template("main_page.html", data=data)
@app.route("/add/")
def add_page():
key = request.args.get('KEY')
for field in g.fields:
new_val = int(request.args.get(field, '0'))
old_val = int(g.db.hget(key, field) or '0')
new_val += old_val
g.db.hset(key, field, new_val)
g.db.hincrby(key, "REQUESTS", "1")
return redirect("/")
| Add proto of average page. Without sorting.
| from flask import render_template, g, redirect, request
from db import connect_db, get_all_sum
from statistics import app
@app.before_request
def before_request():
g.db = connect_db()
g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"]
@app.route("/")
def main_page():
sort_by = request.args.get('sort_by', None)
data = get_all_sum(g.db)
if sort_by:
data = sorted(data, key=lambda row: row[sort_by])
return render_template("main_page.html", data=data)
@app.route("/average/")
def average():
data = get_all_sum(g.db)
for row in data:
req_count = row['REQUESTS']
for k in row:
if k != 'NAME' and k != 'REQUESTS':
row[k] = float(row[k])/req_count
return render_template("main_page.html", data=data)
@app.route("/add/")
def add_page():
key = request.args.get('KEY')
for field in g.fields:
new_val = int(request.args.get(field, '0'))
old_val = int(g.db.hget(key, field) or '0')
new_val += old_val
g.db.hset(key, field, new_val)
g.db.hincrby(key, "REQUESTS", "1")
return redirect("/")
|
import json
from rest_framework.authtoken.models import Token
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
from bluebottle.clients import properties
from bluebottle.clients.models import Client
from bluebottle.clients.utils import LocalTenant
class Command(BaseCommand):
help = 'Export tenants, so that we can import them into the accounting app'
def add_arguments(self, parser):
parser.add_argument('--file', type=str, default=None, action='store')
def handle(self, *args, **options):
results = []
for client in Client.objects.all():
properties.set_tenant(client)
with LocalTenant(client, clear_tenant=True):
ContentType.objects.clear_cache()
accounts = []
for merchant in properties.MERCHANT_ACCOUNTS:
if merchant['merchant'] == 'docdata':
accounts.append(
{
'service_type': 'docdata',
'username': merchant['merchant_name']
}
)
api_key = Token.objects.get(user__username='accounting').key
results.append({
"name": client.schema_name,
"domain": properties.TENANT_MAIL_PROPERTIES['website'],
"api_key": api_key,
"accounts": accounts
})
if options['file']:
text_file = open(options['file'], "w")
text_file.write(json.dumps(results))
text_file.close()
else:
print json.dumps(results)
| Use client_name instead of schema_name
| import json
from rest_framework.authtoken.models import Token
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
from bluebottle.clients import properties
from bluebottle.clients.models import Client
from bluebottle.clients.utils import LocalTenant
class Command(BaseCommand):
help = 'Export tenants, so that we can import them into the accounting app'
def add_arguments(self, parser):
parser.add_argument('--file', type=str, default=None, action='store')
def handle(self, *args, **options):
results = []
for client in Client.objects.all():
properties.set_tenant(client)
with LocalTenant(client, clear_tenant=True):
ContentType.objects.clear_cache()
accounts = []
for merchant in properties.MERCHANT_ACCOUNTS:
if merchant['merchant'] == 'docdata':
accounts.append(
{
'service_type': 'docdata',
'username': merchant['merchant_name']
}
)
api_key = Token.objects.get(user__username='accounting').key
results.append({
"name": client.client_name,
"domain": properties.TENANT_MAIL_PROPERTIES['website'],
"api_key": api_key,
"accounts": accounts
})
if options['file']:
text_file = open(options['file'], "w")
text_file.write(json.dumps(results))
text_file.close()
else:
print json.dumps(results)
|
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from djs_playground.views import index
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^summernote/', include('django_summernote.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| Change url in favor of the re_path
| from django.conf import settings
from django.urls import re_path, include
from django.conf.urls.static import static
from django.contrib import admin
from djs_playground.views import index
urlpatterns = [
re_path(r'^$', index, name='index'),
re_path(r'^admin/', admin.site.urls),
re_path(r'^summernote/', include('django_summernote.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule
class InvalidSyntaxTest(TestCase):
pass
if __name__ == '__main__':
main() | Add base set of rule's invalid syntax tests
| #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule
from grammpy.exceptions import RuleSyntaxException
from .grammar import *
class InvalidSyntaxTest(TestCase):
def test_rulesMissingEncloseList(self):
class tmp(Rule):
rules = ([0], [1])
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_rulesMissingTuple(self):
class tmp(Rule):
rules = [[0], [1]]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_rulesMissingInnerLeftList(self):
class tmp(Rule):
rules = [(0, [1])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_rulesMissingInnerRightList(self):
class tmp(Rule):
rules = [([0], 1)]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_multipleRulesMissingInnerLeftList(self):
class tmp(Rule):
rules = [(NFirst, TSecond), (0, [1])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_multipleRulesMissingInnerRightList(self):
class tmp(Rule):
rules = [(NFifth, TFirst), ([0], 1)]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_emptyRule(self):
class tmp(Rule):
rules = [([], [])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_emptyOneOfRules(self):
class tmp(Rule):
rules = [(NFifth, TFirst), ([], [])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_onlyOuterArray(self):
class tmp(Rule):
rules = [NFifth, TFirst]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_outerIsTuple(self):
class tmp(Rule):
rules = (([NFirst], [TSecond]), ([0], [1]))
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
if __name__ == '__main__':
main()
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
from reversion.revisions import default_revision_manager
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
default_revision_manager.save_revision((item,))
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
| Fix broken initial version creation.
| from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
def create_initial_version(obj):
try:
from reversion.revisions import default_revision_manager
default_revision_manager.save_revision((obj,))
except:
from reversion.revisions import add_to_revision
add_to_revision(obj)
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
create_initial_version(item)
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
|
#!/usr/bin/env python
import os.path
import sys
import imp
import argparse
from api import App, add_subparsers
def load_plugins(dir):
for f in os.listdir(dir):
module_name, ext = os.path.splitext(f)
if ext == '.py':
imp.load_source('arbitrary', os.path.join(dir, f))
def main(args=sys.argv[1:]):
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/evaluators'))
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/apps'))
parser = argparse.ArgumentParser()
add_subparsers(parser, sorted(App.CLASSES.items()), 'app_cls', title='apps')
args = parser.parse_args()
args.app_cls(parser, args)()
if __name__ == '__main__':
main(sys.argv[1:])
| Allow sub-commands to use same main function
| #!/usr/bin/env python
import os.path
import sys
import imp
import argparse
from api import App, add_subparsers
def load_plugins(dir):
for f in os.listdir(dir):
module_name, ext = os.path.splitext(f)
if ext == '.py':
imp.load_source('arbitrary', os.path.join(dir, f))
def main(args=None):
if args is None:
args = sys.argv[1:]
cmd = os.path.basename(sys.argv[0])
if cmd.startswith('dr-'):
args.insert(0, cmd[3:])
prog = 'dr'
else:
prog = None
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/evaluators'))
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/apps'))
parser = argparse.ArgumentParser(prog=prog)
add_subparsers(parser, sorted(App.CLASSES.items()), 'app_cls', title='apps')
args = parser.parse_args(args)
args.app_cls(parser, args)()
if __name__ == '__main__':
main()
|
# coding: utf-8
import os
import traceback
from .handlers import find_handler
_activate_debugger = os.environ.get('DEBUG') == 'yes'
if _activate_debugger:
try:
from trepan.api import debug
set_trace = debug
except ImportError:
import pdb
set_trace = pdb.set_trace
def signal(e):
"""
Some docstrings.
"""
callback = find_handler(e)
if callback is None:
if _activate_debugger:
print 'Handler for error {0} not found'.format(type(e))
traceback.print_stack()
set_trace()
raise e
else:
return callback(e)
| Fix use of Python 2 print
| # coding: utf-8
from __future__ import print_function
import os
import traceback
from .handlers import find_handler
_activate_debugger = os.environ.get('DEBUG') == 'yes'
if _activate_debugger:
try:
from trepan.api import debug
set_trace = debug
except ImportError:
import pdb
set_trace = pdb.set_trace
def signal(e):
"""
Some docstrings.
"""
callback = find_handler(e)
if callback is None:
if _activate_debugger:
print('Handler for error {0} not found'.format(type(e)))
traceback.print_stack()
set_trace()
raise e
else:
return callback(e)
|
''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
| Fix bench error on scipy import when nose is not installed
| ''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
def bench(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for benchmarks - see %s' % nose_url
|
from scrapy.item import Item, Field
class DatasetItem(Item):
name = Field()
frequency = Field()
| Add url field to Dataset web item
| from scrapy.item import Item, Field
class DatasetItem(Item):
url = Field()
name = Field()
frequency = Field()
|
from . import AWSObject, AWSProperty, Tags
from .validators import boolean
class DataResource(AWSProperty):
props = {
"Type": (str, True),
"Values": ([str], False),
}
class EventSelector(AWSProperty):
props = {
"DataResources": ([DataResource], False),
"IncludeManagementEvents": (boolean, False),
"ReadWriteType": (str, False),
}
class Trail(AWSObject):
resource_type = "AWS::CloudTrail::Trail"
props = {
"CloudWatchLogsLogGroupArn": (str, False),
"CloudWatchLogsRoleArn": (str, False),
"EnableLogFileValidation": (boolean, False),
"EventSelectors": ([EventSelector], False),
"IncludeGlobalServiceEvents": (boolean, False),
"IsLogging": (boolean, True),
"IsMultiRegionTrail": (boolean, False),
"KMSKeyId": (str, False),
"S3BucketName": (str, True),
"S3KeyPrefix": (str, False),
"SnsTopicName": (str, False),
"Tags": (Tags, False),
"TrailName": (str, False),
}
| Update Cloudtrail per 2021-09-10 changes
| from . import AWSObject, AWSProperty, Tags
from .validators import boolean
class DataResource(AWSProperty):
props = {
"Type": (str, True),
"Values": ([str], False),
}
class EventSelector(AWSProperty):
props = {
"DataResources": ([DataResource], False),
"ExcludeManagementEventSources": ([str], False),
"IncludeManagementEvents": (boolean, False),
"ReadWriteType": (str, False),
}
class InsightSelector(AWSProperty):
props = {
"InsightType": (str, False),
}
class Trail(AWSObject):
resource_type = "AWS::CloudTrail::Trail"
props = {
"CloudWatchLogsLogGroupArn": (str, False),
"CloudWatchLogsRoleArn": (str, False),
"EnableLogFileValidation": (boolean, False),
"EventSelectors": ([EventSelector], False),
"IncludeGlobalServiceEvents": (boolean, False),
"InsightSelectors": ([InsightSelector], False),
"IsLogging": (boolean, True),
"IsMultiRegionTrail": (boolean, False),
"IsOrganizationTrail": (boolean, False),
"KMSKeyId": (str, False),
"S3BucketName": (str, True),
"S3KeyPrefix": (str, False),
"SnsTopicName": (str, False),
"Tags": (Tags, False),
"TrailName": (str, False),
}
|
# Copyright (c) 2017, Frappe and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })
frappe.reload_doc("stock", "doctype", "item")
frappe.reload_doc("stock", "doctype", "item_barcode")
for item in items_barcode:
barcode = item.barcode.strip()
if barcode and '<' not in barcode:
try:
frappe.get_doc({
'idx': 0,
'doctype': 'Item Barcode',
'barcode': barcode,
'parenttype': 'Item',
'parent': item.name,
'parentfield': 'barcodes'
}).insert()
except frappe.DuplicateEntryError:
continue
| Move reload doc before get query
| # Copyright (c) 2017, Frappe and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("stock", "doctype", "item_barcode")
items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })
frappe.reload_doc("stock", "doctype", "item")
for item in items_barcode:
barcode = item.barcode.strip()
if barcode and '<' not in barcode:
try:
frappe.get_doc({
'idx': 0,
'doctype': 'Item Barcode',
'barcode': barcode,
'parenttype': 'Item',
'parent': item.name,
'parentfield': 'barcodes'
}).insert()
except frappe.DuplicateEntryError:
continue
|
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Farmer(models.Model):
first_name = models.CharField(_('first name'), max_length=50)
surname = models.CharField(_('surname'), max_length=50)
town = models.CharField(_('town'), max_length=50, db_index=True)
class Meta:
verbose_name = _('farmer')
verbose_name_plural = _('farmers')
def __str__(self):
return self.get_full_name()
def get_full_name(self):
return '%s %s' % (self.first_name, self.surname)
def get_short_name(self):
return '%s. %s' % (self.first_name[:1], self_surname)
| Repair bug in the Farmer model
| from django.db import models
from django.utils.translation import ugettext_lazy as _
class Farmer(models.Model):
first_name = models.CharField(_('first name'), max_length=50)
surname = models.CharField(_('surname'), max_length=50)
town = models.CharField(_('town'), max_length=50, db_index=True)
class Meta:
verbose_name = _('farmer')
verbose_name_plural = _('farmers')
def __str__(self):
return self.get_full_name()
def get_full_name(self):
return '%s %s' % (self.first_name, self.surname)
def get_short_name(self):
return '%s. %s' % (self.first_name[:1], self.surname)
|
# Standard imports
import math
import logging
import numpy as np
import emission.core.common as ec
import emission.analysis.section_features as sf
def calDistance(point1, point2):
return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude])
def calHeading(point1, point2):
return sf.calHeading([point1.longitude, point1.latitude],
[point2.longitude, point2.latitude])
def calHC(point1, point2, point3):
return sf.calHC([point1.longitude, point1.latitude],
[point2.longitude, point2.latitude],
[point3.longitude, point3.latitude])
def calSpeed(point1, point2):
distanceDelta = calDistance(point1, point2)
timeDelta = point2.mTime - point1.mTime
# print "Distance delta = %s and time delta = %s" % (distanceDelta, timeDelta)
# assert(timeDelta != 0)
if (timeDelta == 0):
logging.debug("timeDelta = 0, distanceDelta = %s, returning speed = 0")
assert(distanceDelta < 0.01)
return 0
# TODO: Once we perform the conversions from ms to secs as part of the
# usercache -> timeseries switch, we need to remove this division by 1000
return distanceDelta/(float(timeDelta)/1000)
| Change the feature calculation to match the new unified format
- the timestamps are now in seconds, so no need to divide them
- the field is called ts, not mTime
| # Standard imports
import math
import logging
import numpy as np
import emission.core.common as ec
import emission.analysis.section_features as sf
def calDistance(point1, point2):
return ec.calDistance([point1.longitude, point1.latitude], [point2.longitude, point2.latitude])
def calHeading(point1, point2):
return sf.calHeading([point1.longitude, point1.latitude],
[point2.longitude, point2.latitude])
def calHC(point1, point2, point3):
return sf.calHC([point1.longitude, point1.latitude],
[point2.longitude, point2.latitude],
[point3.longitude, point3.latitude])
def calSpeed(point1, point2):
distanceDelta = calDistance(point1, point2)
timeDelta = point2.ts - point1.ts
# print "Distance delta = %s and time delta = %s" % (distanceDelta, timeDelta)
# assert(timeDelta != 0)
if (timeDelta == 0):
logging.debug("timeDelta = 0, distanceDelta = %s, returning speed = 0")
assert(distanceDelta < 0.01)
return 0
return distanceDelta/timeDelta
|
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Mike Place <mp@saltstack.com>`
'''
# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch
from salt import minion
from salt.exceptions import SaltSystemExit
ensure_in_syspath('../')
__opts__ = {}
@skipIf(NO_MOCK, NO_MOCK_REASON)
class MinionTestCase(TestCase):
def test_invalid_master_address(self):
with patch.dict(__opts__, {'ipv6': False, 'master': float('127.0'), 'master_port': '4555', 'retry_dns': False}):
self.assertRaises(SaltSystemExit, minion.resolve_dns, __opts__)
if __name__ == '__main__':
from integration import run_tests
run_tests(MinionTestCase, needs_daemon=False)
| Add test for sock path length
| # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Mike Place <mp@saltstack.com>`
'''
# Import python libs
import os
# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch
# Import salt libs
from salt import minion
from salt.exceptions import SaltSystemExit
import salt.syspaths
ensure_in_syspath('../')
__opts__ = {}
@skipIf(NO_MOCK, NO_MOCK_REASON)
class MinionTestCase(TestCase):
def test_invalid_master_address(self):
with patch.dict(__opts__, {'ipv6': False, 'master': float('127.0'), 'master_port': '4555', 'retry_dns': False}):
self.assertRaises(SaltSystemExit, minion.resolve_dns, __opts__)
def test_sock_path_len(self):
'''
This tests whether or not a larger hash causes the sock path to exceed
the system's max sock path length. See the below link for more
information.
https://github.com/saltstack/salt/issues/12172#issuecomment-43903643
'''
opts = {
'id': 'salt-testing',
'hash_type': 'sha512',
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion')
}
with patch.dict(__opts__, opts):
testminion = minion.MinionBase(__opts__)
try:
testminion._prepare_minion_event_system()
result = True
except SaltSystemExit:
result = False
self.assertTrue(result)
if __name__ == '__main__':
from integration import run_tests
run_tests(MinionTestCase, needs_daemon=False)
|
from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in settings.PAYMENTS_PLANS:
if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"):
stripe.Plan.create(
amount=100 * settings.PAYMENTS_PLANS[plan]["price"],
interval=settings.PAYMENTS_PLANS[plan]["interval"],
name=settings.PAYMENTS_PLANS[plan]["name"],
currency=settings.PAYMENTS_PLANS[plan]["currency"],
id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id")
)
print "Plan created for {0}".format(plan)
| Make sure this value is always an integer | from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in settings.PAYMENTS_PLANS:
if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"):
stripe.Plan.create(
amount=int(100 * settings.PAYMENTS_PLANS[plan]["price"]),
interval=settings.PAYMENTS_PLANS[plan]["interval"],
name=settings.PAYMENTS_PLANS[plan]["name"],
currency=settings.PAYMENTS_PLANS[plan]["currency"],
id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id")
)
print "Plan created for {0}".format(plan)
|
from django.contrib.auth.models import Permission
from rest_framework import viewsets
from .serializers import PermissionSerializer
class PermissionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Permission.objects.all()
serializer_class = PermissionSerializer
| Add search functionality to permissions endpoint
| from django.contrib.auth.models import Permission
from rest_framework import viewsets
from .serializers import PermissionSerializer
class PermissionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Permission.objects.all()
serializer_class = PermissionSerializer
search_fields = ('name',)
|
"""Tests for the Caeser module"""
import pycipher
from lantern.modules import atbash
def _test_atbash(plaintext, *fitness_functions, top_n=1):
ciphertext = pycipher.Atbash().encipher(plaintext, keep_punct=True)
decryption = atbash.decrypt(ciphertext)
assert decryption == plaintext.upper()
def test_decrypt():
"""Test decryption"""
assert atbash.decrypt("uozt{Yzybolm}") == "flag{Babylon}"
def test_encrypt():
"""Test encrypt"""
assert ''.join(atbash.encrypt("flag{Babylon}")) == "uozt{Yzybolm}"
| Remove unnecessary testing code from atbash
| """Tests for the Caeser module"""
from lantern.modules import atbash
def test_decrypt():
"""Test decryption"""
assert atbash.decrypt("uozt{Yzybolm}") == "flag{Babylon}"
def test_encrypt():
"""Test encryption"""
assert ''.join(atbash.encrypt("flag{Babylon}")) == "uozt{Yzybolm}"
|
"""
These functions are written assuming the under a moto call stack.
TODO add check is a fake bucket?
"""
import boto3
def pre_load_s3_data(bucket_name, prefix, region='us-east-1'):
s3 = boto3.client('s3', region_name=region)
res = s3.create_bucket(Bucket=bucket_name)
default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name}
s3.put_object(Key=f"{prefix}/readme.txt", **default_kwargs)
s3.put_object(Key=f"{prefix}/notes.md", **default_kwargs)
# load items, 3 directories
for i, _ in enumerate(range(500)):
res = s3.put_object(Key=f"{prefix}/images/myimage{i}.tif",
**default_kwargs)
for i, _ in enumerate(range(400)):
s3.put_object(
Key=f"{prefix}/scripts/myscripts{i}.py",
**default_kwargs
)
for i, _ in enumerate(range(110)):
s3.put_object(
Key=f"{prefix}/scripts/subdir/otherscripts{i}.sh",
**default_kwargs
)
| Fix string using py3 only feature.
| """
These functions are written assuming the under a moto call stack.
TODO add check is a fake bucket?
"""
import boto3
def pre_load_s3_data(bucket_name, prefix, region='us-east-1'):
s3 = boto3.client('s3', region_name=region)
res = s3.create_bucket(Bucket=bucket_name)
default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name}
s3.put_object(Key="{}/readme.txt".format(prefix), **default_kwargs)
s3.put_object(Key="{}/notes.md".format(prefix), **default_kwargs)
# load items, 3 directories
for i, _ in enumerate(range(500)):
res = s3.put_object(Key="{}/images/myimage{i}.tif".format(prefix),
**default_kwargs)
for i, _ in enumerate(range(400)):
s3.put_object(Key="{}/scripts/myscripts{i}.py".format(prefix),
**default_kwargs)
for i, _ in enumerate(range(110)):
s3.put_object(
Key="{}/scripts/subdir/otherscripts{i}.sh".format(prefix),
**default_kwargs)
|
import helper
from rock import utils
class UtilsTestCase(helper.unittest.TestCase):
def test_shell(self):
utils.Shell.run = lambda self: self
s = utils.Shell()
self.assertTrue(isinstance(s.__enter__(), utils.Shell))
s.write('ok')
s.__exit__(None, None, None)
self.assertEqual(s.stdin.getvalue(), 'ok\n')
def execl(*args):
self.assertEqual(len(args), 4)
self.assertEqual(args[0], '/bin/bash')
self.assertEqual(args[1], '-l')
self.assertEqual(args[2], '-c')
self.assertEqual(args[3], 'ok\n')
utils.os.execl = execl
s.__exit__('type', 'value', 'tracebook')
| Test isexecutable check in utils.Shell
| import helper
from rock import utils
from rock.exceptions import ConfigError
class UtilsTestCase(helper.unittest.TestCase):
def test_shell(self):
utils.Shell.run = lambda self: self
s = utils.Shell()
self.assertTrue(isinstance(s.__enter__(), utils.Shell))
s.write('ok')
s.__exit__(None, None, None)
self.assertEqual(s.stdin.getvalue(), 'ok\n')
def execl(*args):
self.assertEqual(len(args), 4)
self.assertEqual(args[0], '/bin/bash')
self.assertEqual(args[1], '-l')
self.assertEqual(args[2], '-c')
self.assertEqual(args[3], 'ok\n')
utils.os.execl = execl
s.__exit__('type', 'value', 'tracebook')
def test_noshell(self):
utils.ROCK_SHELL = '/tmp/hopefully-no-exists'
s = utils.Shell()
s.__enter__()
self.assertRaises(ConfigError, s.__exit__, 'type', 'value', 'tracebook')
|
"""
Copyright [2009-2014] EMBL-European Bioinformatics Institute
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.
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.',
'NAME': '',
'USER': '',
'PASSWORD': '',
'OPTIONS' : { 'init_command' : 'SET storage_engine=MyISAM', },
}
}
TEMPLATE_DIRS = (
'',
)
STATIC_ROOT = ''
EMAIL_HOST = ''
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT =
EMAIL_USE_TLS = True
EMAIL_RNACENTRAL_HELPDESK = ''
SECRET_KEY = ''
ADMINS = (
('', ''),
)
COMPRESS_ENABLED =
DEBUG =
ALLOWED_HOSTS = []
# django-debug-toolbar
INTERNAL_IPS = ('127.0.0.1',)
| Update the default settings file to include the database threaded option
| """
Copyright [2009-2014] EMBL-European Bioinformatics Institute
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.
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=)(PORT=))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=)))',
'USER': '',
'PASSWORD': '',
'OPTIONS': {
'threaded': True,
},
}
}
TEMPLATE_DIRS = (
'',
)
STATIC_ROOT = ''
EMAIL_HOST = ''
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT =
EMAIL_USE_TLS = True
EMAIL_RNACENTRAL_HELPDESK = ''
SECRET_KEY = ''
ADMINS = (
('', ''),
)
COMPRESS_ENABLED = False
DEBUG = False
ALLOWED_HOSTS = []
# django-debug-toolbar
INTERNAL_IPS = ('127.0.0.1',)
# django-maintenance
MAINTENANCE_MODE = False
|
# encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Email',
fields=[
(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True)),
('from_email', models.TextField(verbose_name=u'from e-mail')),
('recipients', models.TextField(verbose_name=u'recipients')),
('subject', models.TextField(verbose_name=u'subject')),
('body', models.TextField(verbose_name=u'body')),
('ok', models.BooleanField(default=False, db_index=True, verbose_name=u'ok')),
('date_sent', models.DateTimeField(auto_now_add=True, verbose_name=u'date sent', db_index=True)),
],
options={
u'ordering': (u'-date_sent',),
u'verbose_name': u'e-mail',
u'verbose_name_plural': u'e-mails',
},
bases=(models.Model,),
),
]
| Fix migration file for Python 3.2 (and PEP8)
| # encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Email',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False,
auto_created=True, primary_key=True)),
('from_email', models.TextField(verbose_name='from e-mail')),
('recipients', models.TextField(verbose_name='recipients')),
('subject', models.TextField(verbose_name='subject')),
('body', models.TextField(verbose_name='body')),
('ok', models.BooleanField(default=False, db_index=True,
verbose_name='ok')),
('date_sent', models.DateTimeField(auto_now_add=True,
verbose_name='date sent',
db_index=True)),
],
options={
'ordering': ('-date_sent',),
'verbose_name': 'e-mail',
'verbose_name_plural': 'e-mails',
},
bases=(models.Model,),
),
]
|
#!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'wagtailgeowidget': {
'handlers': ['console'],
'level': 'ERROR',
'propagate': True,
},
},
},
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sites',
'wagtail.core',
'wagtail.sites',
'wagtail.users',
'wagtail.images',
'taggit',
'wagtailgeowidget',
"tests",
],
MIDDLEWARE_CLASSES=[],
ROOT_URLCONF='tests.urls',
)
settings.configure(**params)
def runtests():
argv = sys.argv[:1] + ["test"] + sys.argv[1:]
execute_from_command_line(argv)
if __name__ == "__main__":
runtests()
| Add missing config that caused test to fail
| #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'wagtailgeowidget': {
'handlers': ['console'],
'level': 'ERROR',
'propagate': True,
},
},
},
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sites',
'wagtail.core',
"wagtail.admin",
'wagtail.sites',
'wagtail.users',
'wagtail.images',
'taggit',
'wagtailgeowidget',
"tests",
],
MIDDLEWARE_CLASSES=[],
ROOT_URLCONF='tests.urls',
SECRET_KEY="secret key",
)
settings.configure(**params)
def runtests():
argv = sys.argv[:1] + ["test"] + sys.argv[1:]
execute_from_command_line(argv)
if __name__ == "__main__":
runtests()
|
from parglare import Grammar
grammar = Grammar.from_string("""
start: ab EOF;
ab: "a" ab "b" | EMPTY;
""")
start_symbol = 'start'
| Remove `EOF` -- update examples
refs #64
| from parglare import Grammar
grammar = Grammar.from_string("""
start: ab;
ab: "a" ab "b" | EMPTY;
""")
start_symbol = 'start'
|
from cellulario import iocell
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
iocell.DEBUG = True
| Remove uvloop from test run.
| from cellulario import iocell
iocell.DEBUG = True
|
from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties | Add possibilty to get ResultMessage | from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
self.ResultMessage = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties
|
# -*- coding:utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
import boto.swf
from . import settings
SETTINGS = settings.get()
class ConnectedSWFObject(object):
"""Authenticated object interface
Provides the instance attributes:
- `region`: name of the AWS region
- `connection`: to the SWF endpoint (`boto.swf.layer1.Layer1` object):
"""
__slots__ = [
'region',
'connection'
]
def __init__(self, *args, **kwargs):
settings_ = {k: v for k, v in SETTINGS.iteritems()}
settings_.update(kwargs)
self.region = (settings_.pop('region') or
boto.swf.layer1.Layer1.DefaultRegionName)
self.connection = boto.swf.connect_to_region(self.region, **settings_)
if self.connection is None:
raise ValueError('invalid region: {}'.format(self.region))
| Fix ConnectedSWFObject: pass default value to pop()
| # -*- coding:utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
import boto.swf
from . import settings
SETTINGS = settings.get()
class ConnectedSWFObject(object):
"""Authenticated object interface
Provides the instance attributes:
- `region`: name of the AWS region
- `connection`: to the SWF endpoint (`boto.swf.layer1.Layer1` object):
"""
__slots__ = [
'region',
'connection'
]
def __init__(self, *args, **kwargs):
settings_ = {k: v for k, v in SETTINGS.iteritems()}
settings_.update(kwargs)
self.region = (settings_.pop('region', None) or
boto.swf.layer1.Layer1.DefaultRegionName)
self.connection = boto.swf.connect_to_region(self.region, **settings_)
if self.connection is None:
raise ValueError('invalid region: {}'.format(self.region))
|
import random
class IconLayout:
def __init__(self, width, height):
self._icons = []
self._width = width
self._height = height
def add_icon(self, icon):
self._icons.append(icon)
self._layout_icon(icon)
def remove_icon(self, icon):
self._icons.remove(icon)
def _is_valid_position(self, icon, x, y):
icon_size = icon.props.size
border = 20
if not (border < x < self._width - icon_size - border and \
border < y < self._height - icon_size - border):
return False
return True
def _layout_icon(self, icon):
while True:
x = random.random() * self._width
y = random.random() * self._height
if self._is_valid_position(icon, x, y):
break
icon.props.x = x
icon.props.y = y
| Use get/set_property rather than direct accessors
| import random
class IconLayout:
def __init__(self, width, height):
self._icons = []
self._width = width
self._height = height
def add_icon(self, icon):
self._icons.append(icon)
self._layout_icon(icon)
def remove_icon(self, icon):
self._icons.remove(icon)
def _is_valid_position(self, icon, x, y):
icon_size = icon.get_property('size')
border = 20
if not (border < x < self._width - icon_size - border and \
border < y < self._height - icon_size - border):
return False
return True
def _layout_icon(self, icon):
while True:
x = random.random() * self._width
y = random.random() * self._height
if self._is_valid_position(icon, x, y):
break
icon.set_property('x', x)
icon.set_property('y', y)
|