commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 0
2.94k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
444
| message
stringlengths 16
3.45k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43.2k
| prompt
stringlengths 17
4.58k
| response
stringlengths 1
4.43k
| prompt_tagged
stringlengths 58
4.62k
| response_tagged
stringlengths 1
4.43k
| text
stringlengths 132
7.29k
| text_tagged
stringlengths 173
7.33k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
65574a215e60811bb023edf3cc6a7bfb6ff201a1
|
tiddlywebwiki/manage.py
|
tiddlywebwiki/manage.py
|
"""
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all instance_tiddlers in the current instance."""
from tiddlywebplugins.instancer import Instance
instance = Instance('.', config)
instance.update_store()
@make_command()
def twimport(args):
"""Import one or more plugins, tiddlers or recipes in Cook format: <bag> <URI>"""
bag = args[0]
urls = args[1:]
if not bag or not urls:
raise IndexError('missing args')
import_list(bag, urls, config)
@make_command()
def imwiki(args):
"""Import tiddlers from a Tiddlywiki document into a bag: <bag> <filename>"""
store = _store()
try:
bag_name, filename = args[0:2]
import_wiki_file(store, filename, bag_name)
except IndexError, exc:
usage("index error: %s" % exc)
except ValueError, exc:
usage("value error: %s" % exc)
def _store():
"""Get our Store from config."""
return Store(config['server_store'][0],
config['server_store'][1],
environ={'tiddlyweb.config': config})
|
"""
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all instance_tiddlers in the current instance."""
from tiddlywebplugins.instancer import Instance
instance = Instance('.', config)
instance.update_store()
@make_command()
def twimport(args):
"""Import one or more plugins, tiddlers or recipes in Cook format or a wiki: <bag> <URI>"""
bag = args[0]
urls = args[1:]
if not bag or not urls:
raise IndexError('missing args')
import_list(bag, urls, config)
@make_command()
def imwiki(args):
"""Import tiddlers from a Tiddlywiki document into a bag, deprecated in favor of twimport: <bag> <filename>"""
# XXX to be removed soon, deprecated.
store = _store()
try:
bag_name, filename = args[0:2]
import_wiki_file(store, filename, bag_name)
except IndexError, exc:
usage("index error: %s" % exc)
except ValueError, exc:
usage("value error: %s" % exc)
def _store():
"""Get our Store from config."""
return Store(config['server_store'][0],
config['server_store'][1],
environ={'tiddlyweb.config': config})
|
Update the docs on twimport and imwiki to indicate that imwiki is deprecated.
|
Update the docs on twimport and imwiki to indicate that imwiki is deprecated.
|
Python
|
bsd-3-clause
|
tiddlyweb/tiddlywebwiki,tiddlyweb/tiddlywebwiki,tiddlyweb/tiddlywebwiki
|
"""
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all instance_tiddlers in the current instance."""
from tiddlywebplugins.instancer import Instance
instance = Instance('.', config)
instance.update_store()
@make_command()
def twimport(args):
"""Import one or more plugins, tiddlers or recipes in Cook format: <bag> <URI>"""
bag = args[0]
urls = args[1:]
if not bag or not urls:
raise IndexError('missing args')
import_list(bag, urls, config)
@make_command()
def imwiki(args):
"""Import tiddlers from a Tiddlywiki document into a bag: <bag> <filename>"""
store = _store()
try:
bag_name, filename = args[0:2]
import_wiki_file(store, filename, bag_name)
except IndexError, exc:
usage("index error: %s" % exc)
except ValueError, exc:
usage("value error: %s" % exc)
def _store():
"""Get our Store from config."""
return Store(config['server_store'][0],
config['server_store'][1],
environ={'tiddlyweb.config': config})
Update the docs on twimport and imwiki to indicate that imwiki is deprecated.
|
"""
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all instance_tiddlers in the current instance."""
from tiddlywebplugins.instancer import Instance
instance = Instance('.', config)
instance.update_store()
@make_command()
def twimport(args):
"""Import one or more plugins, tiddlers or recipes in Cook format or a wiki: <bag> <URI>"""
bag = args[0]
urls = args[1:]
if not bag or not urls:
raise IndexError('missing args')
import_list(bag, urls, config)
@make_command()
def imwiki(args):
"""Import tiddlers from a Tiddlywiki document into a bag, deprecated in favor of twimport: <bag> <filename>"""
# XXX to be removed soon, deprecated.
store = _store()
try:
bag_name, filename = args[0:2]
import_wiki_file(store, filename, bag_name)
except IndexError, exc:
usage("index error: %s" % exc)
except ValueError, exc:
usage("value error: %s" % exc)
def _store():
"""Get our Store from config."""
return Store(config['server_store'][0],
config['server_store'][1],
environ={'tiddlyweb.config': config})
|
<commit_before>"""
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all instance_tiddlers in the current instance."""
from tiddlywebplugins.instancer import Instance
instance = Instance('.', config)
instance.update_store()
@make_command()
def twimport(args):
"""Import one or more plugins, tiddlers or recipes in Cook format: <bag> <URI>"""
bag = args[0]
urls = args[1:]
if not bag or not urls:
raise IndexError('missing args')
import_list(bag, urls, config)
@make_command()
def imwiki(args):
"""Import tiddlers from a Tiddlywiki document into a bag: <bag> <filename>"""
store = _store()
try:
bag_name, filename = args[0:2]
import_wiki_file(store, filename, bag_name)
except IndexError, exc:
usage("index error: %s" % exc)
except ValueError, exc:
usage("value error: %s" % exc)
def _store():
"""Get our Store from config."""
return Store(config['server_store'][0],
config['server_store'][1],
environ={'tiddlyweb.config': config})
<commit_msg>Update the docs on twimport and imwiki to indicate that imwiki is deprecated.<commit_after>
|
"""
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all instance_tiddlers in the current instance."""
from tiddlywebplugins.instancer import Instance
instance = Instance('.', config)
instance.update_store()
@make_command()
def twimport(args):
"""Import one or more plugins, tiddlers or recipes in Cook format or a wiki: <bag> <URI>"""
bag = args[0]
urls = args[1:]
if not bag or not urls:
raise IndexError('missing args')
import_list(bag, urls, config)
@make_command()
def imwiki(args):
"""Import tiddlers from a Tiddlywiki document into a bag, deprecated in favor of twimport: <bag> <filename>"""
# XXX to be removed soon, deprecated.
store = _store()
try:
bag_name, filename = args[0:2]
import_wiki_file(store, filename, bag_name)
except IndexError, exc:
usage("index error: %s" % exc)
except ValueError, exc:
usage("value error: %s" % exc)
def _store():
"""Get our Store from config."""
return Store(config['server_store'][0],
config['server_store'][1],
environ={'tiddlyweb.config': config})
|
"""
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all instance_tiddlers in the current instance."""
from tiddlywebplugins.instancer import Instance
instance = Instance('.', config)
instance.update_store()
@make_command()
def twimport(args):
"""Import one or more plugins, tiddlers or recipes in Cook format: <bag> <URI>"""
bag = args[0]
urls = args[1:]
if not bag or not urls:
raise IndexError('missing args')
import_list(bag, urls, config)
@make_command()
def imwiki(args):
"""Import tiddlers from a Tiddlywiki document into a bag: <bag> <filename>"""
store = _store()
try:
bag_name, filename = args[0:2]
import_wiki_file(store, filename, bag_name)
except IndexError, exc:
usage("index error: %s" % exc)
except ValueError, exc:
usage("value error: %s" % exc)
def _store():
"""Get our Store from config."""
return Store(config['server_store'][0],
config['server_store'][1],
environ={'tiddlyweb.config': config})
Update the docs on twimport and imwiki to indicate that imwiki is deprecated."""
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all instance_tiddlers in the current instance."""
from tiddlywebplugins.instancer import Instance
instance = Instance('.', config)
instance.update_store()
@make_command()
def twimport(args):
"""Import one or more plugins, tiddlers or recipes in Cook format or a wiki: <bag> <URI>"""
bag = args[0]
urls = args[1:]
if not bag or not urls:
raise IndexError('missing args')
import_list(bag, urls, config)
@make_command()
def imwiki(args):
"""Import tiddlers from a Tiddlywiki document into a bag, deprecated in favor of twimport: <bag> <filename>"""
# XXX to be removed soon, deprecated.
store = _store()
try:
bag_name, filename = args[0:2]
import_wiki_file(store, filename, bag_name)
except IndexError, exc:
usage("index error: %s" % exc)
except ValueError, exc:
usage("value error: %s" % exc)
def _store():
"""Get our Store from config."""
return Store(config['server_store'][0],
config['server_store'][1],
environ={'tiddlyweb.config': config})
|
<commit_before>"""
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all instance_tiddlers in the current instance."""
from tiddlywebplugins.instancer import Instance
instance = Instance('.', config)
instance.update_store()
@make_command()
def twimport(args):
"""Import one or more plugins, tiddlers or recipes in Cook format: <bag> <URI>"""
bag = args[0]
urls = args[1:]
if not bag or not urls:
raise IndexError('missing args')
import_list(bag, urls, config)
@make_command()
def imwiki(args):
"""Import tiddlers from a Tiddlywiki document into a bag: <bag> <filename>"""
store = _store()
try:
bag_name, filename = args[0:2]
import_wiki_file(store, filename, bag_name)
except IndexError, exc:
usage("index error: %s" % exc)
except ValueError, exc:
usage("value error: %s" % exc)
def _store():
"""Get our Store from config."""
return Store(config['server_store'][0],
config['server_store'][1],
environ={'tiddlyweb.config': config})
<commit_msg>Update the docs on twimport and imwiki to indicate that imwiki is deprecated.<commit_after>"""
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all instance_tiddlers in the current instance."""
from tiddlywebplugins.instancer import Instance
instance = Instance('.', config)
instance.update_store()
@make_command()
def twimport(args):
"""Import one or more plugins, tiddlers or recipes in Cook format or a wiki: <bag> <URI>"""
bag = args[0]
urls = args[1:]
if not bag or not urls:
raise IndexError('missing args')
import_list(bag, urls, config)
@make_command()
def imwiki(args):
"""Import tiddlers from a Tiddlywiki document into a bag, deprecated in favor of twimport: <bag> <filename>"""
# XXX to be removed soon, deprecated.
store = _store()
try:
bag_name, filename = args[0:2]
import_wiki_file(store, filename, bag_name)
except IndexError, exc:
usage("index error: %s" % exc)
except ValueError, exc:
usage("value error: %s" % exc)
def _store():
"""Get our Store from config."""
return Store(config['server_store'][0],
config['server_store'][1],
environ={'tiddlyweb.config': config})
|
e70f30758a501db12af4fbbfc4204e2858967c8b
|
conllu/compat.py
|
conllu/compat.py
|
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(pattern, *args):
if not pattern.endswith("$"):
pattern += "$"
return match(pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args)
return match(regex.pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
Make fullmatch work on python 2.7.
|
Bug: Make fullmatch work on python 2.7.
|
Python
|
mit
|
EmilStenstrom/conllu
|
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(pattern, *args):
if not pattern.endswith("$"):
pattern += "$"
return match(pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
Bug: Make fullmatch work on python 2.7.
|
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args)
return match(regex.pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
<commit_before>try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(pattern, *args):
if not pattern.endswith("$"):
pattern += "$"
return match(pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
<commit_msg>Bug: Make fullmatch work on python 2.7.<commit_after>
|
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args)
return match(regex.pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(pattern, *args):
if not pattern.endswith("$"):
pattern += "$"
return match(pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
Bug: Make fullmatch work on python 2.7.try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args)
return match(regex.pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
<commit_before>try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(pattern, *args):
if not pattern.endswith("$"):
pattern += "$"
return match(pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
<commit_msg>Bug: Make fullmatch work on python 2.7.<commit_after>try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(string)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args)
return match(regex.pattern, *args)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
e12e40ea368dc9027e63474c45b43da42accaf67
|
pyconcz_2016/settings_dev.py
|
pyconcz_2016/settings_dev.py
|
from .settings import *
DEBUG = True
SECRET_KEY = 42
INTERNAL_IPS = ['127.0.0.1']
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
WEBPACK_LOADER['DEFAULT']['STATS_FILE'] = (
os.path.join(BASE_DIR, 'static_build', 'webpack-stats-dev.json'))
|
from .settings import *
DEBUG = True
SECRET_KEY = 42
INTERNAL_IPS = ['127.0.0.1']
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
WEBPACK_STATS = os.path.join(BASE_DIR, 'static_build', 'webpack-stats-dev.json')
if os.path.exists(WEBPACK_STATS):
WEBPACK_LOADER['DEFAULT']['STATS_FILE'] = WEBPACK_STATS
else:
print("If you're editing frontend files, plase run `npm start` "
"and restart Django.")
|
Allow local development without running webpack
|
Allow local development without running webpack
|
Python
|
mit
|
benabraham/cz.pycon.org-2017,benabraham/cz.pycon.org-2017,pyvec/cz.pycon.org-2016,pyvec/cz.pycon.org-2016,pyvec/cz.pycon.org-2017,benabraham/cz.pycon.org-2017,pyvec/cz.pycon.org-2017,pyvec/cz.pycon.org-2016,pyvec/cz.pycon.org-2017
|
from .settings import *
DEBUG = True
SECRET_KEY = 42
INTERNAL_IPS = ['127.0.0.1']
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
WEBPACK_LOADER['DEFAULT']['STATS_FILE'] = (
os.path.join(BASE_DIR, 'static_build', 'webpack-stats-dev.json'))
Allow local development without running webpack
|
from .settings import *
DEBUG = True
SECRET_KEY = 42
INTERNAL_IPS = ['127.0.0.1']
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
WEBPACK_STATS = os.path.join(BASE_DIR, 'static_build', 'webpack-stats-dev.json')
if os.path.exists(WEBPACK_STATS):
WEBPACK_LOADER['DEFAULT']['STATS_FILE'] = WEBPACK_STATS
else:
print("If you're editing frontend files, plase run `npm start` "
"and restart Django.")
|
<commit_before>from .settings import *
DEBUG = True
SECRET_KEY = 42
INTERNAL_IPS = ['127.0.0.1']
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
WEBPACK_LOADER['DEFAULT']['STATS_FILE'] = (
os.path.join(BASE_DIR, 'static_build', 'webpack-stats-dev.json'))
<commit_msg>Allow local development without running webpack<commit_after>
|
from .settings import *
DEBUG = True
SECRET_KEY = 42
INTERNAL_IPS = ['127.0.0.1']
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
WEBPACK_STATS = os.path.join(BASE_DIR, 'static_build', 'webpack-stats-dev.json')
if os.path.exists(WEBPACK_STATS):
WEBPACK_LOADER['DEFAULT']['STATS_FILE'] = WEBPACK_STATS
else:
print("If you're editing frontend files, plase run `npm start` "
"and restart Django.")
|
from .settings import *
DEBUG = True
SECRET_KEY = 42
INTERNAL_IPS = ['127.0.0.1']
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
WEBPACK_LOADER['DEFAULT']['STATS_FILE'] = (
os.path.join(BASE_DIR, 'static_build', 'webpack-stats-dev.json'))
Allow local development without running webpackfrom .settings import *
DEBUG = True
SECRET_KEY = 42
INTERNAL_IPS = ['127.0.0.1']
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
WEBPACK_STATS = os.path.join(BASE_DIR, 'static_build', 'webpack-stats-dev.json')
if os.path.exists(WEBPACK_STATS):
WEBPACK_LOADER['DEFAULT']['STATS_FILE'] = WEBPACK_STATS
else:
print("If you're editing frontend files, plase run `npm start` "
"and restart Django.")
|
<commit_before>from .settings import *
DEBUG = True
SECRET_KEY = 42
INTERNAL_IPS = ['127.0.0.1']
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
WEBPACK_LOADER['DEFAULT']['STATS_FILE'] = (
os.path.join(BASE_DIR, 'static_build', 'webpack-stats-dev.json'))
<commit_msg>Allow local development without running webpack<commit_after>from .settings import *
DEBUG = True
SECRET_KEY = 42
INTERNAL_IPS = ['127.0.0.1']
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
WEBPACK_STATS = os.path.join(BASE_DIR, 'static_build', 'webpack-stats-dev.json')
if os.path.exists(WEBPACK_STATS):
WEBPACK_LOADER['DEFAULT']['STATS_FILE'] = WEBPACK_STATS
else:
print("If you're editing frontend files, plase run `npm start` "
"and restart Django.")
|
56e45a5146cfcde797be5cb8d3c52a1fbf874d88
|
user_clipboard/forms.py
|
user_clipboard/forms.py
|
from django import forms
from .models import Clipboard
class ClipboardFileForm(forms.ModelForm):
class Meta:
model = Clipboard
fields = ('file',)
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._meta.model.objects.get(pk=self.instance.pk)
old_instance.file.delete(save=False)
return super(ClipboardFileForm, self).save(commit=commit)
class ClipboardImageForm(ClipboardFileForm):
file = forms.ImageField()
|
from django import forms
from .models import Clipboard
class BaseClipboardForm(object):
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._meta.model.objects.get(pk=self.instance.pk)
old_instance.file.delete(save=False)
return super(BaseClipboardForm, self).save(commit=commit)
class ClipboardFileForm(BaseClipboardForm, forms.ModelForm):
class Meta:
model = Clipboard
fields = ('file',)
class ClipboardImageForm(ClipboardFileForm):
file = forms.ImageField()
|
Create BaseClipboardForm for easy extending if needed
|
Create BaseClipboardForm for easy extending if needed
|
Python
|
mit
|
IndustriaTech/django-user-clipboard,MagicSolutions/django-user-clipboard,IndustriaTech/django-user-clipboard,MagicSolutions/django-user-clipboard
|
from django import forms
from .models import Clipboard
class ClipboardFileForm(forms.ModelForm):
class Meta:
model = Clipboard
fields = ('file',)
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._meta.model.objects.get(pk=self.instance.pk)
old_instance.file.delete(save=False)
return super(ClipboardFileForm, self).save(commit=commit)
class ClipboardImageForm(ClipboardFileForm):
file = forms.ImageField()
Create BaseClipboardForm for easy extending if needed
|
from django import forms
from .models import Clipboard
class BaseClipboardForm(object):
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._meta.model.objects.get(pk=self.instance.pk)
old_instance.file.delete(save=False)
return super(BaseClipboardForm, self).save(commit=commit)
class ClipboardFileForm(BaseClipboardForm, forms.ModelForm):
class Meta:
model = Clipboard
fields = ('file',)
class ClipboardImageForm(ClipboardFileForm):
file = forms.ImageField()
|
<commit_before>from django import forms
from .models import Clipboard
class ClipboardFileForm(forms.ModelForm):
class Meta:
model = Clipboard
fields = ('file',)
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._meta.model.objects.get(pk=self.instance.pk)
old_instance.file.delete(save=False)
return super(ClipboardFileForm, self).save(commit=commit)
class ClipboardImageForm(ClipboardFileForm):
file = forms.ImageField()
<commit_msg>Create BaseClipboardForm for easy extending if needed<commit_after>
|
from django import forms
from .models import Clipboard
class BaseClipboardForm(object):
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._meta.model.objects.get(pk=self.instance.pk)
old_instance.file.delete(save=False)
return super(BaseClipboardForm, self).save(commit=commit)
class ClipboardFileForm(BaseClipboardForm, forms.ModelForm):
class Meta:
model = Clipboard
fields = ('file',)
class ClipboardImageForm(ClipboardFileForm):
file = forms.ImageField()
|
from django import forms
from .models import Clipboard
class ClipboardFileForm(forms.ModelForm):
class Meta:
model = Clipboard
fields = ('file',)
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._meta.model.objects.get(pk=self.instance.pk)
old_instance.file.delete(save=False)
return super(ClipboardFileForm, self).save(commit=commit)
class ClipboardImageForm(ClipboardFileForm):
file = forms.ImageField()
Create BaseClipboardForm for easy extending if neededfrom django import forms
from .models import Clipboard
class BaseClipboardForm(object):
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._meta.model.objects.get(pk=self.instance.pk)
old_instance.file.delete(save=False)
return super(BaseClipboardForm, self).save(commit=commit)
class ClipboardFileForm(BaseClipboardForm, forms.ModelForm):
class Meta:
model = Clipboard
fields = ('file',)
class ClipboardImageForm(ClipboardFileForm):
file = forms.ImageField()
|
<commit_before>from django import forms
from .models import Clipboard
class ClipboardFileForm(forms.ModelForm):
class Meta:
model = Clipboard
fields = ('file',)
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._meta.model.objects.get(pk=self.instance.pk)
old_instance.file.delete(save=False)
return super(ClipboardFileForm, self).save(commit=commit)
class ClipboardImageForm(ClipboardFileForm):
file = forms.ImageField()
<commit_msg>Create BaseClipboardForm for easy extending if needed<commit_after>from django import forms
from .models import Clipboard
class BaseClipboardForm(object):
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._meta.model.objects.get(pk=self.instance.pk)
old_instance.file.delete(save=False)
return super(BaseClipboardForm, self).save(commit=commit)
class ClipboardFileForm(BaseClipboardForm, forms.ModelForm):
class Meta:
model = Clipboard
fields = ('file',)
class ClipboardImageForm(ClipboardFileForm):
file = forms.ImageField()
|
e05ea934335eac29c0b2f164eab600008546324c
|
recurring_contract/migrations/1.2/post-migration.py
|
recurring_contract/migrations/1.2/post-migration.py
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
import sys
def migrate(cr, version):
reload(sys)
sys.setdefaultencoding('UTF8')
if not version:
return
delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4,
'quarterly': 3, 'bimonthly': 2, 'monthly': 1}
cr.execute(
'''
SELECT id, advance_billing FROM recurring_contract_group
'''
)
contract_groups = cr.fetchall()
for contract_group in contract_groups:
delay = delay_dict[contract_group[1]] or 1
cr.execute(
'''
UPDATE recurring_contract_group
SET recurring_value = {0}, advance_billing_months = {0}
WHERE id = {1}
'''.format(delay, contract_group[0])
)
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
import sys
def migrate(cr, version):
reload(sys)
sys.setdefaultencoding('UTF8')
if not version:
return
delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4,
'quarterly': 3, 'bimonthly': 2, 'monthly': 1}
cr.execute(
'''
SELECT id, advance_billing FROM recurring_contract_group
'''
)
contract_groups = cr.fetchall()
for contract_group in contract_groups:
delay = delay_dict[contract_group[1]] or 1
cr.execute(
'''
UPDATE recurring_contract_group
SET advance_billing_months = {0}
WHERE id = {1}
'''.format(delay, contract_group[0])
)
|
Remove wrong migration of contracts.
|
Remove wrong migration of contracts.
|
Python
|
agpl-3.0
|
CompassionCH/compassion-accounting,ndtran/compassion-accounting,ndtran/compassion-accounting,ecino/compassion-accounting,ecino/compassion-accounting,CompassionCH/compassion-accounting,ndtran/compassion-accounting
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
import sys
def migrate(cr, version):
reload(sys)
sys.setdefaultencoding('UTF8')
if not version:
return
delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4,
'quarterly': 3, 'bimonthly': 2, 'monthly': 1}
cr.execute(
'''
SELECT id, advance_billing FROM recurring_contract_group
'''
)
contract_groups = cr.fetchall()
for contract_group in contract_groups:
delay = delay_dict[contract_group[1]] or 1
cr.execute(
'''
UPDATE recurring_contract_group
SET recurring_value = {0}, advance_billing_months = {0}
WHERE id = {1}
'''.format(delay, contract_group[0])
)
Remove wrong migration of contracts.
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
import sys
def migrate(cr, version):
reload(sys)
sys.setdefaultencoding('UTF8')
if not version:
return
delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4,
'quarterly': 3, 'bimonthly': 2, 'monthly': 1}
cr.execute(
'''
SELECT id, advance_billing FROM recurring_contract_group
'''
)
contract_groups = cr.fetchall()
for contract_group in contract_groups:
delay = delay_dict[contract_group[1]] or 1
cr.execute(
'''
UPDATE recurring_contract_group
SET advance_billing_months = {0}
WHERE id = {1}
'''.format(delay, contract_group[0])
)
|
<commit_before># -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
import sys
def migrate(cr, version):
reload(sys)
sys.setdefaultencoding('UTF8')
if not version:
return
delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4,
'quarterly': 3, 'bimonthly': 2, 'monthly': 1}
cr.execute(
'''
SELECT id, advance_billing FROM recurring_contract_group
'''
)
contract_groups = cr.fetchall()
for contract_group in contract_groups:
delay = delay_dict[contract_group[1]] or 1
cr.execute(
'''
UPDATE recurring_contract_group
SET recurring_value = {0}, advance_billing_months = {0}
WHERE id = {1}
'''.format(delay, contract_group[0])
)
<commit_msg>Remove wrong migration of contracts.<commit_after>
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
import sys
def migrate(cr, version):
reload(sys)
sys.setdefaultencoding('UTF8')
if not version:
return
delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4,
'quarterly': 3, 'bimonthly': 2, 'monthly': 1}
cr.execute(
'''
SELECT id, advance_billing FROM recurring_contract_group
'''
)
contract_groups = cr.fetchall()
for contract_group in contract_groups:
delay = delay_dict[contract_group[1]] or 1
cr.execute(
'''
UPDATE recurring_contract_group
SET advance_billing_months = {0}
WHERE id = {1}
'''.format(delay, contract_group[0])
)
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
import sys
def migrate(cr, version):
reload(sys)
sys.setdefaultencoding('UTF8')
if not version:
return
delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4,
'quarterly': 3, 'bimonthly': 2, 'monthly': 1}
cr.execute(
'''
SELECT id, advance_billing FROM recurring_contract_group
'''
)
contract_groups = cr.fetchall()
for contract_group in contract_groups:
delay = delay_dict[contract_group[1]] or 1
cr.execute(
'''
UPDATE recurring_contract_group
SET recurring_value = {0}, advance_billing_months = {0}
WHERE id = {1}
'''.format(delay, contract_group[0])
)
Remove wrong migration of contracts.# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
import sys
def migrate(cr, version):
reload(sys)
sys.setdefaultencoding('UTF8')
if not version:
return
delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4,
'quarterly': 3, 'bimonthly': 2, 'monthly': 1}
cr.execute(
'''
SELECT id, advance_billing FROM recurring_contract_group
'''
)
contract_groups = cr.fetchall()
for contract_group in contract_groups:
delay = delay_dict[contract_group[1]] or 1
cr.execute(
'''
UPDATE recurring_contract_group
SET advance_billing_months = {0}
WHERE id = {1}
'''.format(delay, contract_group[0])
)
|
<commit_before># -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
import sys
def migrate(cr, version):
reload(sys)
sys.setdefaultencoding('UTF8')
if not version:
return
delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4,
'quarterly': 3, 'bimonthly': 2, 'monthly': 1}
cr.execute(
'''
SELECT id, advance_billing FROM recurring_contract_group
'''
)
contract_groups = cr.fetchall()
for contract_group in contract_groups:
delay = delay_dict[contract_group[1]] or 1
cr.execute(
'''
UPDATE recurring_contract_group
SET recurring_value = {0}, advance_billing_months = {0}
WHERE id = {1}
'''.format(delay, contract_group[0])
)
<commit_msg>Remove wrong migration of contracts.<commit_after># -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
import sys
def migrate(cr, version):
reload(sys)
sys.setdefaultencoding('UTF8')
if not version:
return
delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4,
'quarterly': 3, 'bimonthly': 2, 'monthly': 1}
cr.execute(
'''
SELECT id, advance_billing FROM recurring_contract_group
'''
)
contract_groups = cr.fetchall()
for contract_group in contract_groups:
delay = delay_dict[contract_group[1]] or 1
cr.execute(
'''
UPDATE recurring_contract_group
SET advance_billing_months = {0}
WHERE id = {1}
'''.format(delay, contract_group[0])
)
|
d1d66c37419a85a4258f37201261d76a8f6a9e03
|
ckeditor/fields.py
|
ckeditor/fields.py
|
from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'form_class': RichTextFormField,
'config_name': self.config_name,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults)
class RichTextFormField(forms.fields.Field):
def __init__(self, config_name='default', *args, **kwargs):
kwargs.update({'widget': CKEditorWidget(config_name=config_name)})
super(RichTextFormField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^ckeditor\.fields\.RichTextField"])
except:
pass
|
from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'form_class': RichTextFormField,
'config_name': self.config_name,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults)
class RichTextFormField(forms.fields.Field):
def __init__(self,config_name ='default', max_length = None, *args, **kwargs):
kwargs.update({'widget': CKEditorWidget(config_name=config_name)})
super(RichTextFormField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^ckeditor\.fields\.RichTextField"])
except:
pass
|
Fix Function RichTextFormField now received a new parameter max_lenght for django 1.7
|
Fix Function RichTextFormField now received a new parameter max_lenght for django 1.7
|
Python
|
bsd-3-clause
|
gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3
|
from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'form_class': RichTextFormField,
'config_name': self.config_name,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults)
class RichTextFormField(forms.fields.Field):
def __init__(self, config_name='default', *args, **kwargs):
kwargs.update({'widget': CKEditorWidget(config_name=config_name)})
super(RichTextFormField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^ckeditor\.fields\.RichTextField"])
except:
pass
Fix Function RichTextFormField now received a new parameter max_lenght for django 1.7
|
from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'form_class': RichTextFormField,
'config_name': self.config_name,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults)
class RichTextFormField(forms.fields.Field):
def __init__(self,config_name ='default', max_length = None, *args, **kwargs):
kwargs.update({'widget': CKEditorWidget(config_name=config_name)})
super(RichTextFormField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^ckeditor\.fields\.RichTextField"])
except:
pass
|
<commit_before>from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'form_class': RichTextFormField,
'config_name': self.config_name,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults)
class RichTextFormField(forms.fields.Field):
def __init__(self, config_name='default', *args, **kwargs):
kwargs.update({'widget': CKEditorWidget(config_name=config_name)})
super(RichTextFormField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^ckeditor\.fields\.RichTextField"])
except:
pass
<commit_msg>Fix Function RichTextFormField now received a new parameter max_lenght for django 1.7<commit_after>
|
from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'form_class': RichTextFormField,
'config_name': self.config_name,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults)
class RichTextFormField(forms.fields.Field):
def __init__(self,config_name ='default', max_length = None, *args, **kwargs):
kwargs.update({'widget': CKEditorWidget(config_name=config_name)})
super(RichTextFormField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^ckeditor\.fields\.RichTextField"])
except:
pass
|
from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'form_class': RichTextFormField,
'config_name': self.config_name,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults)
class RichTextFormField(forms.fields.Field):
def __init__(self, config_name='default', *args, **kwargs):
kwargs.update({'widget': CKEditorWidget(config_name=config_name)})
super(RichTextFormField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^ckeditor\.fields\.RichTextField"])
except:
pass
Fix Function RichTextFormField now received a new parameter max_lenght for django 1.7from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'form_class': RichTextFormField,
'config_name': self.config_name,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults)
class RichTextFormField(forms.fields.Field):
def __init__(self,config_name ='default', max_length = None, *args, **kwargs):
kwargs.update({'widget': CKEditorWidget(config_name=config_name)})
super(RichTextFormField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^ckeditor\.fields\.RichTextField"])
except:
pass
|
<commit_before>from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'form_class': RichTextFormField,
'config_name': self.config_name,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults)
class RichTextFormField(forms.fields.Field):
def __init__(self, config_name='default', *args, **kwargs):
kwargs.update({'widget': CKEditorWidget(config_name=config_name)})
super(RichTextFormField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^ckeditor\.fields\.RichTextField"])
except:
pass
<commit_msg>Fix Function RichTextFormField now received a new parameter max_lenght for django 1.7<commit_after>from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'form_class': RichTextFormField,
'config_name': self.config_name,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults)
class RichTextFormField(forms.fields.Field):
def __init__(self,config_name ='default', max_length = None, *args, **kwargs):
kwargs.update({'widget': CKEditorWidget(config_name=config_name)})
super(RichTextFormField, self).__init__(*args, **kwargs)
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^ckeditor\.fields\.RichTextField"])
except:
pass
|
b72c9a26c00ca31966be3ae8b529e9272d300290
|
__main__.py
|
__main__.py
|
import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
self.single = sys.stdin.isatty() or args.print
def displayhook(self, value):
self.args.print and print(value)
return super().displayhook(value)
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=self.single)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>', single=self.single)
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--print', action='store_true', help='when compiling, make the top-level code print its evaluation result in addition to returning it (does not affect REPL)')
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
|
import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=True)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>')
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
|
Remove the -p command-line option.
|
Remove the -p command-line option.
It's pretty useless anyway. Use instead.
|
Python
|
mit
|
pyos/dg
|
import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
self.single = sys.stdin.isatty() or args.print
def displayhook(self, value):
self.args.print and print(value)
return super().displayhook(value)
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=self.single)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>', single=self.single)
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--print', action='store_true', help='when compiling, make the top-level code print its evaluation result in addition to returning it (does not affect REPL)')
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
Remove the -p command-line option.
It's pretty useless anyway. Use instead.
|
import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=True)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>')
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
|
<commit_before>import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
self.single = sys.stdin.isatty() or args.print
def displayhook(self, value):
self.args.print and print(value)
return super().displayhook(value)
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=self.single)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>', single=self.single)
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--print', action='store_true', help='when compiling, make the top-level code print its evaluation result in addition to returning it (does not affect REPL)')
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
<commit_msg>Remove the -p command-line option.
It's pretty useless anyway. Use instead.<commit_after>
|
import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=True)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>')
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
|
import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
self.single = sys.stdin.isatty() or args.print
def displayhook(self, value):
self.args.print and print(value)
return super().displayhook(value)
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=self.single)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>', single=self.single)
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--print', action='store_true', help='when compiling, make the top-level code print its evaluation result in addition to returning it (does not affect REPL)')
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
Remove the -p command-line option.
It's pretty useless anyway. Use instead.import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=True)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>')
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
|
<commit_before>import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
self.single = sys.stdin.isatty() or args.print
def displayhook(self, value):
self.args.print and print(value)
return super().displayhook(value)
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=self.single)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>', single=self.single)
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--print', action='store_true', help='when compiling, make the top-level code print its evaluation result in addition to returning it (does not affect REPL)')
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
<commit_msg>Remove the -p command-line option.
It's pretty useless anyway. Use instead.<commit_after>import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=True)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>')
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
|
5d8a37cdbd41af594f03d78092b78a22afc53c05
|
__main__.py
|
__main__.py
|
#!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, help='GitHub user handle')
parser.add_argument('-f', '--format', choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt'],
help='File output format.')
def main():
args = parser.parse_args()
user, format_ = args.user, args.format
return serve_content(get_data(user), user, format_)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, nargs='+', help='GitHub user handle')
parser.add_argument('-f', '--format', nargs='+',
choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt', 'all'],
help='File output format.')
def main():
args = parser.parse_args()
user = args.user
format_ = ['json', 'csv', 'md', 'raw.txt', 'tbl.txt'] if 'all' in args.format else args.format
for u in user:
print('Preparing data for {}...'.format(u))
d = get_data(u)
for f in format_:
if f is not None:
print(' Writing {}...'.format(f), end='')
serve_content(d, u, f)
print(' Done!')
else:
serve_content(d, u, f)
print('Complete!')
return None
if __name__ == '__main__':
main()
|
Add support for multiple users, format types
|
Add support for multiple users, format types
|
Python
|
mit
|
kshvmdn/github-list,kshvmdn/github-list,kshvmdn/github-list
|
#!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, help='GitHub user handle')
parser.add_argument('-f', '--format', choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt'],
help='File output format.')
def main():
args = parser.parse_args()
user, format_ = args.user, args.format
return serve_content(get_data(user), user, format_)
if __name__ == '__main__':
main()
Add support for multiple users, format types
|
#!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, nargs='+', help='GitHub user handle')
parser.add_argument('-f', '--format', nargs='+',
choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt', 'all'],
help='File output format.')
def main():
args = parser.parse_args()
user = args.user
format_ = ['json', 'csv', 'md', 'raw.txt', 'tbl.txt'] if 'all' in args.format else args.format
for u in user:
print('Preparing data for {}...'.format(u))
d = get_data(u)
for f in format_:
if f is not None:
print(' Writing {}...'.format(f), end='')
serve_content(d, u, f)
print(' Done!')
else:
serve_content(d, u, f)
print('Complete!')
return None
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, help='GitHub user handle')
parser.add_argument('-f', '--format', choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt'],
help='File output format.')
def main():
args = parser.parse_args()
user, format_ = args.user, args.format
return serve_content(get_data(user), user, format_)
if __name__ == '__main__':
main()
<commit_msg>Add support for multiple users, format types<commit_after>
|
#!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, nargs='+', help='GitHub user handle')
parser.add_argument('-f', '--format', nargs='+',
choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt', 'all'],
help='File output format.')
def main():
args = parser.parse_args()
user = args.user
format_ = ['json', 'csv', 'md', 'raw.txt', 'tbl.txt'] if 'all' in args.format else args.format
for u in user:
print('Preparing data for {}...'.format(u))
d = get_data(u)
for f in format_:
if f is not None:
print(' Writing {}...'.format(f), end='')
serve_content(d, u, f)
print(' Done!')
else:
serve_content(d, u, f)
print('Complete!')
return None
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, help='GitHub user handle')
parser.add_argument('-f', '--format', choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt'],
help='File output format.')
def main():
args = parser.parse_args()
user, format_ = args.user, args.format
return serve_content(get_data(user), user, format_)
if __name__ == '__main__':
main()
Add support for multiple users, format types#!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, nargs='+', help='GitHub user handle')
parser.add_argument('-f', '--format', nargs='+',
choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt', 'all'],
help='File output format.')
def main():
args = parser.parse_args()
user = args.user
format_ = ['json', 'csv', 'md', 'raw.txt', 'tbl.txt'] if 'all' in args.format else args.format
for u in user:
print('Preparing data for {}...'.format(u))
d = get_data(u)
for f in format_:
if f is not None:
print(' Writing {}...'.format(f), end='')
serve_content(d, u, f)
print(' Done!')
else:
serve_content(d, u, f)
print('Complete!')
return None
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, help='GitHub user handle')
parser.add_argument('-f', '--format', choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt'],
help='File output format.')
def main():
args = parser.parse_args()
user, format_ = args.user, args.format
return serve_content(get_data(user), user, format_)
if __name__ == '__main__':
main()
<commit_msg>Add support for multiple users, format types<commit_after>#!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, nargs='+', help='GitHub user handle')
parser.add_argument('-f', '--format', nargs='+',
choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt', 'all'],
help='File output format.')
def main():
args = parser.parse_args()
user = args.user
format_ = ['json', 'csv', 'md', 'raw.txt', 'tbl.txt'] if 'all' in args.format else args.format
for u in user:
print('Preparing data for {}...'.format(u))
d = get_data(u)
for f in format_:
if f is not None:
print(' Writing {}...'.format(f), end='')
serve_content(d, u, f)
print(' Done!')
else:
serve_content(d, u, f)
print('Complete!')
return None
if __name__ == '__main__':
main()
|
7dd94bf965fafafb279a4304108462e4060c729c
|
waterbutler/identity.py
|
waterbutler/identity.py
|
import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
IDENTITY_METHODS = {
'rest': fetch_rest_identity
}
get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]
|
import asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identity(func):
IDENTITY_METHODS[name] = func
return func
return _register_identity
def get_identity(name, **kwargs):
return get_identity_func(name)(**kwargs)
@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
|
Make use of a register decorator
|
Make use of a register decorator
|
Python
|
apache-2.0
|
Johnetordoff/waterbutler,RCOSDP/waterbutler,cosenal/waterbutler,rafaeldelucena/waterbutler,TomBaxter/waterbutler,icereval/waterbutler,chrisseto/waterbutler,Ghalko/waterbutler,rdhyee/waterbutler,CenterForOpenScience/waterbutler,hmoco/waterbutler,felliott/waterbutler,kwierman/waterbutler
|
import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
IDENTITY_METHODS = {
'rest': fetch_rest_identity
}
get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]
Make use of a register decorator
|
import asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identity(func):
IDENTITY_METHODS[name] = func
return func
return _register_identity
def get_identity(name, **kwargs):
return get_identity_func(name)(**kwargs)
@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
|
<commit_before>import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
IDENTITY_METHODS = {
'rest': fetch_rest_identity
}
get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]
<commit_msg>Make use of a register decorator<commit_after>
|
import asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identity(func):
IDENTITY_METHODS[name] = func
return func
return _register_identity
def get_identity(name, **kwargs):
return get_identity_func(name)(**kwargs)
@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
|
import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
IDENTITY_METHODS = {
'rest': fetch_rest_identity
}
get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]
Make use of a register decoratorimport asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identity(func):
IDENTITY_METHODS[name] = func
return func
return _register_identity
def get_identity(name, **kwargs):
return get_identity_func(name)(**kwargs)
@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
|
<commit_before>import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
IDENTITY_METHODS = {
'rest': fetch_rest_identity
}
get_identity = IDENTITY_METHODS[settings.IDENTITY_METHOD]
<commit_msg>Make use of a register decorator<commit_after>import asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identity(func):
IDENTITY_METHODS[name] = func
return func
return _register_identity
def get_identity(name, **kwargs):
return get_identity_func(name)(**kwargs)
@register_identity('rest')
@asyncio.coroutine
def fetch_rest_identity(**params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if response.status != 200:
data = yield from response.read()
raise web.HTTPError(response.status)
data = yield from response.json()
return data
|
dd8176f26addcf36419f1723448ab1e3ae8d0e89
|
metashare/repository/search_fields.py
|
metashare/repository/search_fields.py
|
"""
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
|
"""
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, facet_id, parent_id, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
self.facet_id = facet_id
self.parent_id = parent_id
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
|
Order facets and add sub facet feature
|
Order facets and add sub facet feature
|
Python
|
bsd-3-clause
|
MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,zeehio/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,MiltosD/CEF-ELRC,JuliBakagianni/META-SHARE,MiltosD/CEFELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,zeehio/META-SHARE,zeehio/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,zeehio/META-SHARE,MiltosD/CEF-ELRC,MiltosD/CEFELRC,JuliBakagianni/CEF-ELRC,JuliBakagianni/CEF-ELRC,JuliBakagianni/META-SHARE,zeehio/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/META-SHARE,JuliBakagianni/META-SHARE,zeehio/META-SHARE,MiltosD/CEFELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,JuliBakagianni/META-SHARE,JuliBakagianni/META-SHARE,zeehio/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/META-SHARE
|
"""
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
Order facets and add sub facet feature
|
"""
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, facet_id, parent_id, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
self.facet_id = facet_id
self.parent_id = parent_id
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
|
<commit_before>"""
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
<commit_msg>Order facets and add sub facet feature<commit_after>
|
"""
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, facet_id, parent_id, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
self.facet_id = facet_id
self.parent_id = parent_id
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
|
"""
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
Order facets and add sub facet feature"""
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, facet_id, parent_id, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
self.facet_id = facet_id
self.parent_id = parent_id
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
|
<commit_before>"""
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
<commit_msg>Order facets and add sub facet feature<commit_after>"""
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, facet_id, parent_id, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
self.facet_id = facet_id
self.parent_id = parent_id
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
|
7577c51486169e8026a74cd680e2f4b58e4ea60a
|
models/phase3_eval/process_sparser.py
|
models/phase3_eval/process_sparser.py
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = 'sources/sparser-20170330'
sentences_folder = 'sources/sparser-20170210'
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
import json
from indra import sparser
from indra.statements import stmts_from_json, get_valid_location, \
get_valid_residue
base_folder = os.environ['HOME'] + \
'/data/darpa/phase3_eval/sources/sparser-20170530'
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.json'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
try:
jd = json.load(fh)
except ValueError as e:
print(e)
return []
for st in jd:
if st.get('type') == 'Translocation':
for loc in ['from_location', 'to_location']:
val = st.get(loc)
try:
loc_valid = get_valid_location(val)
st[loc] = loc_valid
except:
st[loc] = None
try:
res = st['residue']
if res is False:
st['residue'] = None
except:
pass
try:
res = st.get('residue')
if res:
get_valid_residue(res)
except:
st['residue'] = None
try:
res = st['position']
if res is False:
st['position'] = None
except:
pass
stmts = stmts_from_json(jd)
return stmts
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
|
Read and fix Sparser jsons
|
Read and fix Sparser jsons
|
Python
|
bsd-2-clause
|
pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,bgyori/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,bgyori/indra,johnbachman/belpy,sorgerlab/indra,bgyori/indra,johnbachman/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,pvtodorov/indra,johnbachman/indra
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = 'sources/sparser-20170330'
sentences_folder = 'sources/sparser-20170210'
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
Read and fix Sparser jsons
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
import json
from indra import sparser
from indra.statements import stmts_from_json, get_valid_location, \
get_valid_residue
base_folder = os.environ['HOME'] + \
'/data/darpa/phase3_eval/sources/sparser-20170530'
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.json'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
try:
jd = json.load(fh)
except ValueError as e:
print(e)
return []
for st in jd:
if st.get('type') == 'Translocation':
for loc in ['from_location', 'to_location']:
val = st.get(loc)
try:
loc_valid = get_valid_location(val)
st[loc] = loc_valid
except:
st[loc] = None
try:
res = st['residue']
if res is False:
st['residue'] = None
except:
pass
try:
res = st.get('residue')
if res:
get_valid_residue(res)
except:
st['residue'] = None
try:
res = st['position']
if res is False:
st['position'] = None
except:
pass
stmts = stmts_from_json(jd)
return stmts
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
|
<commit_before>from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = 'sources/sparser-20170330'
sentences_folder = 'sources/sparser-20170210'
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
<commit_msg>Read and fix Sparser jsons<commit_after>
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
import json
from indra import sparser
from indra.statements import stmts_from_json, get_valid_location, \
get_valid_residue
base_folder = os.environ['HOME'] + \
'/data/darpa/phase3_eval/sources/sparser-20170530'
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.json'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
try:
jd = json.load(fh)
except ValueError as e:
print(e)
return []
for st in jd:
if st.get('type') == 'Translocation':
for loc in ['from_location', 'to_location']:
val = st.get(loc)
try:
loc_valid = get_valid_location(val)
st[loc] = loc_valid
except:
st[loc] = None
try:
res = st['residue']
if res is False:
st['residue'] = None
except:
pass
try:
res = st.get('residue')
if res:
get_valid_residue(res)
except:
st['residue'] = None
try:
res = st['position']
if res is False:
st['position'] = None
except:
pass
stmts = stmts_from_json(jd)
return stmts
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = 'sources/sparser-20170330'
sentences_folder = 'sources/sparser-20170210'
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
Read and fix Sparser jsonsfrom __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
import json
from indra import sparser
from indra.statements import stmts_from_json, get_valid_location, \
get_valid_residue
base_folder = os.environ['HOME'] + \
'/data/darpa/phase3_eval/sources/sparser-20170530'
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.json'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
try:
jd = json.load(fh)
except ValueError as e:
print(e)
return []
for st in jd:
if st.get('type') == 'Translocation':
for loc in ['from_location', 'to_location']:
val = st.get(loc)
try:
loc_valid = get_valid_location(val)
st[loc] = loc_valid
except:
st[loc] = None
try:
res = st['residue']
if res is False:
st['residue'] = None
except:
pass
try:
res = st.get('residue')
if res:
get_valid_residue(res)
except:
st['residue'] = None
try:
res = st['position']
if res is False:
st['position'] = None
except:
pass
stmts = stmts_from_json(jd)
return stmts
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
|
<commit_before>from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = 'sources/sparser-20170330'
sentences_folder = 'sources/sparser-20170210'
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
<commit_msg>Read and fix Sparser jsons<commit_after>from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
import json
from indra import sparser
from indra.statements import stmts_from_json, get_valid_location, \
get_valid_residue
base_folder = os.environ['HOME'] + \
'/data/darpa/phase3_eval/sources/sparser-20170530'
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.json'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
try:
jd = json.load(fh)
except ValueError as e:
print(e)
return []
for st in jd:
if st.get('type') == 'Translocation':
for loc in ['from_location', 'to_location']:
val = st.get(loc)
try:
loc_valid = get_valid_location(val)
st[loc] = loc_valid
except:
st[loc] = None
try:
res = st['residue']
if res is False:
st['residue'] = None
except:
pass
try:
res = st.get('residue')
if res:
get_valid_residue(res)
except:
st['residue'] = None
try:
res = st['position']
if res is False:
st['position'] = None
except:
pass
stmts = stmts_from_json(jd)
return stmts
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
|
58b798c6e8dc36a28f6e553ce29ae7eab75ea386
|
angr/procedures/linux_kernel/cwd.py
|
angr/procedures/linux_kernel/cwd.py
|
import angr
import logging
l = logging.getLogger(name=__name__)
class getcwd(angr.SimProcedure):
def run(self, buf, size):
cwd = self.state.fs.cwd
size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1)
try:
self.state.memory.store(buf, cwd, size=size)
self.state.memory.store(buf + size, b'\0')
except angr.errors.SimSegfaultException:
return 0
else:
return buf
class chdir(angr.SimProcedure):
def run(self, buf):
cwd = self.state.mem[buf].string
l.info('chdir(%r)', cwd)
self.state.fs.cwd = cwd
return 0
|
import angr
import logging
l = logging.getLogger(name=__name__)
class getcwd(angr.SimProcedure):
def run(self, buf, size):
cwd = self.state.fs.cwd
size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1)
try:
self.state.memory.store(buf, cwd, size=size)
self.state.memory.store(buf + size, b'\0')
except angr.errors.SimSegfaultException:
return 0
else:
return buf
class chdir(angr.SimProcedure):
def run(self, buf):
cwd = self.state.mem[buf].string.concrete
l.info('chdir(%r)', cwd)
self.state.fs.cwd = cwd
return 0
|
Fix string resolution for filesystem
|
Fix string resolution for filesystem
|
Python
|
bsd-2-clause
|
angr/angr,angr/angr,angr/angr
|
import angr
import logging
l = logging.getLogger(name=__name__)
class getcwd(angr.SimProcedure):
def run(self, buf, size):
cwd = self.state.fs.cwd
size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1)
try:
self.state.memory.store(buf, cwd, size=size)
self.state.memory.store(buf + size, b'\0')
except angr.errors.SimSegfaultException:
return 0
else:
return buf
class chdir(angr.SimProcedure):
def run(self, buf):
cwd = self.state.mem[buf].string
l.info('chdir(%r)', cwd)
self.state.fs.cwd = cwd
return 0
Fix string resolution for filesystem
|
import angr
import logging
l = logging.getLogger(name=__name__)
class getcwd(angr.SimProcedure):
def run(self, buf, size):
cwd = self.state.fs.cwd
size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1)
try:
self.state.memory.store(buf, cwd, size=size)
self.state.memory.store(buf + size, b'\0')
except angr.errors.SimSegfaultException:
return 0
else:
return buf
class chdir(angr.SimProcedure):
def run(self, buf):
cwd = self.state.mem[buf].string.concrete
l.info('chdir(%r)', cwd)
self.state.fs.cwd = cwd
return 0
|
<commit_before>import angr
import logging
l = logging.getLogger(name=__name__)
class getcwd(angr.SimProcedure):
def run(self, buf, size):
cwd = self.state.fs.cwd
size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1)
try:
self.state.memory.store(buf, cwd, size=size)
self.state.memory.store(buf + size, b'\0')
except angr.errors.SimSegfaultException:
return 0
else:
return buf
class chdir(angr.SimProcedure):
def run(self, buf):
cwd = self.state.mem[buf].string
l.info('chdir(%r)', cwd)
self.state.fs.cwd = cwd
return 0
<commit_msg>Fix string resolution for filesystem<commit_after>
|
import angr
import logging
l = logging.getLogger(name=__name__)
class getcwd(angr.SimProcedure):
def run(self, buf, size):
cwd = self.state.fs.cwd
size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1)
try:
self.state.memory.store(buf, cwd, size=size)
self.state.memory.store(buf + size, b'\0')
except angr.errors.SimSegfaultException:
return 0
else:
return buf
class chdir(angr.SimProcedure):
def run(self, buf):
cwd = self.state.mem[buf].string.concrete
l.info('chdir(%r)', cwd)
self.state.fs.cwd = cwd
return 0
|
import angr
import logging
l = logging.getLogger(name=__name__)
class getcwd(angr.SimProcedure):
def run(self, buf, size):
cwd = self.state.fs.cwd
size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1)
try:
self.state.memory.store(buf, cwd, size=size)
self.state.memory.store(buf + size, b'\0')
except angr.errors.SimSegfaultException:
return 0
else:
return buf
class chdir(angr.SimProcedure):
def run(self, buf):
cwd = self.state.mem[buf].string
l.info('chdir(%r)', cwd)
self.state.fs.cwd = cwd
return 0
Fix string resolution for filesystemimport angr
import logging
l = logging.getLogger(name=__name__)
class getcwd(angr.SimProcedure):
def run(self, buf, size):
cwd = self.state.fs.cwd
size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1)
try:
self.state.memory.store(buf, cwd, size=size)
self.state.memory.store(buf + size, b'\0')
except angr.errors.SimSegfaultException:
return 0
else:
return buf
class chdir(angr.SimProcedure):
def run(self, buf):
cwd = self.state.mem[buf].string.concrete
l.info('chdir(%r)', cwd)
self.state.fs.cwd = cwd
return 0
|
<commit_before>import angr
import logging
l = logging.getLogger(name=__name__)
class getcwd(angr.SimProcedure):
def run(self, buf, size):
cwd = self.state.fs.cwd
size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1)
try:
self.state.memory.store(buf, cwd, size=size)
self.state.memory.store(buf + size, b'\0')
except angr.errors.SimSegfaultException:
return 0
else:
return buf
class chdir(angr.SimProcedure):
def run(self, buf):
cwd = self.state.mem[buf].string
l.info('chdir(%r)', cwd)
self.state.fs.cwd = cwd
return 0
<commit_msg>Fix string resolution for filesystem<commit_after>import angr
import logging
l = logging.getLogger(name=__name__)
class getcwd(angr.SimProcedure):
def run(self, buf, size):
cwd = self.state.fs.cwd
size = self.state.solver.If(size-1 > len(cwd), len(cwd), size-1)
try:
self.state.memory.store(buf, cwd, size=size)
self.state.memory.store(buf + size, b'\0')
except angr.errors.SimSegfaultException:
return 0
else:
return buf
class chdir(angr.SimProcedure):
def run(self, buf):
cwd = self.state.mem[buf].string.concrete
l.info('chdir(%r)', cwd)
self.state.fs.cwd = cwd
return 0
|
442aa916dc7b6d199b2c5e1fe973aa3fed8e9c35
|
src/python/grpcio_tests/tests_aio/unit/init_test.py
|
src/python/grpcio_tests/tests_aio/unit/init_test.py
|
# Copyright 2019 The gRPC Authors.
#
# 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 logging
import unittest
from tests_aio.unit._test_base import AioTestBase
class TestInit(AioTestBase):
async def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_grpc_dot_aio(self):
import grpc.aio # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_aio_from_grpc(self):
from grpc import aio # pylint: disable=wrong-import-position
channel = aio.insecure_channel('dummy')
self.assertIsInstance(channel, aio.Channel)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
unittest.main(verbosity=2)
|
# Copyright 2019 The gRPC Authors.
#
# 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 logging
import unittest
from tests_aio.unit._test_base import AioTestBase
class TestInit(AioTestBase):
async def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_grpc_dot_aio(self):
import grpc.aio # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
unittest.main(verbosity=2)
|
Make sure the module space won't be polluted by "from grpc import aio"
|
Make sure the module space won't be polluted by "from grpc import aio"
|
Python
|
apache-2.0
|
jtattermusch/grpc,donnadionne/grpc,nicolasnoble/grpc,grpc/grpc,ejona86/grpc,donnadionne/grpc,ctiller/grpc,jtattermusch/grpc,nicolasnoble/grpc,donnadionne/grpc,vjpai/grpc,grpc/grpc,grpc/grpc,ctiller/grpc,vjpai/grpc,jtattermusch/grpc,donnadionne/grpc,grpc/grpc,ejona86/grpc,stanley-cheung/grpc,stanley-cheung/grpc,nicolasnoble/grpc,vjpai/grpc,vjpai/grpc,stanley-cheung/grpc,ctiller/grpc,stanley-cheung/grpc,vjpai/grpc,ejona86/grpc,stanley-cheung/grpc,ejona86/grpc,jtattermusch/grpc,ctiller/grpc,grpc/grpc,vjpai/grpc,ctiller/grpc,grpc/grpc,donnadionne/grpc,vjpai/grpc,ejona86/grpc,jtattermusch/grpc,jtattermusch/grpc,jtattermusch/grpc,vjpai/grpc,vjpai/grpc,jtattermusch/grpc,donnadionne/grpc,nicolasnoble/grpc,nicolasnoble/grpc,jtattermusch/grpc,ctiller/grpc,stanley-cheung/grpc,donnadionne/grpc,jtattermusch/grpc,donnadionne/grpc,nicolasnoble/grpc,nicolasnoble/grpc,jtattermusch/grpc,ctiller/grpc,donnadionne/grpc,grpc/grpc,grpc/grpc,ctiller/grpc,stanley-cheung/grpc,ctiller/grpc,nicolasnoble/grpc,donnadionne/grpc,stanley-cheung/grpc,ejona86/grpc,stanley-cheung/grpc,donnadionne/grpc,jtattermusch/grpc,ejona86/grpc,stanley-cheung/grpc,donnadionne/grpc,ctiller/grpc,ejona86/grpc,ctiller/grpc,stanley-cheung/grpc,nicolasnoble/grpc,ejona86/grpc,vjpai/grpc,stanley-cheung/grpc,grpc/grpc,grpc/grpc,grpc/grpc,vjpai/grpc,nicolasnoble/grpc,nicolasnoble/grpc,nicolasnoble/grpc,ejona86/grpc,ctiller/grpc,ejona86/grpc,ejona86/grpc,grpc/grpc,vjpai/grpc
|
# Copyright 2019 The gRPC Authors.
#
# 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 logging
import unittest
from tests_aio.unit._test_base import AioTestBase
class TestInit(AioTestBase):
async def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_grpc_dot_aio(self):
import grpc.aio # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_aio_from_grpc(self):
from grpc import aio # pylint: disable=wrong-import-position
channel = aio.insecure_channel('dummy')
self.assertIsInstance(channel, aio.Channel)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
unittest.main(verbosity=2)
Make sure the module space won't be polluted by "from grpc import aio"
|
# Copyright 2019 The gRPC Authors.
#
# 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 logging
import unittest
from tests_aio.unit._test_base import AioTestBase
class TestInit(AioTestBase):
async def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_grpc_dot_aio(self):
import grpc.aio # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
unittest.main(verbosity=2)
|
<commit_before># Copyright 2019 The gRPC Authors.
#
# 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 logging
import unittest
from tests_aio.unit._test_base import AioTestBase
class TestInit(AioTestBase):
async def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_grpc_dot_aio(self):
import grpc.aio # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_aio_from_grpc(self):
from grpc import aio # pylint: disable=wrong-import-position
channel = aio.insecure_channel('dummy')
self.assertIsInstance(channel, aio.Channel)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
unittest.main(verbosity=2)
<commit_msg>Make sure the module space won't be polluted by "from grpc import aio"<commit_after>
|
# Copyright 2019 The gRPC Authors.
#
# 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 logging
import unittest
from tests_aio.unit._test_base import AioTestBase
class TestInit(AioTestBase):
async def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_grpc_dot_aio(self):
import grpc.aio # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
unittest.main(verbosity=2)
|
# Copyright 2019 The gRPC Authors.
#
# 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 logging
import unittest
from tests_aio.unit._test_base import AioTestBase
class TestInit(AioTestBase):
async def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_grpc_dot_aio(self):
import grpc.aio # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_aio_from_grpc(self):
from grpc import aio # pylint: disable=wrong-import-position
channel = aio.insecure_channel('dummy')
self.assertIsInstance(channel, aio.Channel)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
unittest.main(verbosity=2)
Make sure the module space won't be polluted by "from grpc import aio"# Copyright 2019 The gRPC Authors.
#
# 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 logging
import unittest
from tests_aio.unit._test_base import AioTestBase
class TestInit(AioTestBase):
async def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_grpc_dot_aio(self):
import grpc.aio # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
unittest.main(verbosity=2)
|
<commit_before># Copyright 2019 The gRPC Authors.
#
# 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 logging
import unittest
from tests_aio.unit._test_base import AioTestBase
class TestInit(AioTestBase):
async def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_grpc_dot_aio(self):
import grpc.aio # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_aio_from_grpc(self):
from grpc import aio # pylint: disable=wrong-import-position
channel = aio.insecure_channel('dummy')
self.assertIsInstance(channel, aio.Channel)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
unittest.main(verbosity=2)
<commit_msg>Make sure the module space won't be polluted by "from grpc import aio"<commit_after># Copyright 2019 The gRPC Authors.
#
# 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 logging
import unittest
from tests_aio.unit._test_base import AioTestBase
class TestInit(AioTestBase):
async def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
async def test_grpc_dot_aio(self):
import grpc.aio # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
unittest.main(verbosity=2)
|
f99c2687786144d3c06d25705cc884199b962272
|
microdrop/tests/update_dmf_control_board.py
|
microdrop/tests/update_dmf_control_board.py
|
import os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board.git'])
else:
print 'Fetch lastest update...'
subprocess.call(['git', 'pull'])
|
import os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.check_call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board.git'])
else:
print 'Fetch lastest update...'
subprocess.check_call(['git', 'pull'])
|
Check that update script is successful
|
Check that update script is successful
|
Python
|
bsd-3-clause
|
wheeler-microfluidics/microdrop
|
import os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board.git'])
else:
print 'Fetch lastest update...'
subprocess.call(['git', 'pull'])Check that update script is successful
|
import os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.check_call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board.git'])
else:
print 'Fetch lastest update...'
subprocess.check_call(['git', 'pull'])
|
<commit_before>import os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board.git'])
else:
print 'Fetch lastest update...'
subprocess.call(['git', 'pull'])<commit_msg>Check that update script is successful<commit_after>
|
import os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.check_call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board.git'])
else:
print 'Fetch lastest update...'
subprocess.check_call(['git', 'pull'])
|
import os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board.git'])
else:
print 'Fetch lastest update...'
subprocess.call(['git', 'pull'])Check that update script is successfulimport os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.check_call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board.git'])
else:
print 'Fetch lastest update...'
subprocess.check_call(['git', 'pull'])
|
<commit_before>import os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board.git'])
else:
print 'Fetch lastest update...'
subprocess.call(['git', 'pull'])<commit_msg>Check that update script is successful<commit_after>import os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.check_call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board.git'])
else:
print 'Fetch lastest update...'
subprocess.check_call(['git', 'pull'])
|
9cdae34b42ef51502a54dc4dfbd70486d695c114
|
anyway/parsers/utils.py
|
anyway/parsers/utils.py
|
def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in xrange(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
break
yield batch
if iteration_stopped:
break
|
def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in range(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
break
yield batch
if iteration_stopped:
break
|
Change xrange to range for forward-competability
|
Change xrange to range for forward-competability
|
Python
|
mit
|
hasadna/anyway,hasadna/anyway,hasadna/anyway,hasadna/anyway
|
def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in xrange(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
break
yield batch
if iteration_stopped:
break
Change xrange to range for forward-competability
|
def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in range(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
break
yield batch
if iteration_stopped:
break
|
<commit_before>def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in xrange(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
break
yield batch
if iteration_stopped:
break
<commit_msg>Change xrange to range for forward-competability<commit_after>
|
def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in range(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
break
yield batch
if iteration_stopped:
break
|
def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in xrange(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
break
yield batch
if iteration_stopped:
break
Change xrange to range for forward-competabilitydef batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in range(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
break
yield batch
if iteration_stopped:
break
|
<commit_before>def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in xrange(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
break
yield batch
if iteration_stopped:
break
<commit_msg>Change xrange to range for forward-competability<commit_after>def batch_iterator(iterable, batch_size):
iterator = iter(iterable)
iteration_stopped = False
while True:
batch = []
for _ in range(batch_size):
try:
batch.append(next(iterator))
except StopIteration:
iteration_stopped = True
break
yield batch
if iteration_stopped:
break
|
2bfd89b7fe7c4ac4c70f324a745dedbd84dd0672
|
__main__.py
|
__main__.py
|
from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
ps1 = term.bold_blue(ps1)
ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
|
from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
|
Remove colors from REPL prompt
|
Remove colors from REPL prompt
They weren't playing nice with Readline.
There's still an optional dependency on Blessings, but that is only
used to strip away the trailing ps2.
|
Python
|
isc
|
gvx/isle
|
from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
ps1 = term.bold_blue(ps1)
ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
Remove colors from REPL prompt
They weren't playing nice with Readline.
There's still an optional dependency on Blessings, but that is only
used to strip away the trailing ps2.
|
from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
|
<commit_before>from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
ps1 = term.bold_blue(ps1)
ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
<commit_msg>Remove colors from REPL prompt
They weren't playing nice with Readline.
There's still an optional dependency on Blessings, but that is only
used to strip away the trailing ps2.<commit_after>
|
from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
|
from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
ps1 = term.bold_blue(ps1)
ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
Remove colors from REPL prompt
They weren't playing nice with Readline.
There's still an optional dependency on Blessings, but that is only
used to strip away the trailing ps2.from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
|
<commit_before>from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
ps1 = term.bold_blue(ps1)
ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
<commit_msg>Remove colors from REPL prompt
They weren't playing nice with Readline.
There's still an optional dependency on Blessings, but that is only
used to strip away the trailing ps2.<commit_after>from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
|
03ef4407612d553095f39694527d20543bc4405a
|
subiquity/core.py
|
subiquity/core.py
|
# Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Installpath",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
|
# Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
|
Drop Installpath controller, whilst it's single option.
|
Drop Installpath controller, whilst it's single option.
|
Python
|
agpl-3.0
|
CanonicalLtd/subiquity,CanonicalLtd/subiquity
|
# Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Installpath",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
Drop Installpath controller, whilst it's single option.
|
# Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
|
<commit_before># Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Installpath",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
<commit_msg>Drop Installpath controller, whilst it's single option.<commit_after>
|
# Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
|
# Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Installpath",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
Drop Installpath controller, whilst it's single option.# Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
|
<commit_before># Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Installpath",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
<commit_msg>Drop Installpath controller, whilst it's single option.<commit_after># Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
|
4d4e0534c7c9ac674876175d63927fc38a5aa507
|
app/sense.py
|
app/sense.py
|
import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.2
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
|
import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.1
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
|
Increase the frequency of the sensing checks (important for the color sensor/simple line following.
|
Increase the frequency of the sensing checks (important for the color sensor/simple line following.
|
Python
|
bsd-2-clause
|
legorovers/legoflask,legorovers/legoflask,legorovers/legoflask
|
import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.2
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
Increase the frequency of the sensing checks (important for the color sensor/simple line following.
|
import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.1
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
|
<commit_before>import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.2
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
<commit_msg>Increase the frequency of the sensing checks (important for the color sensor/simple line following.<commit_after>
|
import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.1
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
|
import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.2
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
Increase the frequency of the sensing checks (important for the color sensor/simple line following.import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.1
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
|
<commit_before>import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.2
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
<commit_msg>Increase the frequency of the sensing checks (important for the color sensor/simple line following.<commit_after>import threading
import time
class SensorThread(object):
def __init__(self, notify, delay=0):
self.notify = notify
self.delay = delay
self.interval = 0.1
self.color = -1
def start(self, control, robot):
self.control = control
self.robot = robot
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
color = int(self.robot.color())
touch = self.robot.touch()
try:
direction = self.robot.direction()
except:
direction = 0
self.control.readings(color, touch, direction)
time.sleep(self.interval)
def sensors(self, color, touch, direction):
#print "sense: %s %s" % (touch, direction)
if not self.color == color:
self.notify.emit('sense', color)
self.color = color
print "color %s%%" % color
|
add4824d69afc928790459129fffbdf72820971f
|
accloudtant/__main__.py
|
accloudtant/__main__.py
|
import csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
if __name__ == "__main__":
usage = []
with open("tests/fixtures/2021/03/S3.csv") as f:
reader = csv.DictReader(f)
for row in reader:
usage.append(row)
print("Simple Storage Service")
for area_name in set([area(entry) for entry in usage]):
print("\t", area_name)
|
import csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
def get_areas(entries):
areas = {}
for entry in entries:
area_name = area(entry)
if area_name not in areas:
areas[area_name] = []
areas[area_name].append(entry)
return areas
if __name__ == "__main__":
usage = []
with open("tests/fixtures/2021/03/S3.csv") as f:
reader = csv.DictReader(f)
for row in reader:
usage.append(row)
print("Simple Storage Service")
for area_name, entries in get_areas(usage).items():
print("\t", area_name)
for concept in set([entry[" UsageType"] for entry in entries]):
print("\t\t", concept)
|
Print list of concepts per area
|
Print list of concepts per area
|
Python
|
apache-2.0
|
ifosch/accloudtant
|
import csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
if __name__ == "__main__":
usage = []
with open("tests/fixtures/2021/03/S3.csv") as f:
reader = csv.DictReader(f)
for row in reader:
usage.append(row)
print("Simple Storage Service")
for area_name in set([area(entry) for entry in usage]):
print("\t", area_name)
Print list of concepts per area
|
import csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
def get_areas(entries):
areas = {}
for entry in entries:
area_name = area(entry)
if area_name not in areas:
areas[area_name] = []
areas[area_name].append(entry)
return areas
if __name__ == "__main__":
usage = []
with open("tests/fixtures/2021/03/S3.csv") as f:
reader = csv.DictReader(f)
for row in reader:
usage.append(row)
print("Simple Storage Service")
for area_name, entries in get_areas(usage).items():
print("\t", area_name)
for concept in set([entry[" UsageType"] for entry in entries]):
print("\t\t", concept)
|
<commit_before>import csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
if __name__ == "__main__":
usage = []
with open("tests/fixtures/2021/03/S3.csv") as f:
reader = csv.DictReader(f)
for row in reader:
usage.append(row)
print("Simple Storage Service")
for area_name in set([area(entry) for entry in usage]):
print("\t", area_name)
<commit_msg>Print list of concepts per area<commit_after>
|
import csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
def get_areas(entries):
areas = {}
for entry in entries:
area_name = area(entry)
if area_name not in areas:
areas[area_name] = []
areas[area_name].append(entry)
return areas
if __name__ == "__main__":
usage = []
with open("tests/fixtures/2021/03/S3.csv") as f:
reader = csv.DictReader(f)
for row in reader:
usage.append(row)
print("Simple Storage Service")
for area_name, entries in get_areas(usage).items():
print("\t", area_name)
for concept in set([entry[" UsageType"] for entry in entries]):
print("\t\t", concept)
|
import csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
if __name__ == "__main__":
usage = []
with open("tests/fixtures/2021/03/S3.csv") as f:
reader = csv.DictReader(f)
for row in reader:
usage.append(row)
print("Simple Storage Service")
for area_name in set([area(entry) for entry in usage]):
print("\t", area_name)
Print list of concepts per areaimport csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
def get_areas(entries):
areas = {}
for entry in entries:
area_name = area(entry)
if area_name not in areas:
areas[area_name] = []
areas[area_name].append(entry)
return areas
if __name__ == "__main__":
usage = []
with open("tests/fixtures/2021/03/S3.csv") as f:
reader = csv.DictReader(f)
for row in reader:
usage.append(row)
print("Simple Storage Service")
for area_name, entries in get_areas(usage).items():
print("\t", area_name)
for concept in set([entry[" UsageType"] for entry in entries]):
print("\t\t", concept)
|
<commit_before>import csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
if __name__ == "__main__":
usage = []
with open("tests/fixtures/2021/03/S3.csv") as f:
reader = csv.DictReader(f)
for row in reader:
usage.append(row)
print("Simple Storage Service")
for area_name in set([area(entry) for entry in usage]):
print("\t", area_name)
<commit_msg>Print list of concepts per area<commit_after>import csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
def get_areas(entries):
areas = {}
for entry in entries:
area_name = area(entry)
if area_name not in areas:
areas[area_name] = []
areas[area_name].append(entry)
return areas
if __name__ == "__main__":
usage = []
with open("tests/fixtures/2021/03/S3.csv") as f:
reader = csv.DictReader(f)
for row in reader:
usage.append(row)
print("Simple Storage Service")
for area_name, entries in get_areas(usage).items():
print("\t", area_name)
for concept in set([entry[" UsageType"] for entry in entries]):
print("\t\t", concept)
|
f704722d54092a6d9b65f726a6b83d208b3e1946
|
chatroom.py
|
chatroom.py
|
class ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
self.users.remove(user)
return len (self.users)
|
class ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
if user in self.users:
self.users.remove(user)
return len (self.users)
|
Make sure user is in room's user list before removing
|
Make sure user is in room's user list before removing
|
Python
|
mit
|
jtoelke/fenfirechat
|
class ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
self.users.remove(user)
return len (self.users)
Make sure user is in room's user list before removing
|
class ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
if user in self.users:
self.users.remove(user)
return len (self.users)
|
<commit_before>class ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
self.users.remove(user)
return len (self.users)
<commit_msg>Make sure user is in room's user list before removing<commit_after>
|
class ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
if user in self.users:
self.users.remove(user)
return len (self.users)
|
class ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
self.users.remove(user)
return len (self.users)
Make sure user is in room's user list before removingclass ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
if user in self.users:
self.users.remove(user)
return len (self.users)
|
<commit_before>class ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
self.users.remove(user)
return len (self.users)
<commit_msg>Make sure user is in room's user list before removing<commit_after>class ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
if user in self.users:
self.users.remove(user)
return len (self.users)
|
8d34496986e68de8aa1a691a494da08f523cb034
|
oauthenticator/tests/conftest.py
|
oauthenticator/tests/conftest.py
|
"""Py.Test fixtures"""
from tornado.httpclient import AsyncHTTPClient
from pytest import fixture
from .mocks import MockAsyncHTTPClient
@fixture
def client(io_loop, request):
"""Return mocked AsyncHTTPClient"""
before = AsyncHTTPClient.configured_class()
AsyncHTTPClient.configure(MockAsyncHTTPClient)
request.addfinalizer(lambda : AsyncHTTPClient.configure(before))
c = AsyncHTTPClient()
assert isinstance(c, MockAsyncHTTPClient)
return c
|
"""Py.Test fixtures"""
from tornado.httpclient import AsyncHTTPClient
from tornado import ioloop
from pytest import fixture
from .mocks import MockAsyncHTTPClient
@fixture
def io_loop(request):
"""Same as pytest-tornado.io_loop, adapted for tornado 5"""
io_loop = ioloop.IOLoop()
io_loop.make_current()
def _close():
io_loop.clear_current()
io_loop.close(all_fds=True)
request.addfinalizer(_close)
return io_loop
@fixture
def client(io_loop, request):
"""Return mocked AsyncHTTPClient"""
before = AsyncHTTPClient.configured_class()
AsyncHTTPClient.configure(MockAsyncHTTPClient)
request.addfinalizer(lambda : AsyncHTTPClient.configure(before))
c = AsyncHTTPClient()
assert isinstance(c, MockAsyncHTTPClient)
return c
|
Add ioloop fixture that works with tornado 5
|
Add ioloop fixture that works with tornado 5
|
Python
|
bsd-3-clause
|
maltevogl/oauthenticator,minrk/oauthenticator,NickolausDS/oauthenticator,jupyterhub/oauthenticator,jupyter/oauthenticator,jupyter/oauthenticator,enolfc/oauthenticator
|
"""Py.Test fixtures"""
from tornado.httpclient import AsyncHTTPClient
from pytest import fixture
from .mocks import MockAsyncHTTPClient
@fixture
def client(io_loop, request):
"""Return mocked AsyncHTTPClient"""
before = AsyncHTTPClient.configured_class()
AsyncHTTPClient.configure(MockAsyncHTTPClient)
request.addfinalizer(lambda : AsyncHTTPClient.configure(before))
c = AsyncHTTPClient()
assert isinstance(c, MockAsyncHTTPClient)
return c
Add ioloop fixture that works with tornado 5
|
"""Py.Test fixtures"""
from tornado.httpclient import AsyncHTTPClient
from tornado import ioloop
from pytest import fixture
from .mocks import MockAsyncHTTPClient
@fixture
def io_loop(request):
"""Same as pytest-tornado.io_loop, adapted for tornado 5"""
io_loop = ioloop.IOLoop()
io_loop.make_current()
def _close():
io_loop.clear_current()
io_loop.close(all_fds=True)
request.addfinalizer(_close)
return io_loop
@fixture
def client(io_loop, request):
"""Return mocked AsyncHTTPClient"""
before = AsyncHTTPClient.configured_class()
AsyncHTTPClient.configure(MockAsyncHTTPClient)
request.addfinalizer(lambda : AsyncHTTPClient.configure(before))
c = AsyncHTTPClient()
assert isinstance(c, MockAsyncHTTPClient)
return c
|
<commit_before>"""Py.Test fixtures"""
from tornado.httpclient import AsyncHTTPClient
from pytest import fixture
from .mocks import MockAsyncHTTPClient
@fixture
def client(io_loop, request):
"""Return mocked AsyncHTTPClient"""
before = AsyncHTTPClient.configured_class()
AsyncHTTPClient.configure(MockAsyncHTTPClient)
request.addfinalizer(lambda : AsyncHTTPClient.configure(before))
c = AsyncHTTPClient()
assert isinstance(c, MockAsyncHTTPClient)
return c
<commit_msg>Add ioloop fixture that works with tornado 5<commit_after>
|
"""Py.Test fixtures"""
from tornado.httpclient import AsyncHTTPClient
from tornado import ioloop
from pytest import fixture
from .mocks import MockAsyncHTTPClient
@fixture
def io_loop(request):
"""Same as pytest-tornado.io_loop, adapted for tornado 5"""
io_loop = ioloop.IOLoop()
io_loop.make_current()
def _close():
io_loop.clear_current()
io_loop.close(all_fds=True)
request.addfinalizer(_close)
return io_loop
@fixture
def client(io_loop, request):
"""Return mocked AsyncHTTPClient"""
before = AsyncHTTPClient.configured_class()
AsyncHTTPClient.configure(MockAsyncHTTPClient)
request.addfinalizer(lambda : AsyncHTTPClient.configure(before))
c = AsyncHTTPClient()
assert isinstance(c, MockAsyncHTTPClient)
return c
|
"""Py.Test fixtures"""
from tornado.httpclient import AsyncHTTPClient
from pytest import fixture
from .mocks import MockAsyncHTTPClient
@fixture
def client(io_loop, request):
"""Return mocked AsyncHTTPClient"""
before = AsyncHTTPClient.configured_class()
AsyncHTTPClient.configure(MockAsyncHTTPClient)
request.addfinalizer(lambda : AsyncHTTPClient.configure(before))
c = AsyncHTTPClient()
assert isinstance(c, MockAsyncHTTPClient)
return c
Add ioloop fixture that works with tornado 5"""Py.Test fixtures"""
from tornado.httpclient import AsyncHTTPClient
from tornado import ioloop
from pytest import fixture
from .mocks import MockAsyncHTTPClient
@fixture
def io_loop(request):
"""Same as pytest-tornado.io_loop, adapted for tornado 5"""
io_loop = ioloop.IOLoop()
io_loop.make_current()
def _close():
io_loop.clear_current()
io_loop.close(all_fds=True)
request.addfinalizer(_close)
return io_loop
@fixture
def client(io_loop, request):
"""Return mocked AsyncHTTPClient"""
before = AsyncHTTPClient.configured_class()
AsyncHTTPClient.configure(MockAsyncHTTPClient)
request.addfinalizer(lambda : AsyncHTTPClient.configure(before))
c = AsyncHTTPClient()
assert isinstance(c, MockAsyncHTTPClient)
return c
|
<commit_before>"""Py.Test fixtures"""
from tornado.httpclient import AsyncHTTPClient
from pytest import fixture
from .mocks import MockAsyncHTTPClient
@fixture
def client(io_loop, request):
"""Return mocked AsyncHTTPClient"""
before = AsyncHTTPClient.configured_class()
AsyncHTTPClient.configure(MockAsyncHTTPClient)
request.addfinalizer(lambda : AsyncHTTPClient.configure(before))
c = AsyncHTTPClient()
assert isinstance(c, MockAsyncHTTPClient)
return c
<commit_msg>Add ioloop fixture that works with tornado 5<commit_after>"""Py.Test fixtures"""
from tornado.httpclient import AsyncHTTPClient
from tornado import ioloop
from pytest import fixture
from .mocks import MockAsyncHTTPClient
@fixture
def io_loop(request):
"""Same as pytest-tornado.io_loop, adapted for tornado 5"""
io_loop = ioloop.IOLoop()
io_loop.make_current()
def _close():
io_loop.clear_current()
io_loop.close(all_fds=True)
request.addfinalizer(_close)
return io_loop
@fixture
def client(io_loop, request):
"""Return mocked AsyncHTTPClient"""
before = AsyncHTTPClient.configured_class()
AsyncHTTPClient.configure(MockAsyncHTTPClient)
request.addfinalizer(lambda : AsyncHTTPClient.configure(before))
c = AsyncHTTPClient()
assert isinstance(c, MockAsyncHTTPClient)
return c
|
12f1024d559c300c7c04256362da78ec8d3a647b
|
data/models.py
|
data/models.py
|
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
|
import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
@classmethod
def get_data(cls):
data = DataPoint.objects.filter(band_gap__isnull=False,
exact_name__isnull=False,
decay_feature__isnull=False)
M = len(data)
HOMO = numpy.zeros((M, 1))
LUMO = numpy.zeros((M, 1))
GAP = numpy.zeros((M, 1))
vectors = []
for i, x in enumerate(data):
HOMO[i] = x.homo
LUMO[i] = x.lumo
GAP[i] = x.band_gap
vectors.append(ast.literal_eval(x.decay_feature))
FEATURE = numpy.matrix(vectors)
return FEATURE, HOMO, LUMO, GAP
|
Add method on DataPoint to get numpy matrices with all the ML data
|
Add method on DataPoint to get numpy matrices with all the ML data
|
Python
|
mit
|
crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp
|
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
Add method on DataPoint to get numpy matrices with all the ML data
|
import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
@classmethod
def get_data(cls):
data = DataPoint.objects.filter(band_gap__isnull=False,
exact_name__isnull=False,
decay_feature__isnull=False)
M = len(data)
HOMO = numpy.zeros((M, 1))
LUMO = numpy.zeros((M, 1))
GAP = numpy.zeros((M, 1))
vectors = []
for i, x in enumerate(data):
HOMO[i] = x.homo
LUMO[i] = x.lumo
GAP[i] = x.band_gap
vectors.append(ast.literal_eval(x.decay_feature))
FEATURE = numpy.matrix(vectors)
return FEATURE, HOMO, LUMO, GAP
|
<commit_before>from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
<commit_msg>Add method on DataPoint to get numpy matrices with all the ML data<commit_after>
|
import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
@classmethod
def get_data(cls):
data = DataPoint.objects.filter(band_gap__isnull=False,
exact_name__isnull=False,
decay_feature__isnull=False)
M = len(data)
HOMO = numpy.zeros((M, 1))
LUMO = numpy.zeros((M, 1))
GAP = numpy.zeros((M, 1))
vectors = []
for i, x in enumerate(data):
HOMO[i] = x.homo
LUMO[i] = x.lumo
GAP[i] = x.band_gap
vectors.append(ast.literal_eval(x.decay_feature))
FEATURE = numpy.matrix(vectors)
return FEATURE, HOMO, LUMO, GAP
|
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
Add method on DataPoint to get numpy matrices with all the ML dataimport numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
@classmethod
def get_data(cls):
data = DataPoint.objects.filter(band_gap__isnull=False,
exact_name__isnull=False,
decay_feature__isnull=False)
M = len(data)
HOMO = numpy.zeros((M, 1))
LUMO = numpy.zeros((M, 1))
GAP = numpy.zeros((M, 1))
vectors = []
for i, x in enumerate(data):
HOMO[i] = x.homo
LUMO[i] = x.lumo
GAP[i] = x.band_gap
vectors.append(ast.literal_eval(x.decay_feature))
FEATURE = numpy.matrix(vectors)
return FEATURE, HOMO, LUMO, GAP
|
<commit_before>from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
<commit_msg>Add method on DataPoint to get numpy matrices with all the ML data<commit_after>import numpy
import ast
from django.db import models
class DataPoint(models.Model):
name = models.CharField(max_length=600)
exact_name = models.CharField(max_length=1000, null=True, blank=True)
decay_feature = models.CharField(max_length=1000, null=True, blank=True)
options = models.CharField(max_length=100)
homo = models.FloatField()
lumo = models.FloatField()
homo_orbital = models.IntegerField()
energy = models.FloatField()
dipole = models.FloatField()
band_gap = models.FloatField(null=True, blank=True)
def __unicode__(self):
return self.exact_name
@classmethod
def get_data(cls):
data = DataPoint.objects.filter(band_gap__isnull=False,
exact_name__isnull=False,
decay_feature__isnull=False)
M = len(data)
HOMO = numpy.zeros((M, 1))
LUMO = numpy.zeros((M, 1))
GAP = numpy.zeros((M, 1))
vectors = []
for i, x in enumerate(data):
HOMO[i] = x.homo
LUMO[i] = x.lumo
GAP[i] = x.band_gap
vectors.append(ast.literal_eval(x.decay_feature))
FEATURE = numpy.matrix(vectors)
return FEATURE, HOMO, LUMO, GAP
|
83e83cdd90364e037530974e2cea977a05ac449b
|
pos_picking_state_fix/models/pos_picking.py
|
pos_picking_state_fix/models/pos_picking.py
|
# -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
|
# -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
pass
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
|
Move code outside of exception
|
[FIX] Move code outside of exception
|
Python
|
agpl-3.0
|
rgbconsulting/rgb-pos,rgbconsulting/rgb-addons,rgbconsulting/rgb-pos,rgbconsulting/rgb-addons
|
# -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
[FIX] Move code outside of exception
|
# -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
pass
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
|
<commit_before># -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
<commit_msg>[FIX] Move code outside of exception<commit_after>
|
# -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
pass
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
|
# -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
[FIX] Move code outside of exception# -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
pass
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
|
<commit_before># -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
<commit_msg>[FIX] Move code outside of exception<commit_after># -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import time
from openerp import models, api
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PosPicking(models.Model):
_inherit = 'pos.order'
@api.multi
def create_picking(self):
try:
super(PosPicking, self).create_picking()
except:
pass
if self.picking_id.state != 'done':
for move in self.picking_id.move_lines:
if move.quant_ids:
# We pass this move to done because the quants were already moved
move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)})
else:
# If there are no moved quants we pass the move to Waiting Availability
move.do_unreserve()
return True
|
6807e5a5966f1f37f69a54e255a9981918cc8fb6
|
tests/test_cmd.py
|
tests/test_cmd.py
|
import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
client_secret = open("/tmp/client_secret.json", "w")
data = os.environ.get("CLIENT_SECRET")
client_secret.write(base64.b64decode(data))
client_secret.close()
def configure_settings(self):
from django.conf import settings
settings.configure(
DATABASES={
"default": {
"NAME": ":memory:",
"ENGINE": "django.db.backends.sqlite3",
"TEST": {
"NAME": ":memory:"
}
}
},
INSTALLED_APPS=(
"django.contrib.contenttypes",
"fusion_tables",
),
ROOT_URLCONF="tests.urls",
MODELS_TO_SYNC=("fusion_tables.SampleModel", ),
CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json",
LOCATION_FIELDS=("TextField", )
)
def run(self):
import django
from django.core.management import call_command
self.create_client_secret_file()
self.configure_settings()
django.setup()
call_command("test", "fusion_tables")
|
import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
client_secret = open("/tmp/client_secret.json", "w")
data = os.environ.get("CLIENT_SECRET").decode("utf-8")
client_secret.write(base64.b64decode(data))
client_secret.close()
def configure_settings(self):
from django.conf import settings
settings.configure(
DATABASES={
"default": {
"NAME": ":memory:",
"ENGINE": "django.db.backends.sqlite3",
"TEST": {
"NAME": ":memory:"
}
}
},
INSTALLED_APPS=(
"django.contrib.contenttypes",
"fusion_tables",
),
ROOT_URLCONF="tests.urls",
MODELS_TO_SYNC=("fusion_tables.SampleModel", ),
CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json",
LOCATION_FIELDS=("TextField", )
)
def run(self):
import django
from django.core.management import call_command
self.create_client_secret_file()
self.configure_settings()
django.setup()
call_command("test", "fusion_tables")
|
Fix unit test python3 compatibility.
|
Fix unit test python3 compatibility.
|
Python
|
mit
|
bsvetchine/django-fusion-tables
|
import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
client_secret = open("/tmp/client_secret.json", "w")
data = os.environ.get("CLIENT_SECRET")
client_secret.write(base64.b64decode(data))
client_secret.close()
def configure_settings(self):
from django.conf import settings
settings.configure(
DATABASES={
"default": {
"NAME": ":memory:",
"ENGINE": "django.db.backends.sqlite3",
"TEST": {
"NAME": ":memory:"
}
}
},
INSTALLED_APPS=(
"django.contrib.contenttypes",
"fusion_tables",
),
ROOT_URLCONF="tests.urls",
MODELS_TO_SYNC=("fusion_tables.SampleModel", ),
CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json",
LOCATION_FIELDS=("TextField", )
)
def run(self):
import django
from django.core.management import call_command
self.create_client_secret_file()
self.configure_settings()
django.setup()
call_command("test", "fusion_tables")
Fix unit test python3 compatibility.
|
import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
client_secret = open("/tmp/client_secret.json", "w")
data = os.environ.get("CLIENT_SECRET").decode("utf-8")
client_secret.write(base64.b64decode(data))
client_secret.close()
def configure_settings(self):
from django.conf import settings
settings.configure(
DATABASES={
"default": {
"NAME": ":memory:",
"ENGINE": "django.db.backends.sqlite3",
"TEST": {
"NAME": ":memory:"
}
}
},
INSTALLED_APPS=(
"django.contrib.contenttypes",
"fusion_tables",
),
ROOT_URLCONF="tests.urls",
MODELS_TO_SYNC=("fusion_tables.SampleModel", ),
CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json",
LOCATION_FIELDS=("TextField", )
)
def run(self):
import django
from django.core.management import call_command
self.create_client_secret_file()
self.configure_settings()
django.setup()
call_command("test", "fusion_tables")
|
<commit_before>import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
client_secret = open("/tmp/client_secret.json", "w")
data = os.environ.get("CLIENT_SECRET")
client_secret.write(base64.b64decode(data))
client_secret.close()
def configure_settings(self):
from django.conf import settings
settings.configure(
DATABASES={
"default": {
"NAME": ":memory:",
"ENGINE": "django.db.backends.sqlite3",
"TEST": {
"NAME": ":memory:"
}
}
},
INSTALLED_APPS=(
"django.contrib.contenttypes",
"fusion_tables",
),
ROOT_URLCONF="tests.urls",
MODELS_TO_SYNC=("fusion_tables.SampleModel", ),
CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json",
LOCATION_FIELDS=("TextField", )
)
def run(self):
import django
from django.core.management import call_command
self.create_client_secret_file()
self.configure_settings()
django.setup()
call_command("test", "fusion_tables")
<commit_msg>Fix unit test python3 compatibility.<commit_after>
|
import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
client_secret = open("/tmp/client_secret.json", "w")
data = os.environ.get("CLIENT_SECRET").decode("utf-8")
client_secret.write(base64.b64decode(data))
client_secret.close()
def configure_settings(self):
from django.conf import settings
settings.configure(
DATABASES={
"default": {
"NAME": ":memory:",
"ENGINE": "django.db.backends.sqlite3",
"TEST": {
"NAME": ":memory:"
}
}
},
INSTALLED_APPS=(
"django.contrib.contenttypes",
"fusion_tables",
),
ROOT_URLCONF="tests.urls",
MODELS_TO_SYNC=("fusion_tables.SampleModel", ),
CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json",
LOCATION_FIELDS=("TextField", )
)
def run(self):
import django
from django.core.management import call_command
self.create_client_secret_file()
self.configure_settings()
django.setup()
call_command("test", "fusion_tables")
|
import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
client_secret = open("/tmp/client_secret.json", "w")
data = os.environ.get("CLIENT_SECRET")
client_secret.write(base64.b64decode(data))
client_secret.close()
def configure_settings(self):
from django.conf import settings
settings.configure(
DATABASES={
"default": {
"NAME": ":memory:",
"ENGINE": "django.db.backends.sqlite3",
"TEST": {
"NAME": ":memory:"
}
}
},
INSTALLED_APPS=(
"django.contrib.contenttypes",
"fusion_tables",
),
ROOT_URLCONF="tests.urls",
MODELS_TO_SYNC=("fusion_tables.SampleModel", ),
CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json",
LOCATION_FIELDS=("TextField", )
)
def run(self):
import django
from django.core.management import call_command
self.create_client_secret_file()
self.configure_settings()
django.setup()
call_command("test", "fusion_tables")
Fix unit test python3 compatibility.import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
client_secret = open("/tmp/client_secret.json", "w")
data = os.environ.get("CLIENT_SECRET").decode("utf-8")
client_secret.write(base64.b64decode(data))
client_secret.close()
def configure_settings(self):
from django.conf import settings
settings.configure(
DATABASES={
"default": {
"NAME": ":memory:",
"ENGINE": "django.db.backends.sqlite3",
"TEST": {
"NAME": ":memory:"
}
}
},
INSTALLED_APPS=(
"django.contrib.contenttypes",
"fusion_tables",
),
ROOT_URLCONF="tests.urls",
MODELS_TO_SYNC=("fusion_tables.SampleModel", ),
CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json",
LOCATION_FIELDS=("TextField", )
)
def run(self):
import django
from django.core.management import call_command
self.create_client_secret_file()
self.configure_settings()
django.setup()
call_command("test", "fusion_tables")
|
<commit_before>import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
client_secret = open("/tmp/client_secret.json", "w")
data = os.environ.get("CLIENT_SECRET")
client_secret.write(base64.b64decode(data))
client_secret.close()
def configure_settings(self):
from django.conf import settings
settings.configure(
DATABASES={
"default": {
"NAME": ":memory:",
"ENGINE": "django.db.backends.sqlite3",
"TEST": {
"NAME": ":memory:"
}
}
},
INSTALLED_APPS=(
"django.contrib.contenttypes",
"fusion_tables",
),
ROOT_URLCONF="tests.urls",
MODELS_TO_SYNC=("fusion_tables.SampleModel", ),
CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json",
LOCATION_FIELDS=("TextField", )
)
def run(self):
import django
from django.core.management import call_command
self.create_client_secret_file()
self.configure_settings()
django.setup()
call_command("test", "fusion_tables")
<commit_msg>Fix unit test python3 compatibility.<commit_after>import base64
import os
from distutils.core import Command
class TestCommand(Command):
description = "Launch all tests under fusion_tables app"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def create_client_secret_file(self):
client_secret = open("/tmp/client_secret.json", "w")
data = os.environ.get("CLIENT_SECRET").decode("utf-8")
client_secret.write(base64.b64decode(data))
client_secret.close()
def configure_settings(self):
from django.conf import settings
settings.configure(
DATABASES={
"default": {
"NAME": ":memory:",
"ENGINE": "django.db.backends.sqlite3",
"TEST": {
"NAME": ":memory:"
}
}
},
INSTALLED_APPS=(
"django.contrib.contenttypes",
"fusion_tables",
),
ROOT_URLCONF="tests.urls",
MODELS_TO_SYNC=("fusion_tables.SampleModel", ),
CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json",
LOCATION_FIELDS=("TextField", )
)
def run(self):
import django
from django.core.management import call_command
self.create_client_secret_file()
self.configure_settings()
django.setup()
call_command("test", "fusion_tables")
|
5397cbd48ce149b5671dcd694d83467af84093dc
|
fantasyStocks/fantasyStocks/urls.py
|
fantasyStocks/fantasyStocks/urls.py
|
"""fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
|
"""fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/v1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
|
Add version to API URL
|
Add version to API URL
|
Python
|
apache-2.0
|
ddsnowboard/FantasyStocks,ddsnowboard/FantasyStocks,ddsnowboard/FantasyStocks
|
"""fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
Add version to API URL
|
"""fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/v1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
|
<commit_before>"""fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
<commit_msg>Add version to API URL<commit_after>
|
"""fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/v1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
|
"""fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
Add version to API URL"""fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/v1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
|
<commit_before>"""fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
<commit_msg>Add version to API URL<commit_after>"""fantasyStocks URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from stocks import stockUrls, views
from stocksApi import urls as apiUrls
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
urlpatterns = static(settings.STATIC_URL) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
url(r'^admin/', include(admin.site.urls), name="admin"),
url(r"^stocks/", include(stockUrls), name="stocks"),
url(r"^api/v1/", include(apiUrls), name="api"),
url(r"^$", RedirectView.as_view(url="stocks/", permanent=True), name="redirect")
]
|
1f50f159de11a6ff48ce9ce1a502e990228f8dc0
|
builtin_fns.py
|
builtin_fns.py
|
import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
|
import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
@builtin(["print", "$obj", "without", "newline"])
def print_wn(args, context):
print(args["obj"], end="")
return NULL
@builtin(["input"])
def input_builtin(args, context):
try:
return obj.String(input())
except (KeyboardInterrupt, EOFError):
return NULL
@builtin(["input", "with", "prompt", "$prompt"])
def input_prompt_builtin(args, context):
try:
return obj.String(input(args["prompt"]))
except (KeyboardInterrupt, EOFError):
return NULL
|
Add a few more builtins
|
Add a few more builtins
- print $obj without newline
- input
- input with prompt $prompt
|
Python
|
mit
|
Zac-Garby/pluto-lang
|
import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
Add a few more builtins
- print $obj without newline
- input
- input with prompt $prompt
|
import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
@builtin(["print", "$obj", "without", "newline"])
def print_wn(args, context):
print(args["obj"], end="")
return NULL
@builtin(["input"])
def input_builtin(args, context):
try:
return obj.String(input())
except (KeyboardInterrupt, EOFError):
return NULL
@builtin(["input", "with", "prompt", "$prompt"])
def input_prompt_builtin(args, context):
try:
return obj.String(input(args["prompt"]))
except (KeyboardInterrupt, EOFError):
return NULL
|
<commit_before>import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
<commit_msg>Add a few more builtins
- print $obj without newline
- input
- input with prompt $prompt<commit_after>
|
import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
@builtin(["print", "$obj", "without", "newline"])
def print_wn(args, context):
print(args["obj"], end="")
return NULL
@builtin(["input"])
def input_builtin(args, context):
try:
return obj.String(input())
except (KeyboardInterrupt, EOFError):
return NULL
@builtin(["input", "with", "prompt", "$prompt"])
def input_prompt_builtin(args, context):
try:
return obj.String(input(args["prompt"]))
except (KeyboardInterrupt, EOFError):
return NULL
|
import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
Add a few more builtins
- print $obj without newline
- input
- input with prompt $promptimport object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
@builtin(["print", "$obj", "without", "newline"])
def print_wn(args, context):
print(args["obj"], end="")
return NULL
@builtin(["input"])
def input_builtin(args, context):
try:
return obj.String(input())
except (KeyboardInterrupt, EOFError):
return NULL
@builtin(["input", "with", "prompt", "$prompt"])
def input_prompt_builtin(args, context):
try:
return obj.String(input(args["prompt"]))
except (KeyboardInterrupt, EOFError):
return NULL
|
<commit_before>import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
<commit_msg>Add a few more builtins
- print $obj without newline
- input
- input with prompt $prompt<commit_after>import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
@builtin(["print", "$obj", "without", "newline"])
def print_wn(args, context):
print(args["obj"], end="")
return NULL
@builtin(["input"])
def input_builtin(args, context):
try:
return obj.String(input())
except (KeyboardInterrupt, EOFError):
return NULL
@builtin(["input", "with", "prompt", "$prompt"])
def input_prompt_builtin(args, context):
try:
return obj.String(input(args["prompt"]))
except (KeyboardInterrupt, EOFError):
return NULL
|
fc66db188ecabbe21cea23c91a9e9b24bbf9d11e
|
bluebottle/homepage/views.py
|
bluebottle/homepage/views.py
|
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
|
from django.utils import translation
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
# Force requested language
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
|
Fix translations for homepage stats
|
Fix translations for homepage stats
|
Python
|
bsd-3-clause
|
jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
|
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
Fix translations for homepage stats
|
from django.utils import translation
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
# Force requested language
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
|
<commit_before>from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
<commit_msg>Fix translations for homepage stats<commit_after>
|
from django.utils import translation
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
# Force requested language
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
|
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
Fix translations for homepage statsfrom django.utils import translation
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
# Force requested language
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
|
<commit_before>from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
<commit_msg>Fix translations for homepage stats<commit_after>from django.utils import translation
from rest_framework import generics, response
from .models import HomePage
from .serializers import HomePageSerializer
# Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object
class HomePageDetail(generics.GenericAPIView):
serializer_class = HomePageSerializer
def get(self, request, language='en'):
# Force requested language
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
homepage = HomePage().get(language)
serialized = HomePageSerializer().to_native(homepage)
return response.Response(serialized)
|
b510b01b1a67ab5a606eefb251f6649d2b238ccc
|
yolk/__init__.py
|
yolk/__init__.py
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.2'
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.3'
|
Increment patch version to 0.7.3
|
Increment patch version to 0.7.3
|
Python
|
bsd-3-clause
|
myint/yolk,myint/yolk
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.2'
Increment patch version to 0.7.3
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.3'
|
<commit_before>"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.2'
<commit_msg>Increment patch version to 0.7.3<commit_after>
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.3'
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.2'
Increment patch version to 0.7.3"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.3'
|
<commit_before>"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.2'
<commit_msg>Increment patch version to 0.7.3<commit_after>"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.3'
|
7714816525547da48060cf45b699c91602fd5095
|
winrm/__init__.py
|
winrm/__init__.py
|
from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {}, out "{}", err "{}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
|
from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {0}, out "{1}", err "{2}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
|
Fix string formatting to work with python 2.6.
|
Fix string formatting to work with python 2.6.
|
Python
|
mit
|
luisfdez/pywinrm,max-orlov/pywinrm,diyan/pywinrm,luisfdez/pywinrm,GitHubFriction/pywinrm,GitHubFriction/pywinrm,cchurch/pywinrm,GitHubFriction/pywinrm,cchurch/pywinrm,cchurch/pywinrm,luisfdez/pywinrm,max-orlov/pywinrm,max-orlov/pywinrm
|
from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {}, out "{}", err "{}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rsFix string formatting to work with python 2.6.
|
from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {0}, out "{1}", err "{2}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
|
<commit_before>from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {}, out "{}", err "{}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs<commit_msg>Fix string formatting to work with python 2.6.<commit_after>
|
from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {0}, out "{1}", err "{2}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
|
from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {}, out "{}", err "{}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rsFix string formatting to work with python 2.6.from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {0}, out "{1}", err "{2}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
|
<commit_before>from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {}, out "{}", err "{}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs<commit_msg>Fix string formatting to work with python 2.6.<commit_after>from winrm.protocol import Protocol
class Response(object):
"""Response from a remote command execution"""
def __init__(self, args):
self.std_out, self.std_err, self.status_code = args
def __repr__(self):
#TODO put tree dots at the end if out/err was truncated
return '<Response code {0}, out "{1}", err "{2}">'.format(
self.status_code, self.std_out[:20], self.std_err[:20])
class Session(object):
#TODO implement context manager methods
def __init__(self, url, auth):
#TODO convert short urls into well-formed endpoint
username, password = auth
self.protocol = Protocol(url, username=username, password=password)
def run_cmd(self, command, args=()):
#TODO optimize perf. Do not call open/close shell every time
shell_id = self.protocol.open_shell()
command_id = self.protocol.run_command(shell_id, command, args)
rs = Response(self.protocol.get_command_output(shell_id, command_id))
self.protocol.cleanup_command(shell_id, command_id)
self.protocol.close_shell(shell_id)
return rs
|
1c51c772d4b21eba70cd09429e603f1873b2c13c
|
examples/demo.py
|
examples/demo.py
|
#!/usr/bin/env python
import pytaf
taf_str = """
TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001
TEMPO 2914/2915 1SM -BR CLR
FM291500 04006KT P6SM SKC
TEMPO 2915/2917 2SM BR OVC008
FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT
PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB
FM300100 31007KT P6SM SCT070 BKN120 +FC
FM300500 23006KT P6SM SCT120 $
"""
t = pytaf.TAF(taf_str)
d = pytaf.Decoder(t)
print taf_str
print
dec = d.decode_taf()
print dec
|
#!/usr/bin/env python
import pytaf
taf_str = """
TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001
TEMPO 2914/2915 1SM -BR CLR
FM291500 04006KT P6SM SKC
TEMPO 2915/2917 2SM BR OVC008
FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT
PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB
FM300100 31007KT P6SM SCT070 BKN120 +FC
FM300500 23006KT P6SM SCT120 $
"""
# Create a parsed TAF object from string
t = pytaf.TAF(taf_str)
# Create a decoder object from the TAF object
d = pytaf.Decoder(t)
# Print the raw string for the reference
print(taf_str)
# Decode and print the decoded string
dec = d.decode_taf()
print(dec)
|
Update the example script to work with python3.
|
Update the example script to work with python3.
|
Python
|
mit
|
dmbaturin/pytaf
|
#!/usr/bin/env python
import pytaf
taf_str = """
TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001
TEMPO 2914/2915 1SM -BR CLR
FM291500 04006KT P6SM SKC
TEMPO 2915/2917 2SM BR OVC008
FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT
PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB
FM300100 31007KT P6SM SCT070 BKN120 +FC
FM300500 23006KT P6SM SCT120 $
"""
t = pytaf.TAF(taf_str)
d = pytaf.Decoder(t)
print taf_str
print
dec = d.decode_taf()
print dec
Update the example script to work with python3.
|
#!/usr/bin/env python
import pytaf
taf_str = """
TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001
TEMPO 2914/2915 1SM -BR CLR
FM291500 04006KT P6SM SKC
TEMPO 2915/2917 2SM BR OVC008
FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT
PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB
FM300100 31007KT P6SM SCT070 BKN120 +FC
FM300500 23006KT P6SM SCT120 $
"""
# Create a parsed TAF object from string
t = pytaf.TAF(taf_str)
# Create a decoder object from the TAF object
d = pytaf.Decoder(t)
# Print the raw string for the reference
print(taf_str)
# Decode and print the decoded string
dec = d.decode_taf()
print(dec)
|
<commit_before>#!/usr/bin/env python
import pytaf
taf_str = """
TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001
TEMPO 2914/2915 1SM -BR CLR
FM291500 04006KT P6SM SKC
TEMPO 2915/2917 2SM BR OVC008
FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT
PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB
FM300100 31007KT P6SM SCT070 BKN120 +FC
FM300500 23006KT P6SM SCT120 $
"""
t = pytaf.TAF(taf_str)
d = pytaf.Decoder(t)
print taf_str
print
dec = d.decode_taf()
print dec
<commit_msg>Update the example script to work with python3.<commit_after>
|
#!/usr/bin/env python
import pytaf
taf_str = """
TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001
TEMPO 2914/2915 1SM -BR CLR
FM291500 04006KT P6SM SKC
TEMPO 2915/2917 2SM BR OVC008
FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT
PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB
FM300100 31007KT P6SM SCT070 BKN120 +FC
FM300500 23006KT P6SM SCT120 $
"""
# Create a parsed TAF object from string
t = pytaf.TAF(taf_str)
# Create a decoder object from the TAF object
d = pytaf.Decoder(t)
# Print the raw string for the reference
print(taf_str)
# Decode and print the decoded string
dec = d.decode_taf()
print(dec)
|
#!/usr/bin/env python
import pytaf
taf_str = """
TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001
TEMPO 2914/2915 1SM -BR CLR
FM291500 04006KT P6SM SKC
TEMPO 2915/2917 2SM BR OVC008
FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT
PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB
FM300100 31007KT P6SM SCT070 BKN120 +FC
FM300500 23006KT P6SM SCT120 $
"""
t = pytaf.TAF(taf_str)
d = pytaf.Decoder(t)
print taf_str
print
dec = d.decode_taf()
print dec
Update the example script to work with python3.#!/usr/bin/env python
import pytaf
taf_str = """
TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001
TEMPO 2914/2915 1SM -BR CLR
FM291500 04006KT P6SM SKC
TEMPO 2915/2917 2SM BR OVC008
FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT
PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB
FM300100 31007KT P6SM SCT070 BKN120 +FC
FM300500 23006KT P6SM SCT120 $
"""
# Create a parsed TAF object from string
t = pytaf.TAF(taf_str)
# Create a decoder object from the TAF object
d = pytaf.Decoder(t)
# Print the raw string for the reference
print(taf_str)
# Decode and print the decoded string
dec = d.decode_taf()
print(dec)
|
<commit_before>#!/usr/bin/env python
import pytaf
taf_str = """
TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001
TEMPO 2914/2915 1SM -BR CLR
FM291500 04006KT P6SM SKC
TEMPO 2915/2917 2SM BR OVC008
FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT
PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB
FM300100 31007KT P6SM SCT070 BKN120 +FC
FM300500 23006KT P6SM SCT120 $
"""
t = pytaf.TAF(taf_str)
d = pytaf.Decoder(t)
print taf_str
print
dec = d.decode_taf()
print dec
<commit_msg>Update the example script to work with python3.<commit_after>#!/usr/bin/env python
import pytaf
taf_str = """
TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001
TEMPO 2914/2915 1SM -BR CLR
FM291500 04006KT P6SM SKC
TEMPO 2915/2917 2SM BR OVC008
FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT
PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB
FM300100 31007KT P6SM SCT070 BKN120 +FC
FM300500 23006KT P6SM SCT120 $
"""
# Create a parsed TAF object from string
t = pytaf.TAF(taf_str)
# Create a decoder object from the TAF object
d = pytaf.Decoder(t)
# Print the raw string for the reference
print(taf_str)
# Decode and print the decoded string
dec = d.decode_taf()
print(dec)
|
8a70475983d973b5f9287d7a7c807c55994d3b70
|
aioriak/tests/test_kv.py
|
aioriak/tests/test_kv.py
|
from .base import IntegrationTest, AsyncUnitTestCase
class BasicKVTests(IntegrationTest, AsyncUnitTestCase):
def test_no_returnbody(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
o = await bucket.new(self.key_name, "bar")
await o.store(return_body=False)
self.assertEqual(o.vclock, None)
self.loop.run_until_complete(go())
def test_is_alive(self):
self.assertTrue(self.client.is_alive())
def test_store_and_get(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
rand = self.randint()
obj = await bucket.new('foo', rand)
await obj.store()
obj = await bucket.get('foo')
self.assertTrue(obj.exists)
self.assertEqual(obj.bucket.name, self.bucket_name)
self.assertEqual(obj.key, 'foo')
self.assertEqual(obj.data, rand)
obj2 = await bucket.new('baz', rand, 'application/json')
obj2.charset = 'UTF-8'
await obj2.store()
obj2 = await bucket.get('baz')
self.assertEqual(obj2.data, rand)
self.loop.run_until_complete(go())
|
from .base import IntegrationTest, AsyncUnitTestCase
class BasicKVTests(IntegrationTest, AsyncUnitTestCase):
def test_no_returnbody(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
o = await bucket.new(self.key_name, "bar")
await o.store(return_body=False)
self.assertEqual(o.vclock, None)
self.loop.run_until_complete(go())
def test_is_alive(self):
self.assertTrue(self.client.is_alive())
def test_store_and_get(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
rand = self.randint()
obj = await bucket.new('foo', rand)
await obj.store()
obj = await bucket.get('foo')
self.assertTrue(obj.exists)
self.assertEqual(obj.bucket.name, self.bucket_name)
self.assertEqual(obj.key, 'foo')
self.assertEqual(obj.data, rand)
obj2 = await bucket.new('baz', rand, 'application/json')
obj2.charset = 'UTF-8'
await obj2.store()
obj2 = await bucket.get('baz')
self.assertEqual(obj2.data, rand)
self.loop.run_until_complete(go())
def test_store_object_with_unicode(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
data = {'føø': u'éå'}
obj = await bucket.new('foo', data)
await obj.store()
obj = await bucket.get('foo')
self.assertEqual(obj.data, data)
self.loop.run_until_complete(go())
|
Add test store unicode object
|
Add test store unicode object
|
Python
|
mit
|
rambler-digital-solutions/aioriak
|
from .base import IntegrationTest, AsyncUnitTestCase
class BasicKVTests(IntegrationTest, AsyncUnitTestCase):
def test_no_returnbody(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
o = await bucket.new(self.key_name, "bar")
await o.store(return_body=False)
self.assertEqual(o.vclock, None)
self.loop.run_until_complete(go())
def test_is_alive(self):
self.assertTrue(self.client.is_alive())
def test_store_and_get(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
rand = self.randint()
obj = await bucket.new('foo', rand)
await obj.store()
obj = await bucket.get('foo')
self.assertTrue(obj.exists)
self.assertEqual(obj.bucket.name, self.bucket_name)
self.assertEqual(obj.key, 'foo')
self.assertEqual(obj.data, rand)
obj2 = await bucket.new('baz', rand, 'application/json')
obj2.charset = 'UTF-8'
await obj2.store()
obj2 = await bucket.get('baz')
self.assertEqual(obj2.data, rand)
self.loop.run_until_complete(go())
Add test store unicode object
|
from .base import IntegrationTest, AsyncUnitTestCase
class BasicKVTests(IntegrationTest, AsyncUnitTestCase):
def test_no_returnbody(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
o = await bucket.new(self.key_name, "bar")
await o.store(return_body=False)
self.assertEqual(o.vclock, None)
self.loop.run_until_complete(go())
def test_is_alive(self):
self.assertTrue(self.client.is_alive())
def test_store_and_get(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
rand = self.randint()
obj = await bucket.new('foo', rand)
await obj.store()
obj = await bucket.get('foo')
self.assertTrue(obj.exists)
self.assertEqual(obj.bucket.name, self.bucket_name)
self.assertEqual(obj.key, 'foo')
self.assertEqual(obj.data, rand)
obj2 = await bucket.new('baz', rand, 'application/json')
obj2.charset = 'UTF-8'
await obj2.store()
obj2 = await bucket.get('baz')
self.assertEqual(obj2.data, rand)
self.loop.run_until_complete(go())
def test_store_object_with_unicode(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
data = {'føø': u'éå'}
obj = await bucket.new('foo', data)
await obj.store()
obj = await bucket.get('foo')
self.assertEqual(obj.data, data)
self.loop.run_until_complete(go())
|
<commit_before>from .base import IntegrationTest, AsyncUnitTestCase
class BasicKVTests(IntegrationTest, AsyncUnitTestCase):
def test_no_returnbody(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
o = await bucket.new(self.key_name, "bar")
await o.store(return_body=False)
self.assertEqual(o.vclock, None)
self.loop.run_until_complete(go())
def test_is_alive(self):
self.assertTrue(self.client.is_alive())
def test_store_and_get(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
rand = self.randint()
obj = await bucket.new('foo', rand)
await obj.store()
obj = await bucket.get('foo')
self.assertTrue(obj.exists)
self.assertEqual(obj.bucket.name, self.bucket_name)
self.assertEqual(obj.key, 'foo')
self.assertEqual(obj.data, rand)
obj2 = await bucket.new('baz', rand, 'application/json')
obj2.charset = 'UTF-8'
await obj2.store()
obj2 = await bucket.get('baz')
self.assertEqual(obj2.data, rand)
self.loop.run_until_complete(go())
<commit_msg>Add test store unicode object<commit_after>
|
from .base import IntegrationTest, AsyncUnitTestCase
class BasicKVTests(IntegrationTest, AsyncUnitTestCase):
def test_no_returnbody(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
o = await bucket.new(self.key_name, "bar")
await o.store(return_body=False)
self.assertEqual(o.vclock, None)
self.loop.run_until_complete(go())
def test_is_alive(self):
self.assertTrue(self.client.is_alive())
def test_store_and_get(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
rand = self.randint()
obj = await bucket.new('foo', rand)
await obj.store()
obj = await bucket.get('foo')
self.assertTrue(obj.exists)
self.assertEqual(obj.bucket.name, self.bucket_name)
self.assertEqual(obj.key, 'foo')
self.assertEqual(obj.data, rand)
obj2 = await bucket.new('baz', rand, 'application/json')
obj2.charset = 'UTF-8'
await obj2.store()
obj2 = await bucket.get('baz')
self.assertEqual(obj2.data, rand)
self.loop.run_until_complete(go())
def test_store_object_with_unicode(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
data = {'føø': u'éå'}
obj = await bucket.new('foo', data)
await obj.store()
obj = await bucket.get('foo')
self.assertEqual(obj.data, data)
self.loop.run_until_complete(go())
|
from .base import IntegrationTest, AsyncUnitTestCase
class BasicKVTests(IntegrationTest, AsyncUnitTestCase):
def test_no_returnbody(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
o = await bucket.new(self.key_name, "bar")
await o.store(return_body=False)
self.assertEqual(o.vclock, None)
self.loop.run_until_complete(go())
def test_is_alive(self):
self.assertTrue(self.client.is_alive())
def test_store_and_get(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
rand = self.randint()
obj = await bucket.new('foo', rand)
await obj.store()
obj = await bucket.get('foo')
self.assertTrue(obj.exists)
self.assertEqual(obj.bucket.name, self.bucket_name)
self.assertEqual(obj.key, 'foo')
self.assertEqual(obj.data, rand)
obj2 = await bucket.new('baz', rand, 'application/json')
obj2.charset = 'UTF-8'
await obj2.store()
obj2 = await bucket.get('baz')
self.assertEqual(obj2.data, rand)
self.loop.run_until_complete(go())
Add test store unicode objectfrom .base import IntegrationTest, AsyncUnitTestCase
class BasicKVTests(IntegrationTest, AsyncUnitTestCase):
def test_no_returnbody(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
o = await bucket.new(self.key_name, "bar")
await o.store(return_body=False)
self.assertEqual(o.vclock, None)
self.loop.run_until_complete(go())
def test_is_alive(self):
self.assertTrue(self.client.is_alive())
def test_store_and_get(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
rand = self.randint()
obj = await bucket.new('foo', rand)
await obj.store()
obj = await bucket.get('foo')
self.assertTrue(obj.exists)
self.assertEqual(obj.bucket.name, self.bucket_name)
self.assertEqual(obj.key, 'foo')
self.assertEqual(obj.data, rand)
obj2 = await bucket.new('baz', rand, 'application/json')
obj2.charset = 'UTF-8'
await obj2.store()
obj2 = await bucket.get('baz')
self.assertEqual(obj2.data, rand)
self.loop.run_until_complete(go())
def test_store_object_with_unicode(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
data = {'føø': u'éå'}
obj = await bucket.new('foo', data)
await obj.store()
obj = await bucket.get('foo')
self.assertEqual(obj.data, data)
self.loop.run_until_complete(go())
|
<commit_before>from .base import IntegrationTest, AsyncUnitTestCase
class BasicKVTests(IntegrationTest, AsyncUnitTestCase):
def test_no_returnbody(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
o = await bucket.new(self.key_name, "bar")
await o.store(return_body=False)
self.assertEqual(o.vclock, None)
self.loop.run_until_complete(go())
def test_is_alive(self):
self.assertTrue(self.client.is_alive())
def test_store_and_get(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
rand = self.randint()
obj = await bucket.new('foo', rand)
await obj.store()
obj = await bucket.get('foo')
self.assertTrue(obj.exists)
self.assertEqual(obj.bucket.name, self.bucket_name)
self.assertEqual(obj.key, 'foo')
self.assertEqual(obj.data, rand)
obj2 = await bucket.new('baz', rand, 'application/json')
obj2.charset = 'UTF-8'
await obj2.store()
obj2 = await bucket.get('baz')
self.assertEqual(obj2.data, rand)
self.loop.run_until_complete(go())
<commit_msg>Add test store unicode object<commit_after>from .base import IntegrationTest, AsyncUnitTestCase
class BasicKVTests(IntegrationTest, AsyncUnitTestCase):
def test_no_returnbody(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
o = await bucket.new(self.key_name, "bar")
await o.store(return_body=False)
self.assertEqual(o.vclock, None)
self.loop.run_until_complete(go())
def test_is_alive(self):
self.assertTrue(self.client.is_alive())
def test_store_and_get(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
rand = self.randint()
obj = await bucket.new('foo', rand)
await obj.store()
obj = await bucket.get('foo')
self.assertTrue(obj.exists)
self.assertEqual(obj.bucket.name, self.bucket_name)
self.assertEqual(obj.key, 'foo')
self.assertEqual(obj.data, rand)
obj2 = await bucket.new('baz', rand, 'application/json')
obj2.charset = 'UTF-8'
await obj2.store()
obj2 = await bucket.get('baz')
self.assertEqual(obj2.data, rand)
self.loop.run_until_complete(go())
def test_store_object_with_unicode(self):
async def go():
bucket = self.client.bucket(self.bucket_name)
data = {'føø': u'éå'}
obj = await bucket.new('foo', data)
await obj.store()
obj = await bucket.get('foo')
self.assertEqual(obj.data, data)
self.loop.run_until_complete(go())
|
992a5a41580a520b330ec0fbbeba4e328924523a
|
tests/structures/test_list_comprehension.py
|
tests/structures/test_list_comprehension.py
|
from ..utils import TranspileTestCase
class ListComprehensionTests(TranspileTestCase):
def test_syntax(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print([v**2 for v in x])
print([v for v in x])
""")
def test_list_comprehension_with_if_condition(self):
self.assertCodeExecution("""
print([v for v in range(100) if v % 2 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0])
""")
def test_method(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print(list(v**2 for v in x))
""")
|
from ..utils import TranspileTestCase
class ListComprehensionTests(TranspileTestCase):
def test_syntax(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print([v**2 for v in x])
print([v for v in x])
""")
def test_list_comprehension_with_if_condition(self):
self.assertCodeExecution("""
print([v for v in range(100) if v % 2 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0 if v > 10 if v < 80])
""")
def test_method(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print(list(v**2 for v in x))
""")
|
Add a test for list comprehensions with more than two ifs
|
Add a test for list comprehensions with more than two ifs
|
Python
|
bsd-3-clause
|
freakboy3742/voc,cflee/voc,cflee/voc,freakboy3742/voc
|
from ..utils import TranspileTestCase
class ListComprehensionTests(TranspileTestCase):
def test_syntax(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print([v**2 for v in x])
print([v for v in x])
""")
def test_list_comprehension_with_if_condition(self):
self.assertCodeExecution("""
print([v for v in range(100) if v % 2 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0])
""")
def test_method(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print(list(v**2 for v in x))
""")
Add a test for list comprehensions with more than two ifs
|
from ..utils import TranspileTestCase
class ListComprehensionTests(TranspileTestCase):
def test_syntax(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print([v**2 for v in x])
print([v for v in x])
""")
def test_list_comprehension_with_if_condition(self):
self.assertCodeExecution("""
print([v for v in range(100) if v % 2 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0 if v > 10 if v < 80])
""")
def test_method(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print(list(v**2 for v in x))
""")
|
<commit_before>from ..utils import TranspileTestCase
class ListComprehensionTests(TranspileTestCase):
def test_syntax(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print([v**2 for v in x])
print([v for v in x])
""")
def test_list_comprehension_with_if_condition(self):
self.assertCodeExecution("""
print([v for v in range(100) if v % 2 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0])
""")
def test_method(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print(list(v**2 for v in x))
""")
<commit_msg>Add a test for list comprehensions with more than two ifs<commit_after>
|
from ..utils import TranspileTestCase
class ListComprehensionTests(TranspileTestCase):
def test_syntax(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print([v**2 for v in x])
print([v for v in x])
""")
def test_list_comprehension_with_if_condition(self):
self.assertCodeExecution("""
print([v for v in range(100) if v % 2 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0 if v > 10 if v < 80])
""")
def test_method(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print(list(v**2 for v in x))
""")
|
from ..utils import TranspileTestCase
class ListComprehensionTests(TranspileTestCase):
def test_syntax(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print([v**2 for v in x])
print([v for v in x])
""")
def test_list_comprehension_with_if_condition(self):
self.assertCodeExecution("""
print([v for v in range(100) if v % 2 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0])
""")
def test_method(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print(list(v**2 for v in x))
""")
Add a test for list comprehensions with more than two ifsfrom ..utils import TranspileTestCase
class ListComprehensionTests(TranspileTestCase):
def test_syntax(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print([v**2 for v in x])
print([v for v in x])
""")
def test_list_comprehension_with_if_condition(self):
self.assertCodeExecution("""
print([v for v in range(100) if v % 2 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0 if v > 10 if v < 80])
""")
def test_method(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print(list(v**2 for v in x))
""")
|
<commit_before>from ..utils import TranspileTestCase
class ListComprehensionTests(TranspileTestCase):
def test_syntax(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print([v**2 for v in x])
print([v for v in x])
""")
def test_list_comprehension_with_if_condition(self):
self.assertCodeExecution("""
print([v for v in range(100) if v % 2 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0])
""")
def test_method(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print(list(v**2 for v in x))
""")
<commit_msg>Add a test for list comprehensions with more than two ifs<commit_after>from ..utils import TranspileTestCase
class ListComprehensionTests(TranspileTestCase):
def test_syntax(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print([v**2 for v in x])
print([v for v in x])
""")
def test_list_comprehension_with_if_condition(self):
self.assertCodeExecution("""
print([v for v in range(100) if v % 2 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0])
print([v for v in range(100) if v % 2 == 0 if v % 3 == 0 if v > 10 if v < 80])
""")
def test_method(self):
self.assertCodeExecution("""
x = [1, 2, 3, 4, 5]
print(list(v**2 for v in x))
""")
|
f5b813b597e7dbc3d6ee3456ddb8318dacd1700b
|
wheresyourtrash/apps/notifications/tests.py
|
wheresyourtrash/apps/notifications/tests.py
|
import mock
import unittest
from django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
|
from django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
|
Remove unittest and mock for now
|
Remove unittest and mock for now
|
Python
|
bsd-3-clause
|
Code4Maine/wheresyourtrash,mainecivichackday/wheresyourtrash,mainecivichackday/wheresyourtrash,mainecivichackday/wheresyourtrash,mainecivichackday/wheresyourtrash,Code4Maine/wheresyourtrash,Code4Maine/wheresyourtrash,Code4Maine/wheresyourtrash
|
import mock
import unittest
from django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
Remove unittest and mock for now
|
from django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
|
<commit_before>import mock
import unittest
from django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
<commit_msg>Remove unittest and mock for now<commit_after>
|
from django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
|
import mock
import unittest
from django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
Remove unittest and mock for nowfrom django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
|
<commit_before>import mock
import unittest
from django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
<commit_msg>Remove unittest and mock for now<commit_after>from django.test import TestCase
from datetime import datetime, timedelta
from notifications.models import District, DistrictExceptions, Municipality
class DistrictTestCase(TestCase):
def setUp(self):
today = datetime.now()
m = Municipality.objects.create(state="ME", zipcode="04421",
name="Castine")
District.objects.create(municipality=m,
pickup_time="every monday",
district_type="TRASH")
def test_next_pickup_date_correct(self):
"""District property should return next date correctly"""
district = District.objects.get(district_type="TRASH")
today = datetime.now()
next_monday = today + timedelta(days=-today.weekday(), weeks=1)
self.assertEqual(district.next_pickup, next_monday.date())
DistrictExceptions.objects.create(district=district,
date=next_monday)
next_next_monday = next_monday + timedelta(days=-next_monday.weekday(),
weeks=1)
self.assertEqual(district.next_pickup, next_next_monday.date())
|
de731520f9ad3f871a976fd597ff1a4d8acf155f
|
tests/modules/test_enumerable.py
|
tests/modules/test_enumerable.py
|
class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert ec.space.w_true
|
class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert w_res is ec.space.w_true
def test_all_false(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 4
end
""")
assert w_res is ec.space.w_false
|
Fix true test, add false test
|
Fix true test, add false test
|
Python
|
bsd-3-clause
|
babelsberg/babelsberg-r,topazproject/topaz,topazproject/topaz,babelsberg/babelsberg-r,babelsberg/babelsberg-r,babelsberg/babelsberg-r,babelsberg/babelsberg-r,topazproject/topaz,kachick/topaz,kachick/topaz,topazproject/topaz,kachick/topaz
|
class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert ec.space.w_true
Fix true test, add false test
|
class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert w_res is ec.space.w_true
def test_all_false(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 4
end
""")
assert w_res is ec.space.w_false
|
<commit_before>class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert ec.space.w_true
<commit_msg>Fix true test, add false test<commit_after>
|
class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert w_res is ec.space.w_true
def test_all_false(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 4
end
""")
assert w_res is ec.space.w_false
|
class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert ec.space.w_true
Fix true test, add false testclass TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert w_res is ec.space.w_true
def test_all_false(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 4
end
""")
assert w_res is ec.space.w_false
|
<commit_before>class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert ec.space.w_true
<commit_msg>Fix true test, add false test<commit_after>class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n|
sum + n
end
""")
assert ec.space.int_w(w_res) == 45
def test_each_with_index(self, ec):
w_res = ec.space.execute(ec, """
result = []
(5..10).each_with_index do |n, idx|
result << [n, idx]
end
return result
""")
assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
def test_all(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 3
end
""")
assert w_res is ec.space.w_true
def test_all_false(self, ec):
w_res = ec.space.execute(ec, """
return ["ant", "bear", "cat"].all? do |word|
word.length >= 4
end
""")
assert w_res is ec.space.w_false
|
8324b45214dee9cd52c1c9bc85e6d10567dae6e1
|
plugins/join_on_invite/plugin.py
|
plugins/join_on_invite/plugin.py
|
class InviteJoinPlugin(object):
def __init__(self, cardinal):
cardinal.event_manager.register_callback("irc.invite", self.join_channel)
def join_channel(self, cardinal, user, channel):
cardinal.join(channel);
def setup(cardinal):
return InviteJoinPlugin(cardinal)
|
class InviteJoinPlugin(object):
"""Simple plugin that joins a channel if an invite is given."""
callback_id = None
"""ID generated when callback was added for the irc.invite event"""
def __init__(self, cardinal):
"""Register our callback and save the callback ID"""
self.callback_id = cardinal.event_manager.register_callback("irc.invite", self.join_channel)
def join_channel(self, cardinal, user, channel):
"""Callback for irc.invite that joins a channel"""
cardinal.join(channel);
def close(self, cardinal):
"""When the plugin is closed, removes our callback"""
cardinal.event_manager.remove_callback("irc.invite", self.callback_id)
def setup(cardinal):
return InviteJoinPlugin(cardinal)
|
Remove callback from join_on_invite during close()
|
Remove callback from join_on_invite during close()
|
Python
|
mit
|
BiohZn/Cardinal,JohnMaguire/Cardinal
|
class InviteJoinPlugin(object):
def __init__(self, cardinal):
cardinal.event_manager.register_callback("irc.invite", self.join_channel)
def join_channel(self, cardinal, user, channel):
cardinal.join(channel);
def setup(cardinal):
return InviteJoinPlugin(cardinal)
Remove callback from join_on_invite during close()
|
class InviteJoinPlugin(object):
"""Simple plugin that joins a channel if an invite is given."""
callback_id = None
"""ID generated when callback was added for the irc.invite event"""
def __init__(self, cardinal):
"""Register our callback and save the callback ID"""
self.callback_id = cardinal.event_manager.register_callback("irc.invite", self.join_channel)
def join_channel(self, cardinal, user, channel):
"""Callback for irc.invite that joins a channel"""
cardinal.join(channel);
def close(self, cardinal):
"""When the plugin is closed, removes our callback"""
cardinal.event_manager.remove_callback("irc.invite", self.callback_id)
def setup(cardinal):
return InviteJoinPlugin(cardinal)
|
<commit_before>class InviteJoinPlugin(object):
def __init__(self, cardinal):
cardinal.event_manager.register_callback("irc.invite", self.join_channel)
def join_channel(self, cardinal, user, channel):
cardinal.join(channel);
def setup(cardinal):
return InviteJoinPlugin(cardinal)
<commit_msg>Remove callback from join_on_invite during close()<commit_after>
|
class InviteJoinPlugin(object):
"""Simple plugin that joins a channel if an invite is given."""
callback_id = None
"""ID generated when callback was added for the irc.invite event"""
def __init__(self, cardinal):
"""Register our callback and save the callback ID"""
self.callback_id = cardinal.event_manager.register_callback("irc.invite", self.join_channel)
def join_channel(self, cardinal, user, channel):
"""Callback for irc.invite that joins a channel"""
cardinal.join(channel);
def close(self, cardinal):
"""When the plugin is closed, removes our callback"""
cardinal.event_manager.remove_callback("irc.invite", self.callback_id)
def setup(cardinal):
return InviteJoinPlugin(cardinal)
|
class InviteJoinPlugin(object):
def __init__(self, cardinal):
cardinal.event_manager.register_callback("irc.invite", self.join_channel)
def join_channel(self, cardinal, user, channel):
cardinal.join(channel);
def setup(cardinal):
return InviteJoinPlugin(cardinal)
Remove callback from join_on_invite during close()class InviteJoinPlugin(object):
"""Simple plugin that joins a channel if an invite is given."""
callback_id = None
"""ID generated when callback was added for the irc.invite event"""
def __init__(self, cardinal):
"""Register our callback and save the callback ID"""
self.callback_id = cardinal.event_manager.register_callback("irc.invite", self.join_channel)
def join_channel(self, cardinal, user, channel):
"""Callback for irc.invite that joins a channel"""
cardinal.join(channel);
def close(self, cardinal):
"""When the plugin is closed, removes our callback"""
cardinal.event_manager.remove_callback("irc.invite", self.callback_id)
def setup(cardinal):
return InviteJoinPlugin(cardinal)
|
<commit_before>class InviteJoinPlugin(object):
def __init__(self, cardinal):
cardinal.event_manager.register_callback("irc.invite", self.join_channel)
def join_channel(self, cardinal, user, channel):
cardinal.join(channel);
def setup(cardinal):
return InviteJoinPlugin(cardinal)
<commit_msg>Remove callback from join_on_invite during close()<commit_after>class InviteJoinPlugin(object):
"""Simple plugin that joins a channel if an invite is given."""
callback_id = None
"""ID generated when callback was added for the irc.invite event"""
def __init__(self, cardinal):
"""Register our callback and save the callback ID"""
self.callback_id = cardinal.event_manager.register_callback("irc.invite", self.join_channel)
def join_channel(self, cardinal, user, channel):
"""Callback for irc.invite that joins a channel"""
cardinal.join(channel);
def close(self, cardinal):
"""When the plugin is closed, removes our callback"""
cardinal.event_manager.remove_callback("irc.invite", self.callback_id)
def setup(cardinal):
return InviteJoinPlugin(cardinal)
|
ea42e8c61bddf614a5fc444b53eb38dcdcff88af
|
HotCIDR/hotcidr/ports.py
|
HotCIDR/hotcidr/ports.py
|
def parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
|
def parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
assert(isinstance(fromport, int))
assert(isinstance(toport, int))
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
|
Check that input to port is an integer
|
Check that input to port is an integer
|
Python
|
apache-2.0
|
ViaSat/hotcidr
|
def parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
Check that input to port is an integer
|
def parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
assert(isinstance(fromport, int))
assert(isinstance(toport, int))
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
|
<commit_before>def parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
<commit_msg>Check that input to port is an integer<commit_after>
|
def parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
assert(isinstance(fromport, int))
assert(isinstance(toport, int))
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
|
def parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
Check that input to port is an integerdef parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
assert(isinstance(fromport, int))
assert(isinstance(toport, int))
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
|
<commit_before>def parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
<commit_msg>Check that input to port is an integer<commit_after>def parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
assert(isinstance(fromport, int))
assert(isinstance(toport, int))
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
|
dc30ef09b024d035ed543c658bfe005d15330111
|
build/split.py
|
build/split.py
|
#!/usr/bin/env python2.7
import json
import os
import re
def main():
session_cells = {n: [] for n in range(1, 6+1)}
f = open(os.path.dirname(__file__) + '/../All.ipynb')
j = json.load(f)
cells = j['cells']
for cell in cells:
source = u''.join(cell['source'])
m = re.search(r'# +(\d+)\. ', source.strip())
if not m:
continue
n = int(m.group(1))
session_cells[n].append(cell)
for n, cells in sorted(session_cells.items()):
print 'Session {}: {} cells'.format(n, len(cells))
if __name__ == '__main__':
main()
|
#!/usr/bin/env python2.7
import json
import os
import re
def main():
session_cells = {n: [] for n in range(1, 6+1)}
f = open(os.path.dirname(__file__) + '/../All.ipynb')
j = json.load(f)
cells = j['cells']
for cell in cells:
source = u''.join(cell['source'])
m = re.search(r'# +(\d+)\. ', source.strip())
if not m:
continue
n = int(m.group(1))
session_cells[n].append(cell)
for n, cells in sorted(session_cells.items()):
print 'Session {}: {} cells'.format(n, len(cells))
def convert(filename):
f = open(os.path.dirname(__file__) + '/../' + filename)
j = json.load(f)
cells = j['cells']
n = 0
for cell in cells:
if cell['cell_type'] != 'code':
continue
source = u''.join(cell['source'])
if source.startswith('#'):
n += 1
print '{:6} {}'.format(n, filename)
#print cell
def main2():
for filename in 'Solutions-1.ipynb',:
convert(filename)
if __name__ == '__main__':
main2()
|
Switch to looking for separate solutions files
|
Switch to looking for separate solutions files
|
Python
|
mit
|
RobbieNesmith/PandasTutorial,Srisai85/pycon-pandas-tutorial,baomingTang/pycon-pandas-tutorial,ledrui/pycon-pandas-tutorial,wkuling/pycon-pandas-tutorial,deepesch/pycon-pandas-tutorial,baomingTang/pycon-pandas-tutorial,jainshailesh/pycon-pandas-tutorial,chrish42/pycon-pandas-tutorial,xy008areshsu/pycon-pandas-tutorial,ledrui/pycon-pandas-tutorial,sk-rai/Intro-to-Pandas,RobbieNesmith/PandasTutorial,chrish42/pycon-pandas-tutorial,xy008areshsu/pycon-pandas-tutorial,Srisai85/pycon-pandas-tutorial,brandon-rhodes/pycon-pandas-tutorial,willingc/pycon-pandas-tutorial,jaehyuk/pycon-pandas-tutorial,sk-rai/Intro-to-Pandas,deepesch/pycon-pandas-tutorial,brandon-rhodes/pycon-pandas-tutorial,jainshailesh/pycon-pandas-tutorial,wkuling/pycon-pandas-tutorial,jaehyuk/pycon-pandas-tutorial,jorgja02/pycon-pandas-tutorial,jorgja02/pycon-pandas-tutorial,willingc/pycon-pandas-tutorial
|
#!/usr/bin/env python2.7
import json
import os
import re
def main():
session_cells = {n: [] for n in range(1, 6+1)}
f = open(os.path.dirname(__file__) + '/../All.ipynb')
j = json.load(f)
cells = j['cells']
for cell in cells:
source = u''.join(cell['source'])
m = re.search(r'# +(\d+)\. ', source.strip())
if not m:
continue
n = int(m.group(1))
session_cells[n].append(cell)
for n, cells in sorted(session_cells.items()):
print 'Session {}: {} cells'.format(n, len(cells))
if __name__ == '__main__':
main()
Switch to looking for separate solutions files
|
#!/usr/bin/env python2.7
import json
import os
import re
def main():
session_cells = {n: [] for n in range(1, 6+1)}
f = open(os.path.dirname(__file__) + '/../All.ipynb')
j = json.load(f)
cells = j['cells']
for cell in cells:
source = u''.join(cell['source'])
m = re.search(r'# +(\d+)\. ', source.strip())
if not m:
continue
n = int(m.group(1))
session_cells[n].append(cell)
for n, cells in sorted(session_cells.items()):
print 'Session {}: {} cells'.format(n, len(cells))
def convert(filename):
f = open(os.path.dirname(__file__) + '/../' + filename)
j = json.load(f)
cells = j['cells']
n = 0
for cell in cells:
if cell['cell_type'] != 'code':
continue
source = u''.join(cell['source'])
if source.startswith('#'):
n += 1
print '{:6} {}'.format(n, filename)
#print cell
def main2():
for filename in 'Solutions-1.ipynb',:
convert(filename)
if __name__ == '__main__':
main2()
|
<commit_before>#!/usr/bin/env python2.7
import json
import os
import re
def main():
session_cells = {n: [] for n in range(1, 6+1)}
f = open(os.path.dirname(__file__) + '/../All.ipynb')
j = json.load(f)
cells = j['cells']
for cell in cells:
source = u''.join(cell['source'])
m = re.search(r'# +(\d+)\. ', source.strip())
if not m:
continue
n = int(m.group(1))
session_cells[n].append(cell)
for n, cells in sorted(session_cells.items()):
print 'Session {}: {} cells'.format(n, len(cells))
if __name__ == '__main__':
main()
<commit_msg>Switch to looking for separate solutions files<commit_after>
|
#!/usr/bin/env python2.7
import json
import os
import re
def main():
session_cells = {n: [] for n in range(1, 6+1)}
f = open(os.path.dirname(__file__) + '/../All.ipynb')
j = json.load(f)
cells = j['cells']
for cell in cells:
source = u''.join(cell['source'])
m = re.search(r'# +(\d+)\. ', source.strip())
if not m:
continue
n = int(m.group(1))
session_cells[n].append(cell)
for n, cells in sorted(session_cells.items()):
print 'Session {}: {} cells'.format(n, len(cells))
def convert(filename):
f = open(os.path.dirname(__file__) + '/../' + filename)
j = json.load(f)
cells = j['cells']
n = 0
for cell in cells:
if cell['cell_type'] != 'code':
continue
source = u''.join(cell['source'])
if source.startswith('#'):
n += 1
print '{:6} {}'.format(n, filename)
#print cell
def main2():
for filename in 'Solutions-1.ipynb',:
convert(filename)
if __name__ == '__main__':
main2()
|
#!/usr/bin/env python2.7
import json
import os
import re
def main():
session_cells = {n: [] for n in range(1, 6+1)}
f = open(os.path.dirname(__file__) + '/../All.ipynb')
j = json.load(f)
cells = j['cells']
for cell in cells:
source = u''.join(cell['source'])
m = re.search(r'# +(\d+)\. ', source.strip())
if not m:
continue
n = int(m.group(1))
session_cells[n].append(cell)
for n, cells in sorted(session_cells.items()):
print 'Session {}: {} cells'.format(n, len(cells))
if __name__ == '__main__':
main()
Switch to looking for separate solutions files#!/usr/bin/env python2.7
import json
import os
import re
def main():
session_cells = {n: [] for n in range(1, 6+1)}
f = open(os.path.dirname(__file__) + '/../All.ipynb')
j = json.load(f)
cells = j['cells']
for cell in cells:
source = u''.join(cell['source'])
m = re.search(r'# +(\d+)\. ', source.strip())
if not m:
continue
n = int(m.group(1))
session_cells[n].append(cell)
for n, cells in sorted(session_cells.items()):
print 'Session {}: {} cells'.format(n, len(cells))
def convert(filename):
f = open(os.path.dirname(__file__) + '/../' + filename)
j = json.load(f)
cells = j['cells']
n = 0
for cell in cells:
if cell['cell_type'] != 'code':
continue
source = u''.join(cell['source'])
if source.startswith('#'):
n += 1
print '{:6} {}'.format(n, filename)
#print cell
def main2():
for filename in 'Solutions-1.ipynb',:
convert(filename)
if __name__ == '__main__':
main2()
|
<commit_before>#!/usr/bin/env python2.7
import json
import os
import re
def main():
session_cells = {n: [] for n in range(1, 6+1)}
f = open(os.path.dirname(__file__) + '/../All.ipynb')
j = json.load(f)
cells = j['cells']
for cell in cells:
source = u''.join(cell['source'])
m = re.search(r'# +(\d+)\. ', source.strip())
if not m:
continue
n = int(m.group(1))
session_cells[n].append(cell)
for n, cells in sorted(session_cells.items()):
print 'Session {}: {} cells'.format(n, len(cells))
if __name__ == '__main__':
main()
<commit_msg>Switch to looking for separate solutions files<commit_after>#!/usr/bin/env python2.7
import json
import os
import re
def main():
session_cells = {n: [] for n in range(1, 6+1)}
f = open(os.path.dirname(__file__) + '/../All.ipynb')
j = json.load(f)
cells = j['cells']
for cell in cells:
source = u''.join(cell['source'])
m = re.search(r'# +(\d+)\. ', source.strip())
if not m:
continue
n = int(m.group(1))
session_cells[n].append(cell)
for n, cells in sorted(session_cells.items()):
print 'Session {}: {} cells'.format(n, len(cells))
def convert(filename):
f = open(os.path.dirname(__file__) + '/../' + filename)
j = json.load(f)
cells = j['cells']
n = 0
for cell in cells:
if cell['cell_type'] != 'code':
continue
source = u''.join(cell['source'])
if source.startswith('#'):
n += 1
print '{:6} {}'.format(n, filename)
#print cell
def main2():
for filename in 'Solutions-1.ipynb',:
convert(filename)
if __name__ == '__main__':
main2()
|
e6bacdb207bdedd854fceb49378bdea129004e49
|
bib.py
|
bib.py
|
import sqlite3
conn = sqlite3.connect('surfaces.db')
c = conn.cursor()
c.execute('''CREATE TABLE bibliography (
kdim INT,
pg INT,
q INT,
K2 INT,
chi INT,
e INT,
h11 INT,
sp INT,
ref TEXT
);
''')
rationalsurfaces = [(-1, 0, 0, "NULL", "NULL", "NULL", 0, 4, '''The projective plane, birational to the Hirzebruch surface $\\Sigma_{0} = \\mathbb{P}^{1} \\times \mathbb{P}^{1}$.''')]
for n in range(2,60):
rationalsurfaces.append((-1, 0, 0, "NULL", "NULL", "NULL", n, 4, "The Hirzebruch surface $\\Sigma_{" + str(n) + "}$."))
c.executemany("INSERT INTO bibliography VALUES (?,?,?,?,?,?,?,?,?)", rationalsurfaces)
c.close()
conn.commit()
|
import sqlite3
conn = sqlite3.connect('surfaces.db')
c = conn.cursor()
c.execute('''CREATE TABLE bibliography (
kdim INT,
pg INT,
q INT,
K2 INT,
chi INT,
e INT,
h11 INT,
sp INT,
ref TEXT
);
''')
rationalsurfaces = [(-1, 0, 0, 9, 3, 1, 0, 7, '''The projective plane, birational to the Hirzebruch surface $\\Sigma_{0} = \\mathbb{P}^{1} \\times \mathbb{P}^{1}$.''')]
for n in range(2,60):
h11 = n+1
e = n+3
K2 = 12 - e
rationalsurfaces.append((-1, 0, 0, K2, e, h11, n, 7, "The Hirzebruch surface $\\Sigma_{" + str(n) + "}$."))
c.executemany("INSERT INTO bibliography VALUES (?,?,?,?,?,?,?,?,?)", rationalsurfaces)
c.close()
conn.commit()
|
Add a bit more info about rational surfaces
|
Add a bit more info about rational surfaces
|
Python
|
unlicense
|
jcommelin/superficie-algebriche,jcommelin/superficie-algebriche
|
import sqlite3
conn = sqlite3.connect('surfaces.db')
c = conn.cursor()
c.execute('''CREATE TABLE bibliography (
kdim INT,
pg INT,
q INT,
K2 INT,
chi INT,
e INT,
h11 INT,
sp INT,
ref TEXT
);
''')
rationalsurfaces = [(-1, 0, 0, "NULL", "NULL", "NULL", 0, 4, '''The projective plane, birational to the Hirzebruch surface $\\Sigma_{0} = \\mathbb{P}^{1} \\times \mathbb{P}^{1}$.''')]
for n in range(2,60):
rationalsurfaces.append((-1, 0, 0, "NULL", "NULL", "NULL", n, 4, "The Hirzebruch surface $\\Sigma_{" + str(n) + "}$."))
c.executemany("INSERT INTO bibliography VALUES (?,?,?,?,?,?,?,?,?)", rationalsurfaces)
c.close()
conn.commit()
Add a bit more info about rational surfaces
|
import sqlite3
conn = sqlite3.connect('surfaces.db')
c = conn.cursor()
c.execute('''CREATE TABLE bibliography (
kdim INT,
pg INT,
q INT,
K2 INT,
chi INT,
e INT,
h11 INT,
sp INT,
ref TEXT
);
''')
rationalsurfaces = [(-1, 0, 0, 9, 3, 1, 0, 7, '''The projective plane, birational to the Hirzebruch surface $\\Sigma_{0} = \\mathbb{P}^{1} \\times \mathbb{P}^{1}$.''')]
for n in range(2,60):
h11 = n+1
e = n+3
K2 = 12 - e
rationalsurfaces.append((-1, 0, 0, K2, e, h11, n, 7, "The Hirzebruch surface $\\Sigma_{" + str(n) + "}$."))
c.executemany("INSERT INTO bibliography VALUES (?,?,?,?,?,?,?,?,?)", rationalsurfaces)
c.close()
conn.commit()
|
<commit_before>import sqlite3
conn = sqlite3.connect('surfaces.db')
c = conn.cursor()
c.execute('''CREATE TABLE bibliography (
kdim INT,
pg INT,
q INT,
K2 INT,
chi INT,
e INT,
h11 INT,
sp INT,
ref TEXT
);
''')
rationalsurfaces = [(-1, 0, 0, "NULL", "NULL", "NULL", 0, 4, '''The projective plane, birational to the Hirzebruch surface $\\Sigma_{0} = \\mathbb{P}^{1} \\times \mathbb{P}^{1}$.''')]
for n in range(2,60):
rationalsurfaces.append((-1, 0, 0, "NULL", "NULL", "NULL", n, 4, "The Hirzebruch surface $\\Sigma_{" + str(n) + "}$."))
c.executemany("INSERT INTO bibliography VALUES (?,?,?,?,?,?,?,?,?)", rationalsurfaces)
c.close()
conn.commit()
<commit_msg>Add a bit more info about rational surfaces<commit_after>
|
import sqlite3
conn = sqlite3.connect('surfaces.db')
c = conn.cursor()
c.execute('''CREATE TABLE bibliography (
kdim INT,
pg INT,
q INT,
K2 INT,
chi INT,
e INT,
h11 INT,
sp INT,
ref TEXT
);
''')
rationalsurfaces = [(-1, 0, 0, 9, 3, 1, 0, 7, '''The projective plane, birational to the Hirzebruch surface $\\Sigma_{0} = \\mathbb{P}^{1} \\times \mathbb{P}^{1}$.''')]
for n in range(2,60):
h11 = n+1
e = n+3
K2 = 12 - e
rationalsurfaces.append((-1, 0, 0, K2, e, h11, n, 7, "The Hirzebruch surface $\\Sigma_{" + str(n) + "}$."))
c.executemany("INSERT INTO bibliography VALUES (?,?,?,?,?,?,?,?,?)", rationalsurfaces)
c.close()
conn.commit()
|
import sqlite3
conn = sqlite3.connect('surfaces.db')
c = conn.cursor()
c.execute('''CREATE TABLE bibliography (
kdim INT,
pg INT,
q INT,
K2 INT,
chi INT,
e INT,
h11 INT,
sp INT,
ref TEXT
);
''')
rationalsurfaces = [(-1, 0, 0, "NULL", "NULL", "NULL", 0, 4, '''The projective plane, birational to the Hirzebruch surface $\\Sigma_{0} = \\mathbb{P}^{1} \\times \mathbb{P}^{1}$.''')]
for n in range(2,60):
rationalsurfaces.append((-1, 0, 0, "NULL", "NULL", "NULL", n, 4, "The Hirzebruch surface $\\Sigma_{" + str(n) + "}$."))
c.executemany("INSERT INTO bibliography VALUES (?,?,?,?,?,?,?,?,?)", rationalsurfaces)
c.close()
conn.commit()
Add a bit more info about rational surfacesimport sqlite3
conn = sqlite3.connect('surfaces.db')
c = conn.cursor()
c.execute('''CREATE TABLE bibliography (
kdim INT,
pg INT,
q INT,
K2 INT,
chi INT,
e INT,
h11 INT,
sp INT,
ref TEXT
);
''')
rationalsurfaces = [(-1, 0, 0, 9, 3, 1, 0, 7, '''The projective plane, birational to the Hirzebruch surface $\\Sigma_{0} = \\mathbb{P}^{1} \\times \mathbb{P}^{1}$.''')]
for n in range(2,60):
h11 = n+1
e = n+3
K2 = 12 - e
rationalsurfaces.append((-1, 0, 0, K2, e, h11, n, 7, "The Hirzebruch surface $\\Sigma_{" + str(n) + "}$."))
c.executemany("INSERT INTO bibliography VALUES (?,?,?,?,?,?,?,?,?)", rationalsurfaces)
c.close()
conn.commit()
|
<commit_before>import sqlite3
conn = sqlite3.connect('surfaces.db')
c = conn.cursor()
c.execute('''CREATE TABLE bibliography (
kdim INT,
pg INT,
q INT,
K2 INT,
chi INT,
e INT,
h11 INT,
sp INT,
ref TEXT
);
''')
rationalsurfaces = [(-1, 0, 0, "NULL", "NULL", "NULL", 0, 4, '''The projective plane, birational to the Hirzebruch surface $\\Sigma_{0} = \\mathbb{P}^{1} \\times \mathbb{P}^{1}$.''')]
for n in range(2,60):
rationalsurfaces.append((-1, 0, 0, "NULL", "NULL", "NULL", n, 4, "The Hirzebruch surface $\\Sigma_{" + str(n) + "}$."))
c.executemany("INSERT INTO bibliography VALUES (?,?,?,?,?,?,?,?,?)", rationalsurfaces)
c.close()
conn.commit()
<commit_msg>Add a bit more info about rational surfaces<commit_after>import sqlite3
conn = sqlite3.connect('surfaces.db')
c = conn.cursor()
c.execute('''CREATE TABLE bibliography (
kdim INT,
pg INT,
q INT,
K2 INT,
chi INT,
e INT,
h11 INT,
sp INT,
ref TEXT
);
''')
rationalsurfaces = [(-1, 0, 0, 9, 3, 1, 0, 7, '''The projective plane, birational to the Hirzebruch surface $\\Sigma_{0} = \\mathbb{P}^{1} \\times \mathbb{P}^{1}$.''')]
for n in range(2,60):
h11 = n+1
e = n+3
K2 = 12 - e
rationalsurfaces.append((-1, 0, 0, K2, e, h11, n, 7, "The Hirzebruch surface $\\Sigma_{" + str(n) + "}$."))
c.executemany("INSERT INTO bibliography VALUES (?,?,?,?,?,?,?,?,?)", rationalsurfaces)
c.close()
conn.commit()
|
e9f53219d305052e7bb74d82cd1a9166d3e7b2f2
|
bot.py
|
bot.py
|
#!/usr/bin/python
import sys
import asyncore
import logging
from irc import Bot
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
bot = Bot('localhost')
try:
bot.run()
asyncore.loop()
except KeyboardInterrupt:
bot.irc_command('QUIT', 'Bye :)')
sys.exit(0)
|
#!/usr/bin/python
import sys
import asyncore
import logging
from irc import Bot
from listener import Listener
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
bot = Bot('localhost')
listener = Listener()
def parse(line):
if line.startswith('@'):
target, line = line[1:].split(' ', 1)
else:
target = bot.config['channel']
bot.irc_command('PRIVMSG', target, line)
listener.add(parse)
try:
bot.run()
asyncore.loop()
except KeyboardInterrupt:
bot.irc_command('QUIT', 'Bye :)')
sys.exit(0)
|
Integrate listener and irc parts
|
Integrate listener and irc parts
|
Python
|
mit
|
adamcik/pycat,adamcik/pycat
|
#!/usr/bin/python
import sys
import asyncore
import logging
from irc import Bot
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
bot = Bot('localhost')
try:
bot.run()
asyncore.loop()
except KeyboardInterrupt:
bot.irc_command('QUIT', 'Bye :)')
sys.exit(0)
Integrate listener and irc parts
|
#!/usr/bin/python
import sys
import asyncore
import logging
from irc import Bot
from listener import Listener
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
bot = Bot('localhost')
listener = Listener()
def parse(line):
if line.startswith('@'):
target, line = line[1:].split(' ', 1)
else:
target = bot.config['channel']
bot.irc_command('PRIVMSG', target, line)
listener.add(parse)
try:
bot.run()
asyncore.loop()
except KeyboardInterrupt:
bot.irc_command('QUIT', 'Bye :)')
sys.exit(0)
|
<commit_before>#!/usr/bin/python
import sys
import asyncore
import logging
from irc import Bot
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
bot = Bot('localhost')
try:
bot.run()
asyncore.loop()
except KeyboardInterrupt:
bot.irc_command('QUIT', 'Bye :)')
sys.exit(0)
<commit_msg>Integrate listener and irc parts<commit_after>
|
#!/usr/bin/python
import sys
import asyncore
import logging
from irc import Bot
from listener import Listener
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
bot = Bot('localhost')
listener = Listener()
def parse(line):
if line.startswith('@'):
target, line = line[1:].split(' ', 1)
else:
target = bot.config['channel']
bot.irc_command('PRIVMSG', target, line)
listener.add(parse)
try:
bot.run()
asyncore.loop()
except KeyboardInterrupt:
bot.irc_command('QUIT', 'Bye :)')
sys.exit(0)
|
#!/usr/bin/python
import sys
import asyncore
import logging
from irc import Bot
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
bot = Bot('localhost')
try:
bot.run()
asyncore.loop()
except KeyboardInterrupt:
bot.irc_command('QUIT', 'Bye :)')
sys.exit(0)
Integrate listener and irc parts#!/usr/bin/python
import sys
import asyncore
import logging
from irc import Bot
from listener import Listener
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
bot = Bot('localhost')
listener = Listener()
def parse(line):
if line.startswith('@'):
target, line = line[1:].split(' ', 1)
else:
target = bot.config['channel']
bot.irc_command('PRIVMSG', target, line)
listener.add(parse)
try:
bot.run()
asyncore.loop()
except KeyboardInterrupt:
bot.irc_command('QUIT', 'Bye :)')
sys.exit(0)
|
<commit_before>#!/usr/bin/python
import sys
import asyncore
import logging
from irc import Bot
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
bot = Bot('localhost')
try:
bot.run()
asyncore.loop()
except KeyboardInterrupt:
bot.irc_command('QUIT', 'Bye :)')
sys.exit(0)
<commit_msg>Integrate listener and irc parts<commit_after>#!/usr/bin/python
import sys
import asyncore
import logging
from irc import Bot
from listener import Listener
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(message)s")
bot = Bot('localhost')
listener = Listener()
def parse(line):
if line.startswith('@'):
target, line = line[1:].split(' ', 1)
else:
target = bot.config['channel']
bot.irc_command('PRIVMSG', target, line)
listener.add(parse)
try:
bot.run()
asyncore.loop()
except KeyboardInterrupt:
bot.irc_command('QUIT', 'Bye :)')
sys.exit(0)
|
b292df611945e15a852db01d61e3b9004307a244
|
bot.py
|
bot.py
|
import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(21600) # 6 hours
|
import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(60) # 6 hours
#time.sleep(21600) # 6 hours
|
Speed up for a while
|
Speed up for a while
|
Python
|
mit
|
gregsabo/only_keep_one,gregsabo/only_keep_one
|
import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(21600) # 6 hours
Speed up for a while
|
import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(60) # 6 hours
#time.sleep(21600) # 6 hours
|
<commit_before>import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(21600) # 6 hours
<commit_msg>Speed up for a while<commit_after>
|
import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(60) # 6 hours
#time.sleep(21600) # 6 hours
|
import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(21600) # 6 hours
Speed up for a whileimport os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(60) # 6 hours
#time.sleep(21600) # 6 hours
|
<commit_before>import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(21600) # 6 hours
<commit_msg>Speed up for a while<commit_after>import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(60) # 6 hours
#time.sleep(21600) # 6 hours
|
2f4bd8b133a3c4db43c039d94a1ecb757f4f41a8
|
django_graphene_utils/mixins.py
|
django_graphene_utils/mixins.py
|
from .forms import ReduceMixinForm
__all__ = ['ReduceMixin']
"""
Mutation mixin to work with form applying the ReduceMixinForm
"""
class ReduceMixin(object):
def get_form_kwargs(self, root, args, context, info):
# ensure we can do it
assert issubclass(self._meta.form, ReduceMixinForm)
# get original keyword arguments
kwargs = super(ReduceMixin, self).get_form_kwargs(root, args, context, info)
# reduce the fields to the data we got in
kwargs['reduce_to'] = (kwargs.get('data', None) or {}).keys()
return kwargs
|
from .forms import ReduceMixinForm
__all__ = ['ReduceMixin']
"""
Mutation mixin to work with form applying the ReduceMixinForm
"""
class ReduceMixin(object):
def get_form_kwargs(self, root, args, context, info):
# ensure we can do it
assert issubclass(self._meta.form_class, ReduceMixinForm)
# get original keyword arguments
kwargs = super(ReduceMixin, self).get_form_kwargs(root, args, context, info)
# reduce the fields to the data we got in
kwargs['reduce_to'] = (kwargs.get('data', None) or {}).keys()
return kwargs
|
Fix critical error on ReduceMixin
|
Fix critical error on ReduceMixin
|
Python
|
mit
|
amille44420/django-graphene-utils
|
from .forms import ReduceMixinForm
__all__ = ['ReduceMixin']
"""
Mutation mixin to work with form applying the ReduceMixinForm
"""
class ReduceMixin(object):
def get_form_kwargs(self, root, args, context, info):
# ensure we can do it
assert issubclass(self._meta.form, ReduceMixinForm)
# get original keyword arguments
kwargs = super(ReduceMixin, self).get_form_kwargs(root, args, context, info)
# reduce the fields to the data we got in
kwargs['reduce_to'] = (kwargs.get('data', None) or {}).keys()
return kwargs
Fix critical error on ReduceMixin
|
from .forms import ReduceMixinForm
__all__ = ['ReduceMixin']
"""
Mutation mixin to work with form applying the ReduceMixinForm
"""
class ReduceMixin(object):
def get_form_kwargs(self, root, args, context, info):
# ensure we can do it
assert issubclass(self._meta.form_class, ReduceMixinForm)
# get original keyword arguments
kwargs = super(ReduceMixin, self).get_form_kwargs(root, args, context, info)
# reduce the fields to the data we got in
kwargs['reduce_to'] = (kwargs.get('data', None) or {}).keys()
return kwargs
|
<commit_before>from .forms import ReduceMixinForm
__all__ = ['ReduceMixin']
"""
Mutation mixin to work with form applying the ReduceMixinForm
"""
class ReduceMixin(object):
def get_form_kwargs(self, root, args, context, info):
# ensure we can do it
assert issubclass(self._meta.form, ReduceMixinForm)
# get original keyword arguments
kwargs = super(ReduceMixin, self).get_form_kwargs(root, args, context, info)
# reduce the fields to the data we got in
kwargs['reduce_to'] = (kwargs.get('data', None) or {}).keys()
return kwargs
<commit_msg>Fix critical error on ReduceMixin<commit_after>
|
from .forms import ReduceMixinForm
__all__ = ['ReduceMixin']
"""
Mutation mixin to work with form applying the ReduceMixinForm
"""
class ReduceMixin(object):
def get_form_kwargs(self, root, args, context, info):
# ensure we can do it
assert issubclass(self._meta.form_class, ReduceMixinForm)
# get original keyword arguments
kwargs = super(ReduceMixin, self).get_form_kwargs(root, args, context, info)
# reduce the fields to the data we got in
kwargs['reduce_to'] = (kwargs.get('data', None) or {}).keys()
return kwargs
|
from .forms import ReduceMixinForm
__all__ = ['ReduceMixin']
"""
Mutation mixin to work with form applying the ReduceMixinForm
"""
class ReduceMixin(object):
def get_form_kwargs(self, root, args, context, info):
# ensure we can do it
assert issubclass(self._meta.form, ReduceMixinForm)
# get original keyword arguments
kwargs = super(ReduceMixin, self).get_form_kwargs(root, args, context, info)
# reduce the fields to the data we got in
kwargs['reduce_to'] = (kwargs.get('data', None) or {}).keys()
return kwargs
Fix critical error on ReduceMixinfrom .forms import ReduceMixinForm
__all__ = ['ReduceMixin']
"""
Mutation mixin to work with form applying the ReduceMixinForm
"""
class ReduceMixin(object):
def get_form_kwargs(self, root, args, context, info):
# ensure we can do it
assert issubclass(self._meta.form_class, ReduceMixinForm)
# get original keyword arguments
kwargs = super(ReduceMixin, self).get_form_kwargs(root, args, context, info)
# reduce the fields to the data we got in
kwargs['reduce_to'] = (kwargs.get('data', None) or {}).keys()
return kwargs
|
<commit_before>from .forms import ReduceMixinForm
__all__ = ['ReduceMixin']
"""
Mutation mixin to work with form applying the ReduceMixinForm
"""
class ReduceMixin(object):
def get_form_kwargs(self, root, args, context, info):
# ensure we can do it
assert issubclass(self._meta.form, ReduceMixinForm)
# get original keyword arguments
kwargs = super(ReduceMixin, self).get_form_kwargs(root, args, context, info)
# reduce the fields to the data we got in
kwargs['reduce_to'] = (kwargs.get('data', None) or {}).keys()
return kwargs
<commit_msg>Fix critical error on ReduceMixin<commit_after>from .forms import ReduceMixinForm
__all__ = ['ReduceMixin']
"""
Mutation mixin to work with form applying the ReduceMixinForm
"""
class ReduceMixin(object):
def get_form_kwargs(self, root, args, context, info):
# ensure we can do it
assert issubclass(self._meta.form_class, ReduceMixinForm)
# get original keyword arguments
kwargs = super(ReduceMixin, self).get_form_kwargs(root, args, context, info)
# reduce the fields to the data we got in
kwargs['reduce_to'] = (kwargs.get('data', None) or {}).keys()
return kwargs
|
6032fb8eb10a2f6be28142c7473e03b4bc349c7c
|
partitions/registry.py
|
partitions/registry.py
|
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions[key].update({app_model: expression})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
|
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions.update({
key: {
app_model: expression
}
})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
|
Use update instead of setting key directly
|
Use update instead of setting key directly
|
Python
|
bsd-3-clause
|
eldarion/django-partitions
|
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions[key].update({app_model: expression})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
Use update instead of setting key directly
|
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions.update({
key: {
app_model: expression
}
})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
|
<commit_before>from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions[key].update({app_model: expression})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
<commit_msg>Use update instead of setting key directly<commit_after>
|
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions.update({
key: {
app_model: expression
}
})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
|
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions[key].update({app_model: expression})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
Use update instead of setting key directlyfrom django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions.update({
key: {
app_model: expression
}
})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
|
<commit_before>from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions[key].update({app_model: expression})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
<commit_msg>Use update instead of setting key directly<commit_after>from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions.update({
key: {
app_model: expression
}
})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
|
abf2f4209f8adf06bef624e9d0a188eba39c2c7a
|
cinch/lexer.py
|
cinch/lexer.py
|
# This is the lexer. We could build a state machine which would parse
# each token character by character, but the point of this project is to
# be as simple as possible, so we will literally just split the string on
# spaces, scrub all newlines, and filter out any empty strings
def lex(source):
"""Lex the source code. Split on spaces, strip newlines, and filter out
empty strings"""
return filter(lambda s: s != '',
map(lambda x: x.strip(), source.split(' ')))
|
import re
# This is the lexer. We could build a state machine which would parse
# each token character by character, but the point of this project is to
# be as simple as possible, so we will literally just split the string on
# spaces, scrub all newlines, and filter out any empty strings
def lex(source):
"""Lex the source code. Split on spaces, strip newlines, and filter out
empty strings"""
# Strip comments from source code.
source = re.sub('#.*$', '', source)
return filter(lambda s: s != '',
map(lambda x: x.strip(), source.split(' ')))
|
Remove comments as part of lexing
|
Remove comments as part of lexing
|
Python
|
mit
|
iankronquist/cinch-lang,tschuy/cinch-lang
|
# This is the lexer. We could build a state machine which would parse
# each token character by character, but the point of this project is to
# be as simple as possible, so we will literally just split the string on
# spaces, scrub all newlines, and filter out any empty strings
def lex(source):
"""Lex the source code. Split on spaces, strip newlines, and filter out
empty strings"""
return filter(lambda s: s != '',
map(lambda x: x.strip(), source.split(' ')))
Remove comments as part of lexing
|
import re
# This is the lexer. We could build a state machine which would parse
# each token character by character, but the point of this project is to
# be as simple as possible, so we will literally just split the string on
# spaces, scrub all newlines, and filter out any empty strings
def lex(source):
"""Lex the source code. Split on spaces, strip newlines, and filter out
empty strings"""
# Strip comments from source code.
source = re.sub('#.*$', '', source)
return filter(lambda s: s != '',
map(lambda x: x.strip(), source.split(' ')))
|
<commit_before># This is the lexer. We could build a state machine which would parse
# each token character by character, but the point of this project is to
# be as simple as possible, so we will literally just split the string on
# spaces, scrub all newlines, and filter out any empty strings
def lex(source):
"""Lex the source code. Split on spaces, strip newlines, and filter out
empty strings"""
return filter(lambda s: s != '',
map(lambda x: x.strip(), source.split(' ')))
<commit_msg>Remove comments as part of lexing<commit_after>
|
import re
# This is the lexer. We could build a state machine which would parse
# each token character by character, but the point of this project is to
# be as simple as possible, so we will literally just split the string on
# spaces, scrub all newlines, and filter out any empty strings
def lex(source):
"""Lex the source code. Split on spaces, strip newlines, and filter out
empty strings"""
# Strip comments from source code.
source = re.sub('#.*$', '', source)
return filter(lambda s: s != '',
map(lambda x: x.strip(), source.split(' ')))
|
# This is the lexer. We could build a state machine which would parse
# each token character by character, but the point of this project is to
# be as simple as possible, so we will literally just split the string on
# spaces, scrub all newlines, and filter out any empty strings
def lex(source):
"""Lex the source code. Split on spaces, strip newlines, and filter out
empty strings"""
return filter(lambda s: s != '',
map(lambda x: x.strip(), source.split(' ')))
Remove comments as part of lexingimport re
# This is the lexer. We could build a state machine which would parse
# each token character by character, but the point of this project is to
# be as simple as possible, so we will literally just split the string on
# spaces, scrub all newlines, and filter out any empty strings
def lex(source):
"""Lex the source code. Split on spaces, strip newlines, and filter out
empty strings"""
# Strip comments from source code.
source = re.sub('#.*$', '', source)
return filter(lambda s: s != '',
map(lambda x: x.strip(), source.split(' ')))
|
<commit_before># This is the lexer. We could build a state machine which would parse
# each token character by character, but the point of this project is to
# be as simple as possible, so we will literally just split the string on
# spaces, scrub all newlines, and filter out any empty strings
def lex(source):
"""Lex the source code. Split on spaces, strip newlines, and filter out
empty strings"""
return filter(lambda s: s != '',
map(lambda x: x.strip(), source.split(' ')))
<commit_msg>Remove comments as part of lexing<commit_after>import re
# This is the lexer. We could build a state machine which would parse
# each token character by character, but the point of this project is to
# be as simple as possible, so we will literally just split the string on
# spaces, scrub all newlines, and filter out any empty strings
def lex(source):
"""Lex the source code. Split on spaces, strip newlines, and filter out
empty strings"""
# Strip comments from source code.
source = re.sub('#.*$', '', source)
return filter(lambda s: s != '',
map(lambda x: x.strip(), source.split(' ')))
|
b51e4e7af7065a487f5ee91697fda8848c209faf
|
libpasteurize/fixes/fix_newstyle.py
|
libpasteurize/fixes/fix_newstyle.py
|
u"""
Fixer for "class Foo: ..." -> "class Foo(object): ..."
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import LParen, RParen, Name
from libfuturize.fixer_util import touch_import_top
def insert_object(node, idx):
node.insert_child(idx, RParen())
node.insert_child(idx, Name(u"object"))
node.insert_child(idx, LParen())
class FixNewstyle(fixer_base.BaseFix):
PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >"
def transform(self, node, results):
colon = results[u"colon"]
idx = node.children.index(colon)
insert_object(node, idx)
touch_import_top(u'future.builtins', 'object', node)
|
u"""
Fixer for "class Foo: ..." -> "class Foo(object): ..."
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import LParen, RParen, Name
from libfuturize.fixer_util import touch_import_top
def insert_object(node, idx):
node.insert_child(idx, RParen())
node.insert_child(idx, Name(u"object"))
node.insert_child(idx, LParen())
class FixNewstyle(fixer_base.BaseFix):
# Match:
# class Blah:
# and:
# class Blah():
PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >"
def transform(self, node, results):
colon = results[u"colon"]
idx = node.children.index(colon)
if (node.children[idx-2].value == '(' and
node.children[idx-1].value == ')'):
del node.children[idx-2:idx]
idx -= 2
insert_object(node, idx)
touch_import_top(u'future.builtins', 'object', node)
|
Generalize fixer for old->new-style classes to accept "class C():"
|
Generalize fixer for old->new-style classes to accept "class C():"
|
Python
|
mit
|
michaelpacer/python-future,PythonCharmers/python-future,QuLogic/python-future,krischer/python-future,michaelpacer/python-future,PythonCharmers/python-future,QuLogic/python-future,krischer/python-future
|
u"""
Fixer for "class Foo: ..." -> "class Foo(object): ..."
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import LParen, RParen, Name
from libfuturize.fixer_util import touch_import_top
def insert_object(node, idx):
node.insert_child(idx, RParen())
node.insert_child(idx, Name(u"object"))
node.insert_child(idx, LParen())
class FixNewstyle(fixer_base.BaseFix):
PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >"
def transform(self, node, results):
colon = results[u"colon"]
idx = node.children.index(colon)
insert_object(node, idx)
touch_import_top(u'future.builtins', 'object', node)
Generalize fixer for old->new-style classes to accept "class C():"
|
u"""
Fixer for "class Foo: ..." -> "class Foo(object): ..."
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import LParen, RParen, Name
from libfuturize.fixer_util import touch_import_top
def insert_object(node, idx):
node.insert_child(idx, RParen())
node.insert_child(idx, Name(u"object"))
node.insert_child(idx, LParen())
class FixNewstyle(fixer_base.BaseFix):
# Match:
# class Blah:
# and:
# class Blah():
PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >"
def transform(self, node, results):
colon = results[u"colon"]
idx = node.children.index(colon)
if (node.children[idx-2].value == '(' and
node.children[idx-1].value == ')'):
del node.children[idx-2:idx]
idx -= 2
insert_object(node, idx)
touch_import_top(u'future.builtins', 'object', node)
|
<commit_before>u"""
Fixer for "class Foo: ..." -> "class Foo(object): ..."
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import LParen, RParen, Name
from libfuturize.fixer_util import touch_import_top
def insert_object(node, idx):
node.insert_child(idx, RParen())
node.insert_child(idx, Name(u"object"))
node.insert_child(idx, LParen())
class FixNewstyle(fixer_base.BaseFix):
PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >"
def transform(self, node, results):
colon = results[u"colon"]
idx = node.children.index(colon)
insert_object(node, idx)
touch_import_top(u'future.builtins', 'object', node)
<commit_msg>Generalize fixer for old->new-style classes to accept "class C():"<commit_after>
|
u"""
Fixer for "class Foo: ..." -> "class Foo(object): ..."
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import LParen, RParen, Name
from libfuturize.fixer_util import touch_import_top
def insert_object(node, idx):
node.insert_child(idx, RParen())
node.insert_child(idx, Name(u"object"))
node.insert_child(idx, LParen())
class FixNewstyle(fixer_base.BaseFix):
# Match:
# class Blah:
# and:
# class Blah():
PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >"
def transform(self, node, results):
colon = results[u"colon"]
idx = node.children.index(colon)
if (node.children[idx-2].value == '(' and
node.children[idx-1].value == ')'):
del node.children[idx-2:idx]
idx -= 2
insert_object(node, idx)
touch_import_top(u'future.builtins', 'object', node)
|
u"""
Fixer for "class Foo: ..." -> "class Foo(object): ..."
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import LParen, RParen, Name
from libfuturize.fixer_util import touch_import_top
def insert_object(node, idx):
node.insert_child(idx, RParen())
node.insert_child(idx, Name(u"object"))
node.insert_child(idx, LParen())
class FixNewstyle(fixer_base.BaseFix):
PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >"
def transform(self, node, results):
colon = results[u"colon"]
idx = node.children.index(colon)
insert_object(node, idx)
touch_import_top(u'future.builtins', 'object', node)
Generalize fixer for old->new-style classes to accept "class C():"u"""
Fixer for "class Foo: ..." -> "class Foo(object): ..."
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import LParen, RParen, Name
from libfuturize.fixer_util import touch_import_top
def insert_object(node, idx):
node.insert_child(idx, RParen())
node.insert_child(idx, Name(u"object"))
node.insert_child(idx, LParen())
class FixNewstyle(fixer_base.BaseFix):
# Match:
# class Blah:
# and:
# class Blah():
PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >"
def transform(self, node, results):
colon = results[u"colon"]
idx = node.children.index(colon)
if (node.children[idx-2].value == '(' and
node.children[idx-1].value == ')'):
del node.children[idx-2:idx]
idx -= 2
insert_object(node, idx)
touch_import_top(u'future.builtins', 'object', node)
|
<commit_before>u"""
Fixer for "class Foo: ..." -> "class Foo(object): ..."
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import LParen, RParen, Name
from libfuturize.fixer_util import touch_import_top
def insert_object(node, idx):
node.insert_child(idx, RParen())
node.insert_child(idx, Name(u"object"))
node.insert_child(idx, LParen())
class FixNewstyle(fixer_base.BaseFix):
PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >"
def transform(self, node, results):
colon = results[u"colon"]
idx = node.children.index(colon)
insert_object(node, idx)
touch_import_top(u'future.builtins', 'object', node)
<commit_msg>Generalize fixer for old->new-style classes to accept "class C():"<commit_after>u"""
Fixer for "class Foo: ..." -> "class Foo(object): ..."
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import LParen, RParen, Name
from libfuturize.fixer_util import touch_import_top
def insert_object(node, idx):
node.insert_child(idx, RParen())
node.insert_child(idx, Name(u"object"))
node.insert_child(idx, LParen())
class FixNewstyle(fixer_base.BaseFix):
# Match:
# class Blah:
# and:
# class Blah():
PATTERN = u"classdef< 'class' NAME ['(' ')'] colon=':' any >"
def transform(self, node, results):
colon = results[u"colon"]
idx = node.children.index(colon)
if (node.children[idx-2].value == '(' and
node.children[idx-1].value == ')'):
del node.children[idx-2:idx]
idx -= 2
insert_object(node, idx)
touch_import_top(u'future.builtins', 'object', node)
|
5c12b0c04b25e414b1bd04250cde0c3b1f869104
|
hr_emergency_contact/models/hr_employee.py
|
hr_emergency_contact/models/hr_employee.py
|
# -*- coding: utf-8 -*-
# © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com>
# © 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class HrEmployee(models.Model):
_name = 'hr.employee'
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
|
# -*- coding: utf-8 -*-
# © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com>
# © 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class HrEmployee(models.Model):
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
|
Remove _name attribute on hr.employee
|
Remove _name attribute on hr.employee
|
Python
|
agpl-3.0
|
VitalPet/hr,thinkopensolutions/hr,VitalPet/hr,xpansa/hr,Eficent/hr,Eficent/hr,feketemihai/hr,feketemihai/hr,acsone/hr,open-synergy/hr,open-synergy/hr,xpansa/hr,acsone/hr,thinkopensolutions/hr
|
# -*- coding: utf-8 -*-
# © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com>
# © 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class HrEmployee(models.Model):
_name = 'hr.employee'
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
Remove _name attribute on hr.employee
|
# -*- coding: utf-8 -*-
# © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com>
# © 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class HrEmployee(models.Model):
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
|
<commit_before># -*- coding: utf-8 -*-
# © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com>
# © 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class HrEmployee(models.Model):
_name = 'hr.employee'
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
<commit_msg>Remove _name attribute on hr.employee<commit_after>
|
# -*- coding: utf-8 -*-
# © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com>
# © 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class HrEmployee(models.Model):
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
|
# -*- coding: utf-8 -*-
# © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com>
# © 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class HrEmployee(models.Model):
_name = 'hr.employee'
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
Remove _name attribute on hr.employee# -*- coding: utf-8 -*-
# © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com>
# © 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class HrEmployee(models.Model):
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
|
<commit_before># -*- coding: utf-8 -*-
# © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com>
# © 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class HrEmployee(models.Model):
_name = 'hr.employee'
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
<commit_msg>Remove _name attribute on hr.employee<commit_after># -*- coding: utf-8 -*-
# © 2011 Michael Telahun Makonnen <mmakonnen@gmail.com>
# © 2016 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields
class HrEmployee(models.Model):
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
|
7b4f69971684bf2c5abfa50876583eb7c640bdac
|
kuulemma/views/feedback.py
|
kuulemma/views/feedback.py
|
from flask import Blueprint, abort, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
|
from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
|
Fix order of imports to comply with isort
|
Fix order of imports to comply with isort
|
Python
|
agpl-3.0
|
City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma
|
from flask import Blueprint, abort, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
Fix order of imports to comply with isort
|
from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
|
<commit_before>from flask import Blueprint, abort, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
<commit_msg>Fix order of imports to comply with isort<commit_after>
|
from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
|
from flask import Blueprint, abort, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
Fix order of imports to comply with isortfrom flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
|
<commit_before>from flask import Blueprint, abort, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
<commit_msg>Fix order of imports to comply with isort<commit_after>from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
|
43cc10fff32ef98522ba100da34816049908abb7
|
zeus/api/resources/auth_index.py
|
zeus/api/resources/auth_index.py
|
from flask import session
from zeus import auth
from zeus.models import Identity, User
from .base import Resource
from ..schemas import IdentitySchema, UserSchema
user_schema = UserSchema(strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
if session.get('uid'):
user = User.query.get(session['uid'])
if user is None:
session.clear()
else:
user = None
if user is None:
context = {
'isAuthenticated': False,
'user': None,
'identities': [],
}
else:
identity_list = list(Identity.query.filter(
Identity.user_id == user.id,
))
context = {
'isAuthenticated': True,
'user': user_schema.dump(user).data,
'identities': identities_schema.dump(identity_list).data,
}
return context
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
|
from flask import session
from zeus import auth
from zeus.models import Email, Identity, User
from .base import Resource
from ..schemas import EmailSchema, IdentitySchema, UserSchema
emails_schema = EmailSchema(many=True, strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
user_schema = UserSchema(strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
if session.get('uid'):
user = User.query.get(session['uid'])
if user is None:
session.clear()
else:
user = None
if user is None:
context = {
'isAuthenticated': False,
}
else:
identity_list = list(Identity.query.filter(
Identity.user_id == user.id,
))
email_list = list(Email.query.filter(
Email.user_id == user.id,
))
context = {
'isAuthenticated': True,
'user': user_schema.dump(user).data,
'emails': emails_schema.dump(email_list).data,
'identities': identities_schema.dump(identity_list).data,
}
return context
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
|
Add emails to auth details
|
Add emails to auth details
|
Python
|
apache-2.0
|
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
|
from flask import session
from zeus import auth
from zeus.models import Identity, User
from .base import Resource
from ..schemas import IdentitySchema, UserSchema
user_schema = UserSchema(strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
if session.get('uid'):
user = User.query.get(session['uid'])
if user is None:
session.clear()
else:
user = None
if user is None:
context = {
'isAuthenticated': False,
'user': None,
'identities': [],
}
else:
identity_list = list(Identity.query.filter(
Identity.user_id == user.id,
))
context = {
'isAuthenticated': True,
'user': user_schema.dump(user).data,
'identities': identities_schema.dump(identity_list).data,
}
return context
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
Add emails to auth details
|
from flask import session
from zeus import auth
from zeus.models import Email, Identity, User
from .base import Resource
from ..schemas import EmailSchema, IdentitySchema, UserSchema
emails_schema = EmailSchema(many=True, strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
user_schema = UserSchema(strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
if session.get('uid'):
user = User.query.get(session['uid'])
if user is None:
session.clear()
else:
user = None
if user is None:
context = {
'isAuthenticated': False,
}
else:
identity_list = list(Identity.query.filter(
Identity.user_id == user.id,
))
email_list = list(Email.query.filter(
Email.user_id == user.id,
))
context = {
'isAuthenticated': True,
'user': user_schema.dump(user).data,
'emails': emails_schema.dump(email_list).data,
'identities': identities_schema.dump(identity_list).data,
}
return context
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
|
<commit_before>from flask import session
from zeus import auth
from zeus.models import Identity, User
from .base import Resource
from ..schemas import IdentitySchema, UserSchema
user_schema = UserSchema(strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
if session.get('uid'):
user = User.query.get(session['uid'])
if user is None:
session.clear()
else:
user = None
if user is None:
context = {
'isAuthenticated': False,
'user': None,
'identities': [],
}
else:
identity_list = list(Identity.query.filter(
Identity.user_id == user.id,
))
context = {
'isAuthenticated': True,
'user': user_schema.dump(user).data,
'identities': identities_schema.dump(identity_list).data,
}
return context
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
<commit_msg>Add emails to auth details<commit_after>
|
from flask import session
from zeus import auth
from zeus.models import Email, Identity, User
from .base import Resource
from ..schemas import EmailSchema, IdentitySchema, UserSchema
emails_schema = EmailSchema(many=True, strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
user_schema = UserSchema(strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
if session.get('uid'):
user = User.query.get(session['uid'])
if user is None:
session.clear()
else:
user = None
if user is None:
context = {
'isAuthenticated': False,
}
else:
identity_list = list(Identity.query.filter(
Identity.user_id == user.id,
))
email_list = list(Email.query.filter(
Email.user_id == user.id,
))
context = {
'isAuthenticated': True,
'user': user_schema.dump(user).data,
'emails': emails_schema.dump(email_list).data,
'identities': identities_schema.dump(identity_list).data,
}
return context
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
|
from flask import session
from zeus import auth
from zeus.models import Identity, User
from .base import Resource
from ..schemas import IdentitySchema, UserSchema
user_schema = UserSchema(strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
if session.get('uid'):
user = User.query.get(session['uid'])
if user is None:
session.clear()
else:
user = None
if user is None:
context = {
'isAuthenticated': False,
'user': None,
'identities': [],
}
else:
identity_list = list(Identity.query.filter(
Identity.user_id == user.id,
))
context = {
'isAuthenticated': True,
'user': user_schema.dump(user).data,
'identities': identities_schema.dump(identity_list).data,
}
return context
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
Add emails to auth detailsfrom flask import session
from zeus import auth
from zeus.models import Email, Identity, User
from .base import Resource
from ..schemas import EmailSchema, IdentitySchema, UserSchema
emails_schema = EmailSchema(many=True, strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
user_schema = UserSchema(strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
if session.get('uid'):
user = User.query.get(session['uid'])
if user is None:
session.clear()
else:
user = None
if user is None:
context = {
'isAuthenticated': False,
}
else:
identity_list = list(Identity.query.filter(
Identity.user_id == user.id,
))
email_list = list(Email.query.filter(
Email.user_id == user.id,
))
context = {
'isAuthenticated': True,
'user': user_schema.dump(user).data,
'emails': emails_schema.dump(email_list).data,
'identities': identities_schema.dump(identity_list).data,
}
return context
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
|
<commit_before>from flask import session
from zeus import auth
from zeus.models import Identity, User
from .base import Resource
from ..schemas import IdentitySchema, UserSchema
user_schema = UserSchema(strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
if session.get('uid'):
user = User.query.get(session['uid'])
if user is None:
session.clear()
else:
user = None
if user is None:
context = {
'isAuthenticated': False,
'user': None,
'identities': [],
}
else:
identity_list = list(Identity.query.filter(
Identity.user_id == user.id,
))
context = {
'isAuthenticated': True,
'user': user_schema.dump(user).data,
'identities': identities_schema.dump(identity_list).data,
}
return context
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
<commit_msg>Add emails to auth details<commit_after>from flask import session
from zeus import auth
from zeus.models import Email, Identity, User
from .base import Resource
from ..schemas import EmailSchema, IdentitySchema, UserSchema
emails_schema = EmailSchema(many=True, strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
user_schema = UserSchema(strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
if session.get('uid'):
user = User.query.get(session['uid'])
if user is None:
session.clear()
else:
user = None
if user is None:
context = {
'isAuthenticated': False,
}
else:
identity_list = list(Identity.query.filter(
Identity.user_id == user.id,
))
email_list = list(Email.query.filter(
Email.user_id == user.id,
))
context = {
'isAuthenticated': True,
'user': user_schema.dump(user).data,
'emails': emails_schema.dump(email_list).data,
'identities': identities_schema.dump(identity_list).data,
}
return context
def delete(self):
"""
Logout.
"""
auth.logout()
return {
'isAuthenticated': False,
'user': None,
}
|
ec9d542e4a6df758b3847486c9084ff8a31b6a7c
|
judge/management/commands/copy_language.py
|
judge/management/commands/copy_language.py
|
from django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set = source.problem_set.all()
|
from django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set.set(source.problem_set.all())
|
Use .set() rather than direct assignment
|
Use .set() rather than direct assignment
|
Python
|
agpl-3.0
|
DMOJ/site,DMOJ/site,DMOJ/site,DMOJ/site
|
from django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set = source.problem_set.all()
Use .set() rather than direct assignment
|
from django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set.set(source.problem_set.all())
|
<commit_before>from django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set = source.problem_set.all()
<commit_msg>Use .set() rather than direct assignment<commit_after>
|
from django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set.set(source.problem_set.all())
|
from django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set = source.problem_set.all()
Use .set() rather than direct assignmentfrom django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set.set(source.problem_set.all())
|
<commit_before>from django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set = source.problem_set.all()
<commit_msg>Use .set() rather than direct assignment<commit_after>from django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set.set(source.problem_set.all())
|
692234e72862839d8c14fb0f1a6ebe7259b15413
|
core/report.py
|
core/report.py
|
import config
def sendMail():
print config.config
print "Sent e-mail"
def sendToGrapite():
pass
|
from config import config as conf
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import time
import pushnotify
def sendMail(recipients, subject, body):
if not isinstance( recipients, list ):
recipients = [ recipients ]
session = smtplib.SMTP( conf.get( 'gmail', 'server' ),
conf.getint( 'gmail', 'port' ) )
session.ehlo()
session.starttls()
session.login( conf.get( 'gmail', 'username' ),
conf.get( 'gmail', 'password' ) )
for recipient in recipients:
headers = "\r\n".join( [ "from: " + conf.get( 'gmail', 'from' ),
"subject: " + subject,
"to: " + recipient,
"mime-version: 1.0",
"content-type: text/html" ] )
content = headers + "\r\n\r\n" + body
session.sendmail( conf.get( 'gmail', 'from' ), recipient, content )
def sendNotification(application, desc, event):
client = pushnotify.get_client('nma', application=application )
client.add_key( conf.get( 'notifymyandroid', 'api_key' ) )
try:
client.notify( desc, event, split=True )
except:
pass
def sendToGrapite(path, value):
message = '%s %s %d\n' % ( path, value, int( time.time() ) )
sock = socket.socket()
graphite_address = ( conf.get( 'graphite', 'server' ),
conf.get( 'graphite', 'port' ) )
sock.connect( graphite_address )
sock.sendall( message )
sock.close()
|
Complete e-mail, Graphite and push notification support
|
Complete e-mail, Graphite and push notification support
|
Python
|
mit
|
nlindblad/ocarina,nlindblad/ocarina
|
import config
def sendMail():
print config.config
print "Sent e-mail"
def sendToGrapite():
pass
Complete e-mail, Graphite and push notification support
|
from config import config as conf
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import time
import pushnotify
def sendMail(recipients, subject, body):
if not isinstance( recipients, list ):
recipients = [ recipients ]
session = smtplib.SMTP( conf.get( 'gmail', 'server' ),
conf.getint( 'gmail', 'port' ) )
session.ehlo()
session.starttls()
session.login( conf.get( 'gmail', 'username' ),
conf.get( 'gmail', 'password' ) )
for recipient in recipients:
headers = "\r\n".join( [ "from: " + conf.get( 'gmail', 'from' ),
"subject: " + subject,
"to: " + recipient,
"mime-version: 1.0",
"content-type: text/html" ] )
content = headers + "\r\n\r\n" + body
session.sendmail( conf.get( 'gmail', 'from' ), recipient, content )
def sendNotification(application, desc, event):
client = pushnotify.get_client('nma', application=application )
client.add_key( conf.get( 'notifymyandroid', 'api_key' ) )
try:
client.notify( desc, event, split=True )
except:
pass
def sendToGrapite(path, value):
message = '%s %s %d\n' % ( path, value, int( time.time() ) )
sock = socket.socket()
graphite_address = ( conf.get( 'graphite', 'server' ),
conf.get( 'graphite', 'port' ) )
sock.connect( graphite_address )
sock.sendall( message )
sock.close()
|
<commit_before>import config
def sendMail():
print config.config
print "Sent e-mail"
def sendToGrapite():
pass
<commit_msg>Complete e-mail, Graphite and push notification support<commit_after>
|
from config import config as conf
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import time
import pushnotify
def sendMail(recipients, subject, body):
if not isinstance( recipients, list ):
recipients = [ recipients ]
session = smtplib.SMTP( conf.get( 'gmail', 'server' ),
conf.getint( 'gmail', 'port' ) )
session.ehlo()
session.starttls()
session.login( conf.get( 'gmail', 'username' ),
conf.get( 'gmail', 'password' ) )
for recipient in recipients:
headers = "\r\n".join( [ "from: " + conf.get( 'gmail', 'from' ),
"subject: " + subject,
"to: " + recipient,
"mime-version: 1.0",
"content-type: text/html" ] )
content = headers + "\r\n\r\n" + body
session.sendmail( conf.get( 'gmail', 'from' ), recipient, content )
def sendNotification(application, desc, event):
client = pushnotify.get_client('nma', application=application )
client.add_key( conf.get( 'notifymyandroid', 'api_key' ) )
try:
client.notify( desc, event, split=True )
except:
pass
def sendToGrapite(path, value):
message = '%s %s %d\n' % ( path, value, int( time.time() ) )
sock = socket.socket()
graphite_address = ( conf.get( 'graphite', 'server' ),
conf.get( 'graphite', 'port' ) )
sock.connect( graphite_address )
sock.sendall( message )
sock.close()
|
import config
def sendMail():
print config.config
print "Sent e-mail"
def sendToGrapite():
pass
Complete e-mail, Graphite and push notification supportfrom config import config as conf
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import time
import pushnotify
def sendMail(recipients, subject, body):
if not isinstance( recipients, list ):
recipients = [ recipients ]
session = smtplib.SMTP( conf.get( 'gmail', 'server' ),
conf.getint( 'gmail', 'port' ) )
session.ehlo()
session.starttls()
session.login( conf.get( 'gmail', 'username' ),
conf.get( 'gmail', 'password' ) )
for recipient in recipients:
headers = "\r\n".join( [ "from: " + conf.get( 'gmail', 'from' ),
"subject: " + subject,
"to: " + recipient,
"mime-version: 1.0",
"content-type: text/html" ] )
content = headers + "\r\n\r\n" + body
session.sendmail( conf.get( 'gmail', 'from' ), recipient, content )
def sendNotification(application, desc, event):
client = pushnotify.get_client('nma', application=application )
client.add_key( conf.get( 'notifymyandroid', 'api_key' ) )
try:
client.notify( desc, event, split=True )
except:
pass
def sendToGrapite(path, value):
message = '%s %s %d\n' % ( path, value, int( time.time() ) )
sock = socket.socket()
graphite_address = ( conf.get( 'graphite', 'server' ),
conf.get( 'graphite', 'port' ) )
sock.connect( graphite_address )
sock.sendall( message )
sock.close()
|
<commit_before>import config
def sendMail():
print config.config
print "Sent e-mail"
def sendToGrapite():
pass
<commit_msg>Complete e-mail, Graphite and push notification support<commit_after>from config import config as conf
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import time
import pushnotify
def sendMail(recipients, subject, body):
if not isinstance( recipients, list ):
recipients = [ recipients ]
session = smtplib.SMTP( conf.get( 'gmail', 'server' ),
conf.getint( 'gmail', 'port' ) )
session.ehlo()
session.starttls()
session.login( conf.get( 'gmail', 'username' ),
conf.get( 'gmail', 'password' ) )
for recipient in recipients:
headers = "\r\n".join( [ "from: " + conf.get( 'gmail', 'from' ),
"subject: " + subject,
"to: " + recipient,
"mime-version: 1.0",
"content-type: text/html" ] )
content = headers + "\r\n\r\n" + body
session.sendmail( conf.get( 'gmail', 'from' ), recipient, content )
def sendNotification(application, desc, event):
client = pushnotify.get_client('nma', application=application )
client.add_key( conf.get( 'notifymyandroid', 'api_key' ) )
try:
client.notify( desc, event, split=True )
except:
pass
def sendToGrapite(path, value):
message = '%s %s %d\n' % ( path, value, int( time.time() ) )
sock = socket.socket()
graphite_address = ( conf.get( 'graphite', 'server' ),
conf.get( 'graphite', 'port' ) )
sock.connect( graphite_address )
sock.sendall( message )
sock.close()
|
482bed9a37f49ba4ae68c94cf69edf28586be07d
|
examples/bank_account_debits.py
|
examples/bank_account_debits.py
|
'''
Learn how to verify a bank account so you can debit with it.
'''
from __future__ import unicode_literals
import balanced
def init():
key = balanced.APIKey().save()
balanced.configure(key.secret)
balanced.Marketplace().save()
def main():
init()
# create a bank account
bank_account = balanced.BankAccount(
account_number='1234567890',
routing_number='321174851',
name='Jack Q Merchant',
).save()
customer = balanced.Customer().save()
bank_account.associate_to(customer)
print 'you can\'t debit until you authenticate'
try:
bank_account.debit(100)
except balanced.exc.HTTPError as ex:
print 'Debit failed, %s' % ex.message
# verify
verification = bank_account.verify()
print 'PROTIP: for TEST bank accounts the valid amount is always 1 and 1'
try:
verification.confirm(1, 2)
except balanced.exc.BankAccountVerificationFailure as ex:
print 'Authentication error , %s' % ex.message
if verification.confirm(1, 1).verification_status != 'succeeded':
raise Exception('unpossible')
debit = bank_account.debit(100)
print 'debited the bank account %s for %d cents' % (
debit.source.href,
debit.amount
)
print 'and there you have it'
if __name__ == '__main__':
main()
|
'''
Learn how to verify a bank account so you can debit with it.
'''
from __future__ import unicode_literals
import balanced
def init():
key = balanced.APIKey().save()
balanced.configure(key.secret)
balanced.Marketplace().save()
def main():
init()
# create a bank account
bank_account = balanced.BankAccount(
account_number='1234567890',
routing_number='321174851',
name='Jack Q Merchant',
).save()
customer = balanced.Customer().save()
bank_account.associate_to(customer)
print 'you can\'t debit until you authenticate'
try:
bank_account.debit(100)
except balanced.exc.HTTPError as ex:
print 'Debit failed, %s' % ex.message
# verify
verification = bank_account.verify()
print 'PROTIP: for TEST bank accounts the valid amount is always 1 and 1'
try:
verification.confirm(amount_1=1, amount_2=1)
except balanced.exc.BankAccountVerificationFailure as ex:
print 'Authentication error , %s' % ex.message
if verification.confirm(1, 1).verification_status != 'succeeded':
raise Exception('unpossible')
debit = bank_account.debit(100)
print 'debited the bank account %s for %d cents' % (
debit.source.href,
debit.amount
)
print 'and there you have it'
if __name__ == '__main__':
main()
|
Update example for bank account debits for confirm()
|
Update example for bank account debits for confirm()
|
Python
|
mit
|
balanced/balanced-python,trenton42/txbalanced
|
'''
Learn how to verify a bank account so you can debit with it.
'''
from __future__ import unicode_literals
import balanced
def init():
key = balanced.APIKey().save()
balanced.configure(key.secret)
balanced.Marketplace().save()
def main():
init()
# create a bank account
bank_account = balanced.BankAccount(
account_number='1234567890',
routing_number='321174851',
name='Jack Q Merchant',
).save()
customer = balanced.Customer().save()
bank_account.associate_to(customer)
print 'you can\'t debit until you authenticate'
try:
bank_account.debit(100)
except balanced.exc.HTTPError as ex:
print 'Debit failed, %s' % ex.message
# verify
verification = bank_account.verify()
print 'PROTIP: for TEST bank accounts the valid amount is always 1 and 1'
try:
verification.confirm(1, 2)
except balanced.exc.BankAccountVerificationFailure as ex:
print 'Authentication error , %s' % ex.message
if verification.confirm(1, 1).verification_status != 'succeeded':
raise Exception('unpossible')
debit = bank_account.debit(100)
print 'debited the bank account %s for %d cents' % (
debit.source.href,
debit.amount
)
print 'and there you have it'
if __name__ == '__main__':
main()
Update example for bank account debits for confirm()
|
'''
Learn how to verify a bank account so you can debit with it.
'''
from __future__ import unicode_literals
import balanced
def init():
key = balanced.APIKey().save()
balanced.configure(key.secret)
balanced.Marketplace().save()
def main():
init()
# create a bank account
bank_account = balanced.BankAccount(
account_number='1234567890',
routing_number='321174851',
name='Jack Q Merchant',
).save()
customer = balanced.Customer().save()
bank_account.associate_to(customer)
print 'you can\'t debit until you authenticate'
try:
bank_account.debit(100)
except balanced.exc.HTTPError as ex:
print 'Debit failed, %s' % ex.message
# verify
verification = bank_account.verify()
print 'PROTIP: for TEST bank accounts the valid amount is always 1 and 1'
try:
verification.confirm(amount_1=1, amount_2=1)
except balanced.exc.BankAccountVerificationFailure as ex:
print 'Authentication error , %s' % ex.message
if verification.confirm(1, 1).verification_status != 'succeeded':
raise Exception('unpossible')
debit = bank_account.debit(100)
print 'debited the bank account %s for %d cents' % (
debit.source.href,
debit.amount
)
print 'and there you have it'
if __name__ == '__main__':
main()
|
<commit_before>'''
Learn how to verify a bank account so you can debit with it.
'''
from __future__ import unicode_literals
import balanced
def init():
key = balanced.APIKey().save()
balanced.configure(key.secret)
balanced.Marketplace().save()
def main():
init()
# create a bank account
bank_account = balanced.BankAccount(
account_number='1234567890',
routing_number='321174851',
name='Jack Q Merchant',
).save()
customer = balanced.Customer().save()
bank_account.associate_to(customer)
print 'you can\'t debit until you authenticate'
try:
bank_account.debit(100)
except balanced.exc.HTTPError as ex:
print 'Debit failed, %s' % ex.message
# verify
verification = bank_account.verify()
print 'PROTIP: for TEST bank accounts the valid amount is always 1 and 1'
try:
verification.confirm(1, 2)
except balanced.exc.BankAccountVerificationFailure as ex:
print 'Authentication error , %s' % ex.message
if verification.confirm(1, 1).verification_status != 'succeeded':
raise Exception('unpossible')
debit = bank_account.debit(100)
print 'debited the bank account %s for %d cents' % (
debit.source.href,
debit.amount
)
print 'and there you have it'
if __name__ == '__main__':
main()
<commit_msg>Update example for bank account debits for confirm()<commit_after>
|
'''
Learn how to verify a bank account so you can debit with it.
'''
from __future__ import unicode_literals
import balanced
def init():
key = balanced.APIKey().save()
balanced.configure(key.secret)
balanced.Marketplace().save()
def main():
init()
# create a bank account
bank_account = balanced.BankAccount(
account_number='1234567890',
routing_number='321174851',
name='Jack Q Merchant',
).save()
customer = balanced.Customer().save()
bank_account.associate_to(customer)
print 'you can\'t debit until you authenticate'
try:
bank_account.debit(100)
except balanced.exc.HTTPError as ex:
print 'Debit failed, %s' % ex.message
# verify
verification = bank_account.verify()
print 'PROTIP: for TEST bank accounts the valid amount is always 1 and 1'
try:
verification.confirm(amount_1=1, amount_2=1)
except balanced.exc.BankAccountVerificationFailure as ex:
print 'Authentication error , %s' % ex.message
if verification.confirm(1, 1).verification_status != 'succeeded':
raise Exception('unpossible')
debit = bank_account.debit(100)
print 'debited the bank account %s for %d cents' % (
debit.source.href,
debit.amount
)
print 'and there you have it'
if __name__ == '__main__':
main()
|
'''
Learn how to verify a bank account so you can debit with it.
'''
from __future__ import unicode_literals
import balanced
def init():
key = balanced.APIKey().save()
balanced.configure(key.secret)
balanced.Marketplace().save()
def main():
init()
# create a bank account
bank_account = balanced.BankAccount(
account_number='1234567890',
routing_number='321174851',
name='Jack Q Merchant',
).save()
customer = balanced.Customer().save()
bank_account.associate_to(customer)
print 'you can\'t debit until you authenticate'
try:
bank_account.debit(100)
except balanced.exc.HTTPError as ex:
print 'Debit failed, %s' % ex.message
# verify
verification = bank_account.verify()
print 'PROTIP: for TEST bank accounts the valid amount is always 1 and 1'
try:
verification.confirm(1, 2)
except balanced.exc.BankAccountVerificationFailure as ex:
print 'Authentication error , %s' % ex.message
if verification.confirm(1, 1).verification_status != 'succeeded':
raise Exception('unpossible')
debit = bank_account.debit(100)
print 'debited the bank account %s for %d cents' % (
debit.source.href,
debit.amount
)
print 'and there you have it'
if __name__ == '__main__':
main()
Update example for bank account debits for confirm()'''
Learn how to verify a bank account so you can debit with it.
'''
from __future__ import unicode_literals
import balanced
def init():
key = balanced.APIKey().save()
balanced.configure(key.secret)
balanced.Marketplace().save()
def main():
init()
# create a bank account
bank_account = balanced.BankAccount(
account_number='1234567890',
routing_number='321174851',
name='Jack Q Merchant',
).save()
customer = balanced.Customer().save()
bank_account.associate_to(customer)
print 'you can\'t debit until you authenticate'
try:
bank_account.debit(100)
except balanced.exc.HTTPError as ex:
print 'Debit failed, %s' % ex.message
# verify
verification = bank_account.verify()
print 'PROTIP: for TEST bank accounts the valid amount is always 1 and 1'
try:
verification.confirm(amount_1=1, amount_2=1)
except balanced.exc.BankAccountVerificationFailure as ex:
print 'Authentication error , %s' % ex.message
if verification.confirm(1, 1).verification_status != 'succeeded':
raise Exception('unpossible')
debit = bank_account.debit(100)
print 'debited the bank account %s for %d cents' % (
debit.source.href,
debit.amount
)
print 'and there you have it'
if __name__ == '__main__':
main()
|
<commit_before>'''
Learn how to verify a bank account so you can debit with it.
'''
from __future__ import unicode_literals
import balanced
def init():
key = balanced.APIKey().save()
balanced.configure(key.secret)
balanced.Marketplace().save()
def main():
init()
# create a bank account
bank_account = balanced.BankAccount(
account_number='1234567890',
routing_number='321174851',
name='Jack Q Merchant',
).save()
customer = balanced.Customer().save()
bank_account.associate_to(customer)
print 'you can\'t debit until you authenticate'
try:
bank_account.debit(100)
except balanced.exc.HTTPError as ex:
print 'Debit failed, %s' % ex.message
# verify
verification = bank_account.verify()
print 'PROTIP: for TEST bank accounts the valid amount is always 1 and 1'
try:
verification.confirm(1, 2)
except balanced.exc.BankAccountVerificationFailure as ex:
print 'Authentication error , %s' % ex.message
if verification.confirm(1, 1).verification_status != 'succeeded':
raise Exception('unpossible')
debit = bank_account.debit(100)
print 'debited the bank account %s for %d cents' % (
debit.source.href,
debit.amount
)
print 'and there you have it'
if __name__ == '__main__':
main()
<commit_msg>Update example for bank account debits for confirm()<commit_after>'''
Learn how to verify a bank account so you can debit with it.
'''
from __future__ import unicode_literals
import balanced
def init():
key = balanced.APIKey().save()
balanced.configure(key.secret)
balanced.Marketplace().save()
def main():
init()
# create a bank account
bank_account = balanced.BankAccount(
account_number='1234567890',
routing_number='321174851',
name='Jack Q Merchant',
).save()
customer = balanced.Customer().save()
bank_account.associate_to(customer)
print 'you can\'t debit until you authenticate'
try:
bank_account.debit(100)
except balanced.exc.HTTPError as ex:
print 'Debit failed, %s' % ex.message
# verify
verification = bank_account.verify()
print 'PROTIP: for TEST bank accounts the valid amount is always 1 and 1'
try:
verification.confirm(amount_1=1, amount_2=1)
except balanced.exc.BankAccountVerificationFailure as ex:
print 'Authentication error , %s' % ex.message
if verification.confirm(1, 1).verification_status != 'succeeded':
raise Exception('unpossible')
debit = bank_account.debit(100)
print 'debited the bank account %s for %d cents' % (
debit.source.href,
debit.amount
)
print 'and there you have it'
if __name__ == '__main__':
main()
|
41fccd9d5060f2b8dcedde2cb9ab3391b48df420
|
scripts/generate_input_syntax.py
|
scripts/generate_input_syntax.py
|
#!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# this script is actually in the scripts subdirectory, so go up a level
app_path += '/..'
# Set the name of the application here and moose directory relative to the application
app_name = 'RAVEN'
MOOSE_DIR = app_path + '/../moose'
# See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
sys.path.append(MOOSE_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, MOOSE_DIR)
|
#!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# Set the name of the application here and moose directory relative to the application
app_name = 'raven'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose'))
FRAMEWORK_DIR = os.path.abspath(os.path.join(app_path, '..', '..', 'moose', 'framework'))
#### See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework')
if os.environ.has_key("FRAMEWORK_DIR"):
FRAMEWORK_DIR = os.environ['FRAMEWORK_DIR']
sys.path.append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR)
|
Update scripts to reflect new MOOSE_DIR definition
|
Update scripts to reflect new MOOSE_DIR definition
r25009
|
Python
|
apache-2.0
|
idaholab/raven,idaholab/raven,idaholab/raven,idaholab/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,idaholab/raven,idaholab/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,idaholab/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven
|
#!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# this script is actually in the scripts subdirectory, so go up a level
app_path += '/..'
# Set the name of the application here and moose directory relative to the application
app_name = 'RAVEN'
MOOSE_DIR = app_path + '/../moose'
# See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
sys.path.append(MOOSE_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, MOOSE_DIR)
Update scripts to reflect new MOOSE_DIR definition
r25009
|
#!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# Set the name of the application here and moose directory relative to the application
app_name = 'raven'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose'))
FRAMEWORK_DIR = os.path.abspath(os.path.join(app_path, '..', '..', 'moose', 'framework'))
#### See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework')
if os.environ.has_key("FRAMEWORK_DIR"):
FRAMEWORK_DIR = os.environ['FRAMEWORK_DIR']
sys.path.append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR)
|
<commit_before>#!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# this script is actually in the scripts subdirectory, so go up a level
app_path += '/..'
# Set the name of the application here and moose directory relative to the application
app_name = 'RAVEN'
MOOSE_DIR = app_path + '/../moose'
# See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
sys.path.append(MOOSE_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, MOOSE_DIR)
<commit_msg>Update scripts to reflect new MOOSE_DIR definition
r25009<commit_after>
|
#!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# Set the name of the application here and moose directory relative to the application
app_name = 'raven'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose'))
FRAMEWORK_DIR = os.path.abspath(os.path.join(app_path, '..', '..', 'moose', 'framework'))
#### See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework')
if os.environ.has_key("FRAMEWORK_DIR"):
FRAMEWORK_DIR = os.environ['FRAMEWORK_DIR']
sys.path.append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR)
|
#!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# this script is actually in the scripts subdirectory, so go up a level
app_path += '/..'
# Set the name of the application here and moose directory relative to the application
app_name = 'RAVEN'
MOOSE_DIR = app_path + '/../moose'
# See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
sys.path.append(MOOSE_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, MOOSE_DIR)
Update scripts to reflect new MOOSE_DIR definition
r25009#!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# Set the name of the application here and moose directory relative to the application
app_name = 'raven'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose'))
FRAMEWORK_DIR = os.path.abspath(os.path.join(app_path, '..', '..', 'moose', 'framework'))
#### See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework')
if os.environ.has_key("FRAMEWORK_DIR"):
FRAMEWORK_DIR = os.environ['FRAMEWORK_DIR']
sys.path.append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR)
|
<commit_before>#!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# this script is actually in the scripts subdirectory, so go up a level
app_path += '/..'
# Set the name of the application here and moose directory relative to the application
app_name = 'RAVEN'
MOOSE_DIR = app_path + '/../moose'
# See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
sys.path.append(MOOSE_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, MOOSE_DIR)
<commit_msg>Update scripts to reflect new MOOSE_DIR definition
r25009<commit_after>#!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# Set the name of the application here and moose directory relative to the application
app_name = 'raven'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose'))
FRAMEWORK_DIR = os.path.abspath(os.path.join(app_path, '..', '..', 'moose', 'framework'))
#### See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework')
if os.environ.has_key("FRAMEWORK_DIR"):
FRAMEWORK_DIR = os.environ['FRAMEWORK_DIR']
sys.path.append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR)
|
f9247d6b869af4f1a57afd907d7fb9a0545cdec5
|
anserv/frontend/views.py
|
anserv/frontend/views.py
|
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.conf import settings
import os
import logging
log=logging.getLogger(__name__)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/essay_site/api/v1/?format=json")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", RequestContext(request,{
'form': form,
}))
@login_required
def protected_data(request, **params):
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
filename_suffix = path.split('.')[-1]
response['Content-Type'] = 'application/{0}'.format(filename_suffix)
response['Content-Disposition'] = 'attachment; filename={0}'.format(path)
response['X-Accel-Redirect'] = str(os.path.join(settings.NGINX_PROTECTED_DATA_URL, path))
return response
|
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.conf import settings
import os
import logging
log=logging.getLogger(__name__)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/essay_site/api/v1/?format=json")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", RequestContext(request,{
'form': form,
}))
@login_required
def protected_data(request, **params):
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
filename_suffix = path.split('.')[-1]
response['Content-Type'] = 'application/{0}'.format(filename_suffix)
response['Content-Disposition'] = 'attachment; filename={0}'.format(path)
log.debug("{0}{1}".format(settings.NGINX_PROTECTED_DATA_URL, path))
response['X-Accel-Redirect'] = "{0}{1}".format(settings.NGINX_PROTECTED_DATA_URL, path)
return response
|
Change structure of the redirect
|
Change structure of the redirect
|
Python
|
agpl-3.0
|
edx/edxanalytics,edx/insights,edx/edxanalytics,edx/edxanalytics,edx/insights,edx/edxanalytics
|
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.conf import settings
import os
import logging
log=logging.getLogger(__name__)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/essay_site/api/v1/?format=json")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", RequestContext(request,{
'form': form,
}))
@login_required
def protected_data(request, **params):
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
filename_suffix = path.split('.')[-1]
response['Content-Type'] = 'application/{0}'.format(filename_suffix)
response['Content-Disposition'] = 'attachment; filename={0}'.format(path)
response['X-Accel-Redirect'] = str(os.path.join(settings.NGINX_PROTECTED_DATA_URL, path))
return response
Change structure of the redirect
|
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.conf import settings
import os
import logging
log=logging.getLogger(__name__)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/essay_site/api/v1/?format=json")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", RequestContext(request,{
'form': form,
}))
@login_required
def protected_data(request, **params):
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
filename_suffix = path.split('.')[-1]
response['Content-Type'] = 'application/{0}'.format(filename_suffix)
response['Content-Disposition'] = 'attachment; filename={0}'.format(path)
log.debug("{0}{1}".format(settings.NGINX_PROTECTED_DATA_URL, path))
response['X-Accel-Redirect'] = "{0}{1}".format(settings.NGINX_PROTECTED_DATA_URL, path)
return response
|
<commit_before>from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.conf import settings
import os
import logging
log=logging.getLogger(__name__)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/essay_site/api/v1/?format=json")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", RequestContext(request,{
'form': form,
}))
@login_required
def protected_data(request, **params):
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
filename_suffix = path.split('.')[-1]
response['Content-Type'] = 'application/{0}'.format(filename_suffix)
response['Content-Disposition'] = 'attachment; filename={0}'.format(path)
response['X-Accel-Redirect'] = str(os.path.join(settings.NGINX_PROTECTED_DATA_URL, path))
return response
<commit_msg>Change structure of the redirect<commit_after>
|
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.conf import settings
import os
import logging
log=logging.getLogger(__name__)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/essay_site/api/v1/?format=json")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", RequestContext(request,{
'form': form,
}))
@login_required
def protected_data(request, **params):
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
filename_suffix = path.split('.')[-1]
response['Content-Type'] = 'application/{0}'.format(filename_suffix)
response['Content-Disposition'] = 'attachment; filename={0}'.format(path)
log.debug("{0}{1}".format(settings.NGINX_PROTECTED_DATA_URL, path))
response['X-Accel-Redirect'] = "{0}{1}".format(settings.NGINX_PROTECTED_DATA_URL, path)
return response
|
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.conf import settings
import os
import logging
log=logging.getLogger(__name__)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/essay_site/api/v1/?format=json")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", RequestContext(request,{
'form': form,
}))
@login_required
def protected_data(request, **params):
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
filename_suffix = path.split('.')[-1]
response['Content-Type'] = 'application/{0}'.format(filename_suffix)
response['Content-Disposition'] = 'attachment; filename={0}'.format(path)
response['X-Accel-Redirect'] = str(os.path.join(settings.NGINX_PROTECTED_DATA_URL, path))
return response
Change structure of the redirectfrom django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.conf import settings
import os
import logging
log=logging.getLogger(__name__)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/essay_site/api/v1/?format=json")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", RequestContext(request,{
'form': form,
}))
@login_required
def protected_data(request, **params):
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
filename_suffix = path.split('.')[-1]
response['Content-Type'] = 'application/{0}'.format(filename_suffix)
response['Content-Disposition'] = 'attachment; filename={0}'.format(path)
log.debug("{0}{1}".format(settings.NGINX_PROTECTED_DATA_URL, path))
response['X-Accel-Redirect'] = "{0}{1}".format(settings.NGINX_PROTECTED_DATA_URL, path)
return response
|
<commit_before>from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.conf import settings
import os
import logging
log=logging.getLogger(__name__)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/essay_site/api/v1/?format=json")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", RequestContext(request,{
'form': form,
}))
@login_required
def protected_data(request, **params):
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
filename_suffix = path.split('.')[-1]
response['Content-Type'] = 'application/{0}'.format(filename_suffix)
response['Content-Disposition'] = 'attachment; filename={0}'.format(path)
response['X-Accel-Redirect'] = str(os.path.join(settings.NGINX_PROTECTED_DATA_URL, path))
return response
<commit_msg>Change structure of the redirect<commit_after>from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.conf import settings
import os
import logging
log=logging.getLogger(__name__)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/essay_site/api/v1/?format=json")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", RequestContext(request,{
'form': form,
}))
@login_required
def protected_data(request, **params):
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
path = params.get("path", None)
if path is None:
path = request.GET.get('path', None)
response = HttpResponse()
filename_suffix = path.split('.')[-1]
response['Content-Type'] = 'application/{0}'.format(filename_suffix)
response['Content-Disposition'] = 'attachment; filename={0}'.format(path)
log.debug("{0}{1}".format(settings.NGINX_PROTECTED_DATA_URL, path))
response['X-Accel-Redirect'] = "{0}{1}".format(settings.NGINX_PROTECTED_DATA_URL, path)
return response
|
1cfaf387af8e373d2bf3fdc8d6144f889489ba13
|
esis/cli.py
|
esis/cli.py
|
# -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
import os
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def valid_directory(path):
"""Directory validation."""
if not os.path.isdir(path):
raise argparse.ArgumentTypeError(
'{!r} is not a valid directory'.format(path))
if not os.access(path, os.R_OK | os.X_OK):
raise argparse.ArgumentTypeError(
'not enough permissions to explore {!r}'.format(path))
return path
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', type=valid_directory, help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
|
Add directory validation to argument parsing
|
Add directory validation to argument parsing
|
Python
|
mit
|
jcollado/esis
|
# -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
Add directory validation to argument parsing
|
# -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
import os
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def valid_directory(path):
"""Directory validation."""
if not os.path.isdir(path):
raise argparse.ArgumentTypeError(
'{!r} is not a valid directory'.format(path))
if not os.access(path, os.R_OK | os.X_OK):
raise argparse.ArgumentTypeError(
'not enough permissions to explore {!r}'.format(path))
return path
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', type=valid_directory, help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
|
<commit_before># -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
<commit_msg>Add directory validation to argument parsing<commit_after>
|
# -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
import os
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def valid_directory(path):
"""Directory validation."""
if not os.path.isdir(path):
raise argparse.ArgumentTypeError(
'{!r} is not a valid directory'.format(path))
if not os.access(path, os.R_OK | os.X_OK):
raise argparse.ArgumentTypeError(
'not enough permissions to explore {!r}'.format(path))
return path
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', type=valid_directory, help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
Add directory validation to argument parsing# -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
import os
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def valid_directory(path):
"""Directory validation."""
if not os.path.isdir(path):
raise argparse.ArgumentTypeError(
'{!r} is not a valid directory'.format(path))
if not os.access(path, os.R_OK | os.X_OK):
raise argparse.ArgumentTypeError(
'not enough permissions to explore {!r}'.format(path))
return path
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', type=valid_directory, help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
|
<commit_before># -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
<commit_msg>Add directory validation to argument parsing<commit_after># -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
import argparse
import os
def main():
"""Entry point for the esis.py script."""
args = parse_arguments()
print args
def valid_directory(path):
"""Directory validation."""
if not os.path.isdir(path):
raise argparse.ArgumentTypeError(
'{!r} is not a valid directory'.format(path))
if not os.access(path, os.R_OK | os.X_OK):
raise argparse.ArgumentTypeError(
'not enough permissions to explore {!r}'.format(path))
return path
def parse_arguments():
"""Parse command line arguments.
:returns: Parsed arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(help='Subcommands')
index = subparsers.add_parser('index', help='Index SQLite database files')
index.add_argument('directory', type=valid_directory, help='Base directory')
search = subparsers.add_parser('search', help='Search indexed data')
search.add_argument('query', help='Search query')
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
|
c9215a00bfe8d1edaf2840f6cd4b3ae8061c26f5
|
allauth_uwum/provider.py
|
allauth_uwum/provider.py
|
"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
return ['authentication', 'notify_email']
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
|
"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
default_scope = ['authentication']
if app_settings.QUERY_EMAIL:
default_scope.append('notify_email')
return default_scope
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
|
Set "notify_email" in default scope only if settings allow it
|
Set "notify_email" in default scope only if settings allow it
|
Python
|
mit
|
ExCiteS/django-allauth-uwum
|
"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
return ['authentication', 'notify_email']
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
Set "notify_email" in default scope only if settings allow it
|
"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
default_scope = ['authentication']
if app_settings.QUERY_EMAIL:
default_scope.append('notify_email')
return default_scope
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
|
<commit_before>"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
return ['authentication', 'notify_email']
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
<commit_msg>Set "notify_email" in default scope only if settings allow it<commit_after>
|
"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
default_scope = ['authentication']
if app_settings.QUERY_EMAIL:
default_scope.append('notify_email')
return default_scope
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
|
"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
return ['authentication', 'notify_email']
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
Set "notify_email" in default scope only if settings allow it"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
default_scope = ['authentication']
if app_settings.QUERY_EMAIL:
default_scope.append('notify_email')
return default_scope
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
|
<commit_before>"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
return ['authentication', 'notify_email']
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
<commit_msg>Set "notify_email" in default scope only if settings allow it<commit_after>"""The UWUM (Unified WeGovNow User Management) provider."""
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class UWUMAccount(ProviderAccount):
"""The UWUM provider account."""
pass
class UWUMProvider(OAuth2Provider):
"""The UWUM OAuth2 provider."""
id = 'uwum'
name = 'UWUM'
settings = app_settings.PROVIDERS.get(id, {})
account_class = UWUMAccount
def get_default_scope(self):
"""Get the default UWUM scope."""
default_scope = ['authentication']
if app_settings.QUERY_EMAIL:
default_scope.append('notify_email')
return default_scope
def extract_uid(self, data):
"""Extract the unique user (UWUM member) identification number."""
member = data.get('member', {})
return str(member.get('id'))
def extract_common_fields(self, data):
"""Extract the common fields for the user (UWUM member)."""
member = data.get('member', {})
return {'username': member.get('name'), 'email': member.get('email')}
registry.register(UWUMProvider)
|
1a16281c6591ab059db09ab5a8af4826d3f3698a
|
eche.py
|
eche.py
|
#!env python
"""Eche - a simple, lisp like language.
Usage:
eche FILE ...
eche (-h | --help)
eche --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
import pathlib
from docopt import docopt
sys.path.append(str(pathlib.Path('.').joinpath('eche')))
import eche.step3_env as eche
VERSION = '0.3.1'
def main():
args = docopt(__doc__, version=VERSION)
if args['--version']:
print(VERSION)
sys.exit(0)
if 'FILE' in args:
for filename in args['FILE']:
eche.process_file(filename)
else:
sys.exit(eche.repl())
if __name__ == "__main__":
main()
|
#!env python
"""Eche - a simple, lisp like language.
Usage:
eche [FILE ...]
eche (-h | --help)
eche --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
import pathlib
from docopt import docopt
sys.path.append(str(pathlib.Path('.').joinpath('eche')))
import eche.step3_env as eche
VERSION = '0.3.1'
def main():
args = docopt(__doc__, version=VERSION)
if args['--version']:
print(VERSION)
sys.exit(0)
if 'FILE' in args:
for filename in args['FILE']:
eche.process_file(filename)
else:
sys.exit(eche.repl())
if __name__ == "__main__":
main()
|
Change args to show repl if no FILEs are given.
|
Change args to show repl if no FILEs are given.
|
Python
|
mit
|
skk/eche
|
#!env python
"""Eche - a simple, lisp like language.
Usage:
eche FILE ...
eche (-h | --help)
eche --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
import pathlib
from docopt import docopt
sys.path.append(str(pathlib.Path('.').joinpath('eche')))
import eche.step3_env as eche
VERSION = '0.3.1'
def main():
args = docopt(__doc__, version=VERSION)
if args['--version']:
print(VERSION)
sys.exit(0)
if 'FILE' in args:
for filename in args['FILE']:
eche.process_file(filename)
else:
sys.exit(eche.repl())
if __name__ == "__main__":
main()
Change args to show repl if no FILEs are given.
|
#!env python
"""Eche - a simple, lisp like language.
Usage:
eche [FILE ...]
eche (-h | --help)
eche --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
import pathlib
from docopt import docopt
sys.path.append(str(pathlib.Path('.').joinpath('eche')))
import eche.step3_env as eche
VERSION = '0.3.1'
def main():
args = docopt(__doc__, version=VERSION)
if args['--version']:
print(VERSION)
sys.exit(0)
if 'FILE' in args:
for filename in args['FILE']:
eche.process_file(filename)
else:
sys.exit(eche.repl())
if __name__ == "__main__":
main()
|
<commit_before>#!env python
"""Eche - a simple, lisp like language.
Usage:
eche FILE ...
eche (-h | --help)
eche --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
import pathlib
from docopt import docopt
sys.path.append(str(pathlib.Path('.').joinpath('eche')))
import eche.step3_env as eche
VERSION = '0.3.1'
def main():
args = docopt(__doc__, version=VERSION)
if args['--version']:
print(VERSION)
sys.exit(0)
if 'FILE' in args:
for filename in args['FILE']:
eche.process_file(filename)
else:
sys.exit(eche.repl())
if __name__ == "__main__":
main()
<commit_msg>Change args to show repl if no FILEs are given.<commit_after>
|
#!env python
"""Eche - a simple, lisp like language.
Usage:
eche [FILE ...]
eche (-h | --help)
eche --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
import pathlib
from docopt import docopt
sys.path.append(str(pathlib.Path('.').joinpath('eche')))
import eche.step3_env as eche
VERSION = '0.3.1'
def main():
args = docopt(__doc__, version=VERSION)
if args['--version']:
print(VERSION)
sys.exit(0)
if 'FILE' in args:
for filename in args['FILE']:
eche.process_file(filename)
else:
sys.exit(eche.repl())
if __name__ == "__main__":
main()
|
#!env python
"""Eche - a simple, lisp like language.
Usage:
eche FILE ...
eche (-h | --help)
eche --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
import pathlib
from docopt import docopt
sys.path.append(str(pathlib.Path('.').joinpath('eche')))
import eche.step3_env as eche
VERSION = '0.3.1'
def main():
args = docopt(__doc__, version=VERSION)
if args['--version']:
print(VERSION)
sys.exit(0)
if 'FILE' in args:
for filename in args['FILE']:
eche.process_file(filename)
else:
sys.exit(eche.repl())
if __name__ == "__main__":
main()
Change args to show repl if no FILEs are given.#!env python
"""Eche - a simple, lisp like language.
Usage:
eche [FILE ...]
eche (-h | --help)
eche --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
import pathlib
from docopt import docopt
sys.path.append(str(pathlib.Path('.').joinpath('eche')))
import eche.step3_env as eche
VERSION = '0.3.1'
def main():
args = docopt(__doc__, version=VERSION)
if args['--version']:
print(VERSION)
sys.exit(0)
if 'FILE' in args:
for filename in args['FILE']:
eche.process_file(filename)
else:
sys.exit(eche.repl())
if __name__ == "__main__":
main()
|
<commit_before>#!env python
"""Eche - a simple, lisp like language.
Usage:
eche FILE ...
eche (-h | --help)
eche --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
import pathlib
from docopt import docopt
sys.path.append(str(pathlib.Path('.').joinpath('eche')))
import eche.step3_env as eche
VERSION = '0.3.1'
def main():
args = docopt(__doc__, version=VERSION)
if args['--version']:
print(VERSION)
sys.exit(0)
if 'FILE' in args:
for filename in args['FILE']:
eche.process_file(filename)
else:
sys.exit(eche.repl())
if __name__ == "__main__":
main()
<commit_msg>Change args to show repl if no FILEs are given.<commit_after>#!env python
"""Eche - a simple, lisp like language.
Usage:
eche [FILE ...]
eche (-h | --help)
eche --version
Options:
-h --help Show this screen.
--version Show version.
"""
import sys
import pathlib
from docopt import docopt
sys.path.append(str(pathlib.Path('.').joinpath('eche')))
import eche.step3_env as eche
VERSION = '0.3.1'
def main():
args = docopt(__doc__, version=VERSION)
if args['--version']:
print(VERSION)
sys.exit(0)
if 'FILE' in args:
for filename in args['FILE']:
eche.process_file(filename)
else:
sys.exit(eche.repl())
if __name__ == "__main__":
main()
|
f1667a27200d63b1c672586017318fd319a7985e
|
github2/commits.py
|
github2/commits.py
|
from github2.core import BaseData, GithubCommand, Attribute, DateAttribute
class Commit(BaseData):
messsage = Attribute("Commit message.")
parents = Attribute("List of parents for this commit.")
url = Attribute("Canonical URL for this commit.")
author = Attribute("Author metadata (dict with name/email.)")
id = Attribute("Commit ID.")
committed_date = DateAttribute("Date committed.", format="commit")
authored_data = DateAttribute("Date authored.", format="commit")
tree = Attribute("Tree SHA for this commit.")
committer = Attribute("Comitter metadata (dict with name/email.)")
added = Attribute("(If present) Datastructure representing what's been "
"added since last commit.")
removed = Attribute("(if present) Datastructure representing what's been "
"removed since last commit.")
modified = Attribute("(If present) Datastructure representing what's "
"been modified since last commit.")
class Commits(GithubCommand):
domain = "commits"
def list(self, project, branch="master", file=None):
return self.get_values("list", project, branch, file,
filter="commits", datatype=Commit)
def show(self, project, sha):
return self.get_value("show", project, sha,
filter="commit", datatype=Commit)
|
from github2.core import BaseData, GithubCommand, Attribute, DateAttribute
class Commit(BaseData):
message = Attribute("Commit message.")
parents = Attribute("List of parents for this commit.")
url = Attribute("Canonical URL for this commit.")
author = Attribute("Author metadata (dict with name/email.)")
id = Attribute("Commit ID.")
committed_date = DateAttribute("Date committed.", format="commit")
authored_data = DateAttribute("Date authored.", format="commit")
tree = Attribute("Tree SHA for this commit.")
committer = Attribute("Comitter metadata (dict with name/email.)")
added = Attribute("(If present) Datastructure representing what's been "
"added since last commit.")
removed = Attribute("(if present) Datastructure representing what's been "
"removed since last commit.")
modified = Attribute("(If present) Datastructure representing what's "
"been modified since last commit.")
class Commits(GithubCommand):
domain = "commits"
def list(self, project, branch="master", file=None):
return self.get_values("list", project, branch, file,
filter="commits", datatype=Commit)
def show(self, project, sha):
return self.get_value("show", project, sha,
filter="commit", datatype=Commit)
|
Fix typo messsage -> message
|
Fix typo messsage -> message
|
Python
|
bsd-3-clause
|
ask/python-github2
|
from github2.core import BaseData, GithubCommand, Attribute, DateAttribute
class Commit(BaseData):
messsage = Attribute("Commit message.")
parents = Attribute("List of parents for this commit.")
url = Attribute("Canonical URL for this commit.")
author = Attribute("Author metadata (dict with name/email.)")
id = Attribute("Commit ID.")
committed_date = DateAttribute("Date committed.", format="commit")
authored_data = DateAttribute("Date authored.", format="commit")
tree = Attribute("Tree SHA for this commit.")
committer = Attribute("Comitter metadata (dict with name/email.)")
added = Attribute("(If present) Datastructure representing what's been "
"added since last commit.")
removed = Attribute("(if present) Datastructure representing what's been "
"removed since last commit.")
modified = Attribute("(If present) Datastructure representing what's "
"been modified since last commit.")
class Commits(GithubCommand):
domain = "commits"
def list(self, project, branch="master", file=None):
return self.get_values("list", project, branch, file,
filter="commits", datatype=Commit)
def show(self, project, sha):
return self.get_value("show", project, sha,
filter="commit", datatype=Commit)
Fix typo messsage -> message
|
from github2.core import BaseData, GithubCommand, Attribute, DateAttribute
class Commit(BaseData):
message = Attribute("Commit message.")
parents = Attribute("List of parents for this commit.")
url = Attribute("Canonical URL for this commit.")
author = Attribute("Author metadata (dict with name/email.)")
id = Attribute("Commit ID.")
committed_date = DateAttribute("Date committed.", format="commit")
authored_data = DateAttribute("Date authored.", format="commit")
tree = Attribute("Tree SHA for this commit.")
committer = Attribute("Comitter metadata (dict with name/email.)")
added = Attribute("(If present) Datastructure representing what's been "
"added since last commit.")
removed = Attribute("(if present) Datastructure representing what's been "
"removed since last commit.")
modified = Attribute("(If present) Datastructure representing what's "
"been modified since last commit.")
class Commits(GithubCommand):
domain = "commits"
def list(self, project, branch="master", file=None):
return self.get_values("list", project, branch, file,
filter="commits", datatype=Commit)
def show(self, project, sha):
return self.get_value("show", project, sha,
filter="commit", datatype=Commit)
|
<commit_before>from github2.core import BaseData, GithubCommand, Attribute, DateAttribute
class Commit(BaseData):
messsage = Attribute("Commit message.")
parents = Attribute("List of parents for this commit.")
url = Attribute("Canonical URL for this commit.")
author = Attribute("Author metadata (dict with name/email.)")
id = Attribute("Commit ID.")
committed_date = DateAttribute("Date committed.", format="commit")
authored_data = DateAttribute("Date authored.", format="commit")
tree = Attribute("Tree SHA for this commit.")
committer = Attribute("Comitter metadata (dict with name/email.)")
added = Attribute("(If present) Datastructure representing what's been "
"added since last commit.")
removed = Attribute("(if present) Datastructure representing what's been "
"removed since last commit.")
modified = Attribute("(If present) Datastructure representing what's "
"been modified since last commit.")
class Commits(GithubCommand):
domain = "commits"
def list(self, project, branch="master", file=None):
return self.get_values("list", project, branch, file,
filter="commits", datatype=Commit)
def show(self, project, sha):
return self.get_value("show", project, sha,
filter="commit", datatype=Commit)
<commit_msg>Fix typo messsage -> message<commit_after>
|
from github2.core import BaseData, GithubCommand, Attribute, DateAttribute
class Commit(BaseData):
message = Attribute("Commit message.")
parents = Attribute("List of parents for this commit.")
url = Attribute("Canonical URL for this commit.")
author = Attribute("Author metadata (dict with name/email.)")
id = Attribute("Commit ID.")
committed_date = DateAttribute("Date committed.", format="commit")
authored_data = DateAttribute("Date authored.", format="commit")
tree = Attribute("Tree SHA for this commit.")
committer = Attribute("Comitter metadata (dict with name/email.)")
added = Attribute("(If present) Datastructure representing what's been "
"added since last commit.")
removed = Attribute("(if present) Datastructure representing what's been "
"removed since last commit.")
modified = Attribute("(If present) Datastructure representing what's "
"been modified since last commit.")
class Commits(GithubCommand):
domain = "commits"
def list(self, project, branch="master", file=None):
return self.get_values("list", project, branch, file,
filter="commits", datatype=Commit)
def show(self, project, sha):
return self.get_value("show", project, sha,
filter="commit", datatype=Commit)
|
from github2.core import BaseData, GithubCommand, Attribute, DateAttribute
class Commit(BaseData):
messsage = Attribute("Commit message.")
parents = Attribute("List of parents for this commit.")
url = Attribute("Canonical URL for this commit.")
author = Attribute("Author metadata (dict with name/email.)")
id = Attribute("Commit ID.")
committed_date = DateAttribute("Date committed.", format="commit")
authored_data = DateAttribute("Date authored.", format="commit")
tree = Attribute("Tree SHA for this commit.")
committer = Attribute("Comitter metadata (dict with name/email.)")
added = Attribute("(If present) Datastructure representing what's been "
"added since last commit.")
removed = Attribute("(if present) Datastructure representing what's been "
"removed since last commit.")
modified = Attribute("(If present) Datastructure representing what's "
"been modified since last commit.")
class Commits(GithubCommand):
domain = "commits"
def list(self, project, branch="master", file=None):
return self.get_values("list", project, branch, file,
filter="commits", datatype=Commit)
def show(self, project, sha):
return self.get_value("show", project, sha,
filter="commit", datatype=Commit)
Fix typo messsage -> messagefrom github2.core import BaseData, GithubCommand, Attribute, DateAttribute
class Commit(BaseData):
message = Attribute("Commit message.")
parents = Attribute("List of parents for this commit.")
url = Attribute("Canonical URL for this commit.")
author = Attribute("Author metadata (dict with name/email.)")
id = Attribute("Commit ID.")
committed_date = DateAttribute("Date committed.", format="commit")
authored_data = DateAttribute("Date authored.", format="commit")
tree = Attribute("Tree SHA for this commit.")
committer = Attribute("Comitter metadata (dict with name/email.)")
added = Attribute("(If present) Datastructure representing what's been "
"added since last commit.")
removed = Attribute("(if present) Datastructure representing what's been "
"removed since last commit.")
modified = Attribute("(If present) Datastructure representing what's "
"been modified since last commit.")
class Commits(GithubCommand):
domain = "commits"
def list(self, project, branch="master", file=None):
return self.get_values("list", project, branch, file,
filter="commits", datatype=Commit)
def show(self, project, sha):
return self.get_value("show", project, sha,
filter="commit", datatype=Commit)
|
<commit_before>from github2.core import BaseData, GithubCommand, Attribute, DateAttribute
class Commit(BaseData):
messsage = Attribute("Commit message.")
parents = Attribute("List of parents for this commit.")
url = Attribute("Canonical URL for this commit.")
author = Attribute("Author metadata (dict with name/email.)")
id = Attribute("Commit ID.")
committed_date = DateAttribute("Date committed.", format="commit")
authored_data = DateAttribute("Date authored.", format="commit")
tree = Attribute("Tree SHA for this commit.")
committer = Attribute("Comitter metadata (dict with name/email.)")
added = Attribute("(If present) Datastructure representing what's been "
"added since last commit.")
removed = Attribute("(if present) Datastructure representing what's been "
"removed since last commit.")
modified = Attribute("(If present) Datastructure representing what's "
"been modified since last commit.")
class Commits(GithubCommand):
domain = "commits"
def list(self, project, branch="master", file=None):
return self.get_values("list", project, branch, file,
filter="commits", datatype=Commit)
def show(self, project, sha):
return self.get_value("show", project, sha,
filter="commit", datatype=Commit)
<commit_msg>Fix typo messsage -> message<commit_after>from github2.core import BaseData, GithubCommand, Attribute, DateAttribute
class Commit(BaseData):
message = Attribute("Commit message.")
parents = Attribute("List of parents for this commit.")
url = Attribute("Canonical URL for this commit.")
author = Attribute("Author metadata (dict with name/email.)")
id = Attribute("Commit ID.")
committed_date = DateAttribute("Date committed.", format="commit")
authored_data = DateAttribute("Date authored.", format="commit")
tree = Attribute("Tree SHA for this commit.")
committer = Attribute("Comitter metadata (dict with name/email.)")
added = Attribute("(If present) Datastructure representing what's been "
"added since last commit.")
removed = Attribute("(if present) Datastructure representing what's been "
"removed since last commit.")
modified = Attribute("(If present) Datastructure representing what's "
"been modified since last commit.")
class Commits(GithubCommand):
domain = "commits"
def list(self, project, branch="master", file=None):
return self.get_values("list", project, branch, file,
filter="commits", datatype=Commit)
def show(self, project, sha):
return self.get_value("show", project, sha,
filter="commit", datatype=Commit)
|
e76ca364ab979e309d34ff458ef2629145a52ce2
|
magnum/db/sqlalchemy/alembic/versions/a1136d335540_add_docker_storage_driver_column.py
|
magnum/db/sqlalchemy/alembic/versions/a1136d335540_add_docker_storage_driver_column.py
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Add docker storage driver column
Revision ID: a1136d335540
Revises: d072f58ab240
Create Date: 2016-03-07 19:00:28.738486
"""
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
|
# 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.
"""Add docker storage driver column
Revision ID: a1136d335540
Revises: d072f58ab240
Create Date: 2016-03-07 19:00:28.738486
"""
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
docker_storage_driver_enum.create(op.get_bind(), checkfirst=True)
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
|
Fix for enum type docker_storage_driver
|
Fix for enum type docker_storage_driver
Create enum type "docker_storage_driver" for migration
This is fixing
oslo_db.exception.DBError: (psycopg2.ProgrammingError) type
"docker_storage_driver" does not exist
Closes-Bug: #1609776
Change-Id: I92d427e90bd73b4114d8688d3761cabac450fc9d
|
Python
|
apache-2.0
|
openstack/magnum,openstack/magnum,ArchiFleKs/magnum,ArchiFleKs/magnum
|
# 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.
"""Add docker storage driver column
Revision ID: a1136d335540
Revises: d072f58ab240
Create Date: 2016-03-07 19:00:28.738486
"""
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
Fix for enum type docker_storage_driver
Create enum type "docker_storage_driver" for migration
This is fixing
oslo_db.exception.DBError: (psycopg2.ProgrammingError) type
"docker_storage_driver" does not exist
Closes-Bug: #1609776
Change-Id: I92d427e90bd73b4114d8688d3761cabac450fc9d
|
# 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.
"""Add docker storage driver column
Revision ID: a1136d335540
Revises: d072f58ab240
Create Date: 2016-03-07 19:00:28.738486
"""
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
docker_storage_driver_enum.create(op.get_bind(), checkfirst=True)
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
|
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Add docker storage driver column
Revision ID: a1136d335540
Revises: d072f58ab240
Create Date: 2016-03-07 19:00:28.738486
"""
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
<commit_msg>Fix for enum type docker_storage_driver
Create enum type "docker_storage_driver" for migration
This is fixing
oslo_db.exception.DBError: (psycopg2.ProgrammingError) type
"docker_storage_driver" does not exist
Closes-Bug: #1609776
Change-Id: I92d427e90bd73b4114d8688d3761cabac450fc9d<commit_after>
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Add docker storage driver column
Revision ID: a1136d335540
Revises: d072f58ab240
Create Date: 2016-03-07 19:00:28.738486
"""
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
docker_storage_driver_enum.create(op.get_bind(), checkfirst=True)
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
|
# 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.
"""Add docker storage driver column
Revision ID: a1136d335540
Revises: d072f58ab240
Create Date: 2016-03-07 19:00:28.738486
"""
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
Fix for enum type docker_storage_driver
Create enum type "docker_storage_driver" for migration
This is fixing
oslo_db.exception.DBError: (psycopg2.ProgrammingError) type
"docker_storage_driver" does not exist
Closes-Bug: #1609776
Change-Id: I92d427e90bd73b4114d8688d3761cabac450fc9d# 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.
"""Add docker storage driver column
Revision ID: a1136d335540
Revises: d072f58ab240
Create Date: 2016-03-07 19:00:28.738486
"""
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
docker_storage_driver_enum.create(op.get_bind(), checkfirst=True)
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
|
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Add docker storage driver column
Revision ID: a1136d335540
Revises: d072f58ab240
Create Date: 2016-03-07 19:00:28.738486
"""
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
<commit_msg>Fix for enum type docker_storage_driver
Create enum type "docker_storage_driver" for migration
This is fixing
oslo_db.exception.DBError: (psycopg2.ProgrammingError) type
"docker_storage_driver" does not exist
Closes-Bug: #1609776
Change-Id: I92d427e90bd73b4114d8688d3761cabac450fc9d<commit_after># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Add docker storage driver column
Revision ID: a1136d335540
Revises: d072f58ab240
Create Date: 2016-03-07 19:00:28.738486
"""
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
docker_storage_driver_enum.create(op.get_bind(), checkfirst=True)
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
|
6881d127cf55dc96c44467ea807a9288a5108dff
|
scripts/lib/check_for_course_revisions.py
|
scripts/lib/check_for_course_revisions.py
|
from collections import OrderedDict
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
|
from collections import OrderedDict
from tzlocal import get_localzone
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
ordered_diff['_updated'] = get_localzone().localize(datetime.now()).isoformat()
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
|
Add '_updated' property to revisions
|
Add '_updated' property to revisions
|
Python
|
mit
|
StoDevX/course-data-tools,StoDevX/course-data-tools
|
from collections import OrderedDict
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
Add '_updated' property to revisions
|
from collections import OrderedDict
from tzlocal import get_localzone
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
ordered_diff['_updated'] = get_localzone().localize(datetime.now()).isoformat()
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
|
<commit_before>from collections import OrderedDict
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
<commit_msg>Add '_updated' property to revisions<commit_after>
|
from collections import OrderedDict
from tzlocal import get_localzone
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
ordered_diff['_updated'] = get_localzone().localize(datetime.now()).isoformat()
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
|
from collections import OrderedDict
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
Add '_updated' property to revisionsfrom collections import OrderedDict
from tzlocal import get_localzone
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
ordered_diff['_updated'] = get_localzone().localize(datetime.now()).isoformat()
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
|
<commit_before>from collections import OrderedDict
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
<commit_msg>Add '_updated' property to revisions<commit_after>from collections import OrderedDict
from tzlocal import get_localzone
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
ordered_diff['_updated'] = get_localzone().localize(datetime.now()).isoformat()
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
|
646e376a8e9bdc1daaa38ebee2de39e945ab443d
|
tests/test_cookiecutter_generation.py
|
tests/test_cookiecutter_generation.py
|
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture
def context():
return {
"project_name": "My Test Project",
"repo_name": "my_test_project",
"author_name": "Test Author",
"email": "test@example.com",
"description": "A short description of the project.",
"domain_name": "example.com",
"version": "0.1.0",
"timezone": "UTC",
"now": "2015/01/13",
"year": "2015"
}
def test_default_configuration(cookies, context):
result = cookies.bake(extra_context=context)
assert result.exit_code == 0
|
# -*- coding: utf-8 -*-
import os
import re
import pytest
from binaryornot.check import is_binary
PATTERN = "{{(\s?cookiecutter)[.](.*?)}}"
RE_OBJ = re.compile(PATTERN)
@pytest.fixture
def context():
return {
"project_name": "My Test Project",
"repo_name": "my_test_project",
"author_name": "Test Author",
"email": "test@example.com",
"description": "A short description of the project.",
"domain_name": "example.com",
"version": "0.1.0",
"timezone": "UTC",
"now": "2015/01/13",
"year": "2015"
}
def build_files_list(root_dir):
"""Build a list containing absolute paths to the generated files."""
return [
os.path.join(dirpath, file_path)
for dirpath, subdirs, files in os.walk(root_dir)
for file_path in files
]
def check_paths(paths):
"""Method to check all paths have correct substitutions,
used by other tests cases
"""
# Assert that no match is found in any of the files
for path in paths:
if is_binary(path):
continue
for line in open(path, 'r'):
match = RE_OBJ.search(line)
msg = "cookiecutter variable not replaced in {}"
assert match is None, msg.format(path)
def test_default_configuration(cookies, context):
result = cookies.bake(extra_context=context)
assert result.exit_code == 0
assert result.exception is None
assert result.project.basename == context['repo_name']
assert result.project.isdir()
paths = build_files_list(str(result.project))
assert paths
check_paths(paths)
|
Integrate additional checks of base.py with slight improvements
|
Integrate additional checks of base.py with slight improvements
|
Python
|
bsd-3-clause
|
webyneter/cookiecutter-django,kappataumu/cookiecutter-django,crdoconnor/cookiecutter-django,gappsexperts/cookiecutter-django,mjhea0/cookiecutter-django,mistalaba/cookiecutter-django,calculuscowboy/cookiecutter-django,hairychris/cookiecutter-django,kappataumu/cookiecutter-django,thisjustin/cookiecutter-django,ddiazpinto/cookiecutter-django,kappataumu/cookiecutter-django,calculuscowboy/cookiecutter-django,yunti/cookiecutter-django,trungdong/cookiecutter-django,topwebmaster/cookiecutter-django,ryankanno/cookiecutter-django,mjhea0/cookiecutter-django,gappsexperts/cookiecutter-django,webyneter/cookiecutter-django,webspired/cookiecutter-django,mjhea0/cookiecutter-django,drxos/cookiecutter-django-dokku,Parbhat/cookiecutter-django-foundation,pydanny/cookiecutter-django,webspired/cookiecutter-django,trungdong/cookiecutter-django,ovidner/cookiecutter-django,yunti/cookiecutter-django,asyncee/cookiecutter-django,pydanny/cookiecutter-django,aleprovencio/cookiecutter-django,crdoconnor/cookiecutter-django,ad-m/cookiecutter-django,nunchaks/cookiecutter-django,hackebrot/cookiecutter-django,aleprovencio/cookiecutter-django,calculuscowboy/cookiecutter-django,ryankanno/cookiecutter-django,mistalaba/cookiecutter-django,andresgz/cookiecutter-django,HandyCodeJob/hcj-django-temp,bopo/cookiecutter-django,aeikenberry/cookiecutter-django-rest-babel,jondelmil/cookiecutter-django,luzfcb/cookiecutter-django,nunchaks/cookiecutter-django,schacki/cookiecutter-django,ovidner/cookiecutter-django,asyncee/cookiecutter-django,webyneter/cookiecutter-django,ovidner/cookiecutter-django,ryankanno/cookiecutter-django,ryankanno/cookiecutter-django,ddiazpinto/cookiecutter-django,nunchaks/cookiecutter-django,ad-m/cookiecutter-django,drxos/cookiecutter-django-dokku,trungdong/cookiecutter-django,yunti/cookiecutter-django,HandyCodeJob/hcj-django-temp,jondelmil/cookiecutter-django,thisjustin/cookiecutter-django,Parbhat/cookiecutter-django-foundation,hackebrot/cookiecutter-django,schacki/cookiecutter-django,topwebmaster/cookiecutter-django,andresgz/cookiecutter-django,bopo/cookiecutter-django,jondelmil/cookiecutter-django,ddiazpinto/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,andresgz/cookiecutter-django,bopo/cookiecutter-django,webspired/cookiecutter-django,ad-m/cookiecutter-django,aeikenberry/cookiecutter-django-rest-babel,webspired/cookiecutter-django,schacki/cookiecutter-django,luzfcb/cookiecutter-django,topwebmaster/cookiecutter-django,gappsexperts/cookiecutter-django,mistalaba/cookiecutter-django,drxos/cookiecutter-django-dokku,crdoconnor/cookiecutter-django,calculuscowboy/cookiecutter-django,thisjustin/cookiecutter-django,jondelmil/cookiecutter-django,HandyCodeJob/hcj-django-temp,ingenioustechie/cookiecutter-django-openshift,pydanny/cookiecutter-django,ovidner/cookiecutter-django,hackebrot/cookiecutter-django,mistalaba/cookiecutter-django,andresgz/cookiecutter-django,Parbhat/cookiecutter-django-foundation,Parbhat/cookiecutter-django-foundation,kappataumu/cookiecutter-django,yunti/cookiecutter-django,topwebmaster/cookiecutter-django,pydanny/cookiecutter-django,hackebrot/cookiecutter-django,schacki/cookiecutter-django,HandyCodeJob/hcj-django-temp,drxos/cookiecutter-django-dokku,mjhea0/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,gappsexperts/cookiecutter-django,hairychris/cookiecutter-django,asyncee/cookiecutter-django,hairychris/cookiecutter-django,hairychris/cookiecutter-django,trungdong/cookiecutter-django,ad-m/cookiecutter-django,crdoconnor/cookiecutter-django,asyncee/cookiecutter-django,nunchaks/cookiecutter-django,aleprovencio/cookiecutter-django,webyneter/cookiecutter-django,thisjustin/cookiecutter-django,bopo/cookiecutter-django,aeikenberry/cookiecutter-django-rest-babel,luzfcb/cookiecutter-django,luzfcb/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,aeikenberry/cookiecutter-django-rest-babel,aleprovencio/cookiecutter-django,ddiazpinto/cookiecutter-django
|
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture
def context():
return {
"project_name": "My Test Project",
"repo_name": "my_test_project",
"author_name": "Test Author",
"email": "test@example.com",
"description": "A short description of the project.",
"domain_name": "example.com",
"version": "0.1.0",
"timezone": "UTC",
"now": "2015/01/13",
"year": "2015"
}
def test_default_configuration(cookies, context):
result = cookies.bake(extra_context=context)
assert result.exit_code == 0
Integrate additional checks of base.py with slight improvements
|
# -*- coding: utf-8 -*-
import os
import re
import pytest
from binaryornot.check import is_binary
PATTERN = "{{(\s?cookiecutter)[.](.*?)}}"
RE_OBJ = re.compile(PATTERN)
@pytest.fixture
def context():
return {
"project_name": "My Test Project",
"repo_name": "my_test_project",
"author_name": "Test Author",
"email": "test@example.com",
"description": "A short description of the project.",
"domain_name": "example.com",
"version": "0.1.0",
"timezone": "UTC",
"now": "2015/01/13",
"year": "2015"
}
def build_files_list(root_dir):
"""Build a list containing absolute paths to the generated files."""
return [
os.path.join(dirpath, file_path)
for dirpath, subdirs, files in os.walk(root_dir)
for file_path in files
]
def check_paths(paths):
"""Method to check all paths have correct substitutions,
used by other tests cases
"""
# Assert that no match is found in any of the files
for path in paths:
if is_binary(path):
continue
for line in open(path, 'r'):
match = RE_OBJ.search(line)
msg = "cookiecutter variable not replaced in {}"
assert match is None, msg.format(path)
def test_default_configuration(cookies, context):
result = cookies.bake(extra_context=context)
assert result.exit_code == 0
assert result.exception is None
assert result.project.basename == context['repo_name']
assert result.project.isdir()
paths = build_files_list(str(result.project))
assert paths
check_paths(paths)
|
<commit_before># -*- coding: utf-8 -*-
import pytest
@pytest.fixture
def context():
return {
"project_name": "My Test Project",
"repo_name": "my_test_project",
"author_name": "Test Author",
"email": "test@example.com",
"description": "A short description of the project.",
"domain_name": "example.com",
"version": "0.1.0",
"timezone": "UTC",
"now": "2015/01/13",
"year": "2015"
}
def test_default_configuration(cookies, context):
result = cookies.bake(extra_context=context)
assert result.exit_code == 0
<commit_msg>Integrate additional checks of base.py with slight improvements<commit_after>
|
# -*- coding: utf-8 -*-
import os
import re
import pytest
from binaryornot.check import is_binary
PATTERN = "{{(\s?cookiecutter)[.](.*?)}}"
RE_OBJ = re.compile(PATTERN)
@pytest.fixture
def context():
return {
"project_name": "My Test Project",
"repo_name": "my_test_project",
"author_name": "Test Author",
"email": "test@example.com",
"description": "A short description of the project.",
"domain_name": "example.com",
"version": "0.1.0",
"timezone": "UTC",
"now": "2015/01/13",
"year": "2015"
}
def build_files_list(root_dir):
"""Build a list containing absolute paths to the generated files."""
return [
os.path.join(dirpath, file_path)
for dirpath, subdirs, files in os.walk(root_dir)
for file_path in files
]
def check_paths(paths):
"""Method to check all paths have correct substitutions,
used by other tests cases
"""
# Assert that no match is found in any of the files
for path in paths:
if is_binary(path):
continue
for line in open(path, 'r'):
match = RE_OBJ.search(line)
msg = "cookiecutter variable not replaced in {}"
assert match is None, msg.format(path)
def test_default_configuration(cookies, context):
result = cookies.bake(extra_context=context)
assert result.exit_code == 0
assert result.exception is None
assert result.project.basename == context['repo_name']
assert result.project.isdir()
paths = build_files_list(str(result.project))
assert paths
check_paths(paths)
|
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture
def context():
return {
"project_name": "My Test Project",
"repo_name": "my_test_project",
"author_name": "Test Author",
"email": "test@example.com",
"description": "A short description of the project.",
"domain_name": "example.com",
"version": "0.1.0",
"timezone": "UTC",
"now": "2015/01/13",
"year": "2015"
}
def test_default_configuration(cookies, context):
result = cookies.bake(extra_context=context)
assert result.exit_code == 0
Integrate additional checks of base.py with slight improvements# -*- coding: utf-8 -*-
import os
import re
import pytest
from binaryornot.check import is_binary
PATTERN = "{{(\s?cookiecutter)[.](.*?)}}"
RE_OBJ = re.compile(PATTERN)
@pytest.fixture
def context():
return {
"project_name": "My Test Project",
"repo_name": "my_test_project",
"author_name": "Test Author",
"email": "test@example.com",
"description": "A short description of the project.",
"domain_name": "example.com",
"version": "0.1.0",
"timezone": "UTC",
"now": "2015/01/13",
"year": "2015"
}
def build_files_list(root_dir):
"""Build a list containing absolute paths to the generated files."""
return [
os.path.join(dirpath, file_path)
for dirpath, subdirs, files in os.walk(root_dir)
for file_path in files
]
def check_paths(paths):
"""Method to check all paths have correct substitutions,
used by other tests cases
"""
# Assert that no match is found in any of the files
for path in paths:
if is_binary(path):
continue
for line in open(path, 'r'):
match = RE_OBJ.search(line)
msg = "cookiecutter variable not replaced in {}"
assert match is None, msg.format(path)
def test_default_configuration(cookies, context):
result = cookies.bake(extra_context=context)
assert result.exit_code == 0
assert result.exception is None
assert result.project.basename == context['repo_name']
assert result.project.isdir()
paths = build_files_list(str(result.project))
assert paths
check_paths(paths)
|
<commit_before># -*- coding: utf-8 -*-
import pytest
@pytest.fixture
def context():
return {
"project_name": "My Test Project",
"repo_name": "my_test_project",
"author_name": "Test Author",
"email": "test@example.com",
"description": "A short description of the project.",
"domain_name": "example.com",
"version": "0.1.0",
"timezone": "UTC",
"now": "2015/01/13",
"year": "2015"
}
def test_default_configuration(cookies, context):
result = cookies.bake(extra_context=context)
assert result.exit_code == 0
<commit_msg>Integrate additional checks of base.py with slight improvements<commit_after># -*- coding: utf-8 -*-
import os
import re
import pytest
from binaryornot.check import is_binary
PATTERN = "{{(\s?cookiecutter)[.](.*?)}}"
RE_OBJ = re.compile(PATTERN)
@pytest.fixture
def context():
return {
"project_name": "My Test Project",
"repo_name": "my_test_project",
"author_name": "Test Author",
"email": "test@example.com",
"description": "A short description of the project.",
"domain_name": "example.com",
"version": "0.1.0",
"timezone": "UTC",
"now": "2015/01/13",
"year": "2015"
}
def build_files_list(root_dir):
"""Build a list containing absolute paths to the generated files."""
return [
os.path.join(dirpath, file_path)
for dirpath, subdirs, files in os.walk(root_dir)
for file_path in files
]
def check_paths(paths):
"""Method to check all paths have correct substitutions,
used by other tests cases
"""
# Assert that no match is found in any of the files
for path in paths:
if is_binary(path):
continue
for line in open(path, 'r'):
match = RE_OBJ.search(line)
msg = "cookiecutter variable not replaced in {}"
assert match is None, msg.format(path)
def test_default_configuration(cookies, context):
result = cookies.bake(extra_context=context)
assert result.exit_code == 0
assert result.exception is None
assert result.project.basename == context['repo_name']
assert result.project.isdir()
paths = build_files_list(str(result.project))
assert paths
check_paths(paths)
|
cf457a8ba688b33748bb03baa5a77d9b4e638e9d
|
emote/emote.py
|
emote/emote.py
|
""" A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def main():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-p','--web_port')
args = parser.parse_args()
# Print help if no cli args are specified.
if len(sys.argv) < 2:
parser.print_help()
if __name__ == "__main__":
main()
|
""" A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def parse_arguments():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-l','--list', action="store_true",
help="List all available emotes.")
# Print help if no cli args are specified.
if len(sys.argv) < 2:
parser.print_help()
return parser.parse_args()
def list_emotes():
print [e for e in emotes.keys()]
print [e for e in emotes.values()]
def main():
args = parse_arguments()
if args.list:
list_emotes()
if __name__ == "__main__":
main()
|
Add partially implemented list option.
|
Add partially implemented list option.
|
Python
|
mit
|
d6e/emotion
|
""" A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def main():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-p','--web_port')
args = parser.parse_args()
# Print help if no cli args are specified.
if len(sys.argv) < 2:
parser.print_help()
if __name__ == "__main__":
main()
Add partially implemented list option.
|
""" A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def parse_arguments():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-l','--list', action="store_true",
help="List all available emotes.")
# Print help if no cli args are specified.
if len(sys.argv) < 2:
parser.print_help()
return parser.parse_args()
def list_emotes():
print [e for e in emotes.keys()]
print [e for e in emotes.values()]
def main():
args = parse_arguments()
if args.list:
list_emotes()
if __name__ == "__main__":
main()
|
<commit_before>""" A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def main():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-p','--web_port')
args = parser.parse_args()
# Print help if no cli args are specified.
if len(sys.argv) < 2:
parser.print_help()
if __name__ == "__main__":
main()
<commit_msg>Add partially implemented list option.<commit_after>
|
""" A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def parse_arguments():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-l','--list', action="store_true",
help="List all available emotes.")
# Print help if no cli args are specified.
if len(sys.argv) < 2:
parser.print_help()
return parser.parse_args()
def list_emotes():
print [e for e in emotes.keys()]
print [e for e in emotes.values()]
def main():
args = parse_arguments()
if args.list:
list_emotes()
if __name__ == "__main__":
main()
|
""" A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def main():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-p','--web_port')
args = parser.parse_args()
# Print help if no cli args are specified.
if len(sys.argv) < 2:
parser.print_help()
if __name__ == "__main__":
main()
Add partially implemented list option.""" A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def parse_arguments():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-l','--list', action="store_true",
help="List all available emotes.")
# Print help if no cli args are specified.
if len(sys.argv) < 2:
parser.print_help()
return parser.parse_args()
def list_emotes():
print [e for e in emotes.keys()]
print [e for e in emotes.values()]
def main():
args = parse_arguments()
if args.list:
list_emotes()
if __name__ == "__main__":
main()
|
<commit_before>""" A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def main():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-p','--web_port')
args = parser.parse_args()
# Print help if no cli args are specified.
if len(sys.argv) < 2:
parser.print_help()
if __name__ == "__main__":
main()
<commit_msg>Add partially implemented list option.<commit_after>""" A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def parse_arguments():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-l','--list', action="store_true",
help="List all available emotes.")
# Print help if no cli args are specified.
if len(sys.argv) < 2:
parser.print_help()
return parser.parse_args()
def list_emotes():
print [e for e in emotes.keys()]
print [e for e in emotes.values()]
def main():
args = parse_arguments()
if args.list:
list_emotes()
if __name__ == "__main__":
main()
|
f76a66809237af29de8bfaeacd017d8f8b60df78
|
python/http_checker.py
|
python/http_checker.py
|
import unittest
import requests
import lxml.html
class TestHtmlTask(unittest.TestCase):
def setUp(self):
self.ulr_google = "https://www.google.com.ua/"
self.url_habr = "http://habrahabr.ru/hub/gdev/"
def test_1(self):
expected_response_1 = 200
r = requests.get(self.ulr_google)
self.assertEqual(r.status_code, expected_response_1)
def test_2(self):
expected_response_2 = "Game Development"
t = lxml.html.parse(self.url_habr)
title = t.find(".//title").text.split('/')
self.assertEqual(title[0].rstrip(), expected_response_2)
if __name__ == '__main__':
unittest.main()
|
import unittest
import requests
import lxml.html
import xmlrunner
class TestHtmlTask(unittest.TestCase):
def setUp(self):
self.urls = open("urls.txt", 'r')
self.url_google = self.urls.readline()
self.url_habr = self.urls.readline()
self.urls.close()
def test_1(self):
expected_response_1 = 200
r = requests.get(self.url_google.strip())
self.assertEqual(r.status_code, expected_response_1, msg='{0}, {1}')
def test_2(self):
expected_response_2 = "Game Development"
t = lxml.html.parse(self.url_habr)
title = t.find(".//title").text.split('/')
self.assertEqual(title[0].rstrip(), expected_response_2)
if __name__ == '__main__':
unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
|
Save test results to XML added
|
Save test results to XML added
|
Python
|
mit
|
amazpyel/sqa_training,amazpyel/sqa_training,amazpyel/sqa_training
|
import unittest
import requests
import lxml.html
class TestHtmlTask(unittest.TestCase):
def setUp(self):
self.ulr_google = "https://www.google.com.ua/"
self.url_habr = "http://habrahabr.ru/hub/gdev/"
def test_1(self):
expected_response_1 = 200
r = requests.get(self.ulr_google)
self.assertEqual(r.status_code, expected_response_1)
def test_2(self):
expected_response_2 = "Game Development"
t = lxml.html.parse(self.url_habr)
title = t.find(".//title").text.split('/')
self.assertEqual(title[0].rstrip(), expected_response_2)
if __name__ == '__main__':
unittest.main()
Save test results to XML added
|
import unittest
import requests
import lxml.html
import xmlrunner
class TestHtmlTask(unittest.TestCase):
def setUp(self):
self.urls = open("urls.txt", 'r')
self.url_google = self.urls.readline()
self.url_habr = self.urls.readline()
self.urls.close()
def test_1(self):
expected_response_1 = 200
r = requests.get(self.url_google.strip())
self.assertEqual(r.status_code, expected_response_1, msg='{0}, {1}')
def test_2(self):
expected_response_2 = "Game Development"
t = lxml.html.parse(self.url_habr)
title = t.find(".//title").text.split('/')
self.assertEqual(title[0].rstrip(), expected_response_2)
if __name__ == '__main__':
unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
|
<commit_before>import unittest
import requests
import lxml.html
class TestHtmlTask(unittest.TestCase):
def setUp(self):
self.ulr_google = "https://www.google.com.ua/"
self.url_habr = "http://habrahabr.ru/hub/gdev/"
def test_1(self):
expected_response_1 = 200
r = requests.get(self.ulr_google)
self.assertEqual(r.status_code, expected_response_1)
def test_2(self):
expected_response_2 = "Game Development"
t = lxml.html.parse(self.url_habr)
title = t.find(".//title").text.split('/')
self.assertEqual(title[0].rstrip(), expected_response_2)
if __name__ == '__main__':
unittest.main()
<commit_msg>Save test results to XML added<commit_after>
|
import unittest
import requests
import lxml.html
import xmlrunner
class TestHtmlTask(unittest.TestCase):
def setUp(self):
self.urls = open("urls.txt", 'r')
self.url_google = self.urls.readline()
self.url_habr = self.urls.readline()
self.urls.close()
def test_1(self):
expected_response_1 = 200
r = requests.get(self.url_google.strip())
self.assertEqual(r.status_code, expected_response_1, msg='{0}, {1}')
def test_2(self):
expected_response_2 = "Game Development"
t = lxml.html.parse(self.url_habr)
title = t.find(".//title").text.split('/')
self.assertEqual(title[0].rstrip(), expected_response_2)
if __name__ == '__main__':
unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
|
import unittest
import requests
import lxml.html
class TestHtmlTask(unittest.TestCase):
def setUp(self):
self.ulr_google = "https://www.google.com.ua/"
self.url_habr = "http://habrahabr.ru/hub/gdev/"
def test_1(self):
expected_response_1 = 200
r = requests.get(self.ulr_google)
self.assertEqual(r.status_code, expected_response_1)
def test_2(self):
expected_response_2 = "Game Development"
t = lxml.html.parse(self.url_habr)
title = t.find(".//title").text.split('/')
self.assertEqual(title[0].rstrip(), expected_response_2)
if __name__ == '__main__':
unittest.main()
Save test results to XML addedimport unittest
import requests
import lxml.html
import xmlrunner
class TestHtmlTask(unittest.TestCase):
def setUp(self):
self.urls = open("urls.txt", 'r')
self.url_google = self.urls.readline()
self.url_habr = self.urls.readline()
self.urls.close()
def test_1(self):
expected_response_1 = 200
r = requests.get(self.url_google.strip())
self.assertEqual(r.status_code, expected_response_1, msg='{0}, {1}')
def test_2(self):
expected_response_2 = "Game Development"
t = lxml.html.parse(self.url_habr)
title = t.find(".//title").text.split('/')
self.assertEqual(title[0].rstrip(), expected_response_2)
if __name__ == '__main__':
unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
|
<commit_before>import unittest
import requests
import lxml.html
class TestHtmlTask(unittest.TestCase):
def setUp(self):
self.ulr_google = "https://www.google.com.ua/"
self.url_habr = "http://habrahabr.ru/hub/gdev/"
def test_1(self):
expected_response_1 = 200
r = requests.get(self.ulr_google)
self.assertEqual(r.status_code, expected_response_1)
def test_2(self):
expected_response_2 = "Game Development"
t = lxml.html.parse(self.url_habr)
title = t.find(".//title").text.split('/')
self.assertEqual(title[0].rstrip(), expected_response_2)
if __name__ == '__main__':
unittest.main()
<commit_msg>Save test results to XML added<commit_after>import unittest
import requests
import lxml.html
import xmlrunner
class TestHtmlTask(unittest.TestCase):
def setUp(self):
self.urls = open("urls.txt", 'r')
self.url_google = self.urls.readline()
self.url_habr = self.urls.readline()
self.urls.close()
def test_1(self):
expected_response_1 = 200
r = requests.get(self.url_google.strip())
self.assertEqual(r.status_code, expected_response_1, msg='{0}, {1}')
def test_2(self):
expected_response_2 = "Game Development"
t = lxml.html.parse(self.url_habr)
title = t.find(".//title").text.split('/')
self.assertEqual(title[0].rstrip(), expected_response_2)
if __name__ == '__main__':
unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
|
ec5bcd6a2ea41651e9a64ee1e5315b3bb4d06306
|
hydroshare/urls.py
|
hydroshare/urls.py
|
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
admin.autodiscover()
urlpatterns = [
url("^mmh-admin/", include(admin.site.urls)),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'', include('myhpom.urls', namespace='myhpom')),
]
# HMMM....? Shouldn't these be served by nginx for debug False?
if settings.DEBUG is False: # if DEBUG is True it will be served automatically
urlpatterns += [
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
]
|
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
admin.autodiscover()
urlpatterns = [
url("^mmh-admin/", include(admin.site.urls)),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'', include('myhpom.urls', namespace='myhpom')),
]
# These should be served by nginx for deployed environments,
# presumably this is here to allow for running without DEBUG
# on in local dev environments.
if settings.DEBUG is False: # if DEBUG is True it will be served automatically
urlpatterns += [
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
]
|
Clarify comment around inclusion of static serving
|
Clarify comment around inclusion of static serving
|
Python
|
bsd-3-clause
|
ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM
|
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
admin.autodiscover()
urlpatterns = [
url("^mmh-admin/", include(admin.site.urls)),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'', include('myhpom.urls', namespace='myhpom')),
]
# HMMM....? Shouldn't these be served by nginx for debug False?
if settings.DEBUG is False: # if DEBUG is True it will be served automatically
urlpatterns += [
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
]
Clarify comment around inclusion of static serving
|
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
admin.autodiscover()
urlpatterns = [
url("^mmh-admin/", include(admin.site.urls)),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'', include('myhpom.urls', namespace='myhpom')),
]
# These should be served by nginx for deployed environments,
# presumably this is here to allow for running without DEBUG
# on in local dev environments.
if settings.DEBUG is False: # if DEBUG is True it will be served automatically
urlpatterns += [
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
]
|
<commit_before>from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
admin.autodiscover()
urlpatterns = [
url("^mmh-admin/", include(admin.site.urls)),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'', include('myhpom.urls', namespace='myhpom')),
]
# HMMM....? Shouldn't these be served by nginx for debug False?
if settings.DEBUG is False: # if DEBUG is True it will be served automatically
urlpatterns += [
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
]
<commit_msg>Clarify comment around inclusion of static serving<commit_after>
|
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
admin.autodiscover()
urlpatterns = [
url("^mmh-admin/", include(admin.site.urls)),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'', include('myhpom.urls', namespace='myhpom')),
]
# These should be served by nginx for deployed environments,
# presumably this is here to allow for running without DEBUG
# on in local dev environments.
if settings.DEBUG is False: # if DEBUG is True it will be served automatically
urlpatterns += [
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
]
|
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
admin.autodiscover()
urlpatterns = [
url("^mmh-admin/", include(admin.site.urls)),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'', include('myhpom.urls', namespace='myhpom')),
]
# HMMM....? Shouldn't these be served by nginx for debug False?
if settings.DEBUG is False: # if DEBUG is True it will be served automatically
urlpatterns += [
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
]
Clarify comment around inclusion of static servingfrom __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
admin.autodiscover()
urlpatterns = [
url("^mmh-admin/", include(admin.site.urls)),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'', include('myhpom.urls', namespace='myhpom')),
]
# These should be served by nginx for deployed environments,
# presumably this is here to allow for running without DEBUG
# on in local dev environments.
if settings.DEBUG is False: # if DEBUG is True it will be served automatically
urlpatterns += [
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
]
|
<commit_before>from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
admin.autodiscover()
urlpatterns = [
url("^mmh-admin/", include(admin.site.urls)),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'', include('myhpom.urls', namespace='myhpom')),
]
# HMMM....? Shouldn't these be served by nginx for debug False?
if settings.DEBUG is False: # if DEBUG is True it will be served automatically
urlpatterns += [
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
]
<commit_msg>Clarify comment around inclusion of static serving<commit_after>from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
admin.autodiscover()
urlpatterns = [
url("^mmh-admin/", include(admin.site.urls)),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'', include('myhpom.urls', namespace='myhpom')),
]
# These should be served by nginx for deployed environments,
# presumably this is here to allow for running without DEBUG
# on in local dev environments.
if settings.DEBUG is False: # if DEBUG is True it will be served automatically
urlpatterns += [
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
]
|
9864f9c60e65fa73f15504950df5ce71baf23dcb
|
ideascube/utils.py
|
ideascube/utils.py
|
import sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string(
namespace='server', key='site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
|
import sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string('server', 'site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
|
Use the API as it was intended
|
Use the API as it was intended
|
Python
|
agpl-3.0
|
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
|
import sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string(
namespace='server', key='site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
Use the API as it was intended
|
import sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string('server', 'site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
|
<commit_before>import sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string(
namespace='server', key='site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
<commit_msg>Use the API as it was intended<commit_after>
|
import sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string('server', 'site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
|
import sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string(
namespace='server', key='site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
Use the API as it was intendedimport sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string('server', 'site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
|
<commit_before>import sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string(
namespace='server', key='site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
<commit_msg>Use the API as it was intended<commit_after>import sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string('server', 'site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
|
088eb8d51f0092c9cfa62c490ae5a9ad111061e0
|
webapp/byceps/util/templatefilters.py
|
webapp/byceps/util/templatefilters.py
|
# -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from . import dateformat, money
def dim(value):
"""Render value in a way so that it looks dimmed."""
return '<span class="dimmed">{}</span>'.format(value)
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
|
# -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from jinja2 import evalcontextfilter, Markup
from . import dateformat, money
@evalcontextfilter
def dim(eval_ctx, value):
"""Render value in a way so that it looks dimmed."""
dimmed = '<span class="dimmed">{}</span>'.format(value)
return Markup(dimmed) if eval_ctx.autoescape else dimmed
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
|
Mark HTML generated by custom template filter as safe if auto-escaping is enabled.
|
Mark HTML generated by custom template filter as safe if auto-escaping is enabled.
|
Python
|
bsd-3-clause
|
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps
|
# -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from . import dateformat, money
def dim(value):
"""Render value in a way so that it looks dimmed."""
return '<span class="dimmed">{}</span>'.format(value)
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
Mark HTML generated by custom template filter as safe if auto-escaping is enabled.
|
# -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from jinja2 import evalcontextfilter, Markup
from . import dateformat, money
@evalcontextfilter
def dim(eval_ctx, value):
"""Render value in a way so that it looks dimmed."""
dimmed = '<span class="dimmed">{}</span>'.format(value)
return Markup(dimmed) if eval_ctx.autoescape else dimmed
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
|
<commit_before># -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from . import dateformat, money
def dim(value):
"""Render value in a way so that it looks dimmed."""
return '<span class="dimmed">{}</span>'.format(value)
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
<commit_msg>Mark HTML generated by custom template filter as safe if auto-escaping is enabled.<commit_after>
|
# -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from jinja2 import evalcontextfilter, Markup
from . import dateformat, money
@evalcontextfilter
def dim(eval_ctx, value):
"""Render value in a way so that it looks dimmed."""
dimmed = '<span class="dimmed">{}</span>'.format(value)
return Markup(dimmed) if eval_ctx.autoescape else dimmed
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
|
# -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from . import dateformat, money
def dim(value):
"""Render value in a way so that it looks dimmed."""
return '<span class="dimmed">{}</span>'.format(value)
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
Mark HTML generated by custom template filter as safe if auto-escaping is enabled.# -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from jinja2 import evalcontextfilter, Markup
from . import dateformat, money
@evalcontextfilter
def dim(eval_ctx, value):
"""Render value in a way so that it looks dimmed."""
dimmed = '<span class="dimmed">{}</span>'.format(value)
return Markup(dimmed) if eval_ctx.autoescape else dimmed
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
|
<commit_before># -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from . import dateformat, money
def dim(value):
"""Render value in a way so that it looks dimmed."""
return '<span class="dimmed">{}</span>'.format(value)
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
<commit_msg>Mark HTML generated by custom template filter as safe if auto-escaping is enabled.<commit_after># -*- coding: utf-8 -*-
"""
byceps.util.templatefilters
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provide and register custom template filters.
:Copyright: 2006-2015 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from jinja2 import evalcontextfilter, Markup
from . import dateformat, money
@evalcontextfilter
def dim(eval_ctx, value):
"""Render value in a way so that it looks dimmed."""
dimmed = '<span class="dimmed">{}</span>'.format(value)
return Markup(dimmed) if eval_ctx.autoescape else dimmed
def register(app):
"""Make functions available as template filters."""
functions = [
dateformat.format_custom,
dateformat.format_date_iso,
dateformat.format_date_short,
dateformat.format_date_long,
dateformat.format_datetime_iso,
dateformat.format_datetime_short,
dateformat.format_datetime_long,
dateformat.format_time,
dim,
money.format_euro_amount,
]
for f in functions:
app.add_template_filter(f)
|
78edb47cc53e52504f2ceb8efa23ae1e50b66946
|
synapse/media/v1/__init__.py
|
synapse/media/v1/__init__.py
|
# -*- coding: utf-8 -*-
import PIL.Image
# check for JPEG support.
try:
PIL.Image._getdecoder("rgb", "jpeg", None)
except IOError as e:
if str(e).startswith("decoder jpeg not available"):
raise Exception(
"FATAL: jpeg codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
# check for PNG support.
try:
PIL.Image._getdecoder("rgb", "zip", None)
except IOError as e:
if str(e).startswith("decoder zip not available"):
raise Exception(
"FATAL: zip codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
|
Add runtime checks on startup to enforce that JPEG/PNG support is included when installing pillow.
|
SYN-208/SYN-228: Add runtime checks on startup to enforce that JPEG/PNG support is included when installing pillow.
|
Python
|
apache-2.0
|
rzr/synapse,matrix-org/synapse,illicitonion/synapse,rzr/synapse,matrix-org/synapse,howethomas/synapse,matrix-org/synapse,iot-factory/synapse,matrix-org/synapse,rzr/synapse,howethomas/synapse,illicitonion/synapse,matrix-org/synapse,matrix-org/synapse,howethomas/synapse,TribeMedia/synapse,iot-factory/synapse,iot-factory/synapse,illicitonion/synapse,howethomas/synapse,TribeMedia/synapse,howethomas/synapse,TribeMedia/synapse,rzr/synapse,iot-factory/synapse,rzr/synapse,illicitonion/synapse,iot-factory/synapse,illicitonion/synapse,TribeMedia/synapse,TribeMedia/synapse
|
SYN-208/SYN-228: Add runtime checks on startup to enforce that JPEG/PNG support is included when installing pillow.
|
# -*- coding: utf-8 -*-
import PIL.Image
# check for JPEG support.
try:
PIL.Image._getdecoder("rgb", "jpeg", None)
except IOError as e:
if str(e).startswith("decoder jpeg not available"):
raise Exception(
"FATAL: jpeg codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
# check for PNG support.
try:
PIL.Image._getdecoder("rgb", "zip", None)
except IOError as e:
if str(e).startswith("decoder zip not available"):
raise Exception(
"FATAL: zip codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
|
<commit_before><commit_msg>SYN-208/SYN-228: Add runtime checks on startup to enforce that JPEG/PNG support is included when installing pillow.<commit_after>
|
# -*- coding: utf-8 -*-
import PIL.Image
# check for JPEG support.
try:
PIL.Image._getdecoder("rgb", "jpeg", None)
except IOError as e:
if str(e).startswith("decoder jpeg not available"):
raise Exception(
"FATAL: jpeg codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
# check for PNG support.
try:
PIL.Image._getdecoder("rgb", "zip", None)
except IOError as e:
if str(e).startswith("decoder zip not available"):
raise Exception(
"FATAL: zip codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
|
SYN-208/SYN-228: Add runtime checks on startup to enforce that JPEG/PNG support is included when installing pillow.# -*- coding: utf-8 -*-
import PIL.Image
# check for JPEG support.
try:
PIL.Image._getdecoder("rgb", "jpeg", None)
except IOError as e:
if str(e).startswith("decoder jpeg not available"):
raise Exception(
"FATAL: jpeg codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
# check for PNG support.
try:
PIL.Image._getdecoder("rgb", "zip", None)
except IOError as e:
if str(e).startswith("decoder zip not available"):
raise Exception(
"FATAL: zip codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
|
<commit_before><commit_msg>SYN-208/SYN-228: Add runtime checks on startup to enforce that JPEG/PNG support is included when installing pillow.<commit_after># -*- coding: utf-8 -*-
import PIL.Image
# check for JPEG support.
try:
PIL.Image._getdecoder("rgb", "jpeg", None)
except IOError as e:
if str(e).startswith("decoder jpeg not available"):
raise Exception(
"FATAL: jpeg codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
# check for PNG support.
try:
PIL.Image._getdecoder("rgb", "zip", None)
except IOError as e:
if str(e).startswith("decoder zip not available"):
raise Exception(
"FATAL: zip codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
|
|
724c3548d657c10de15eb830810a89b94af6d978
|
dikedata_api/parsers.py
|
dikedata_api/parsers.py
|
# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
from rest_framework.parsers import BaseParser, DataAndFiles
class SimpleFileUploadParser(BaseParser):
"""
A naive raw file upload parser.
"""
media_type = '*/*' # Accept anything
def parse(self, stream, media_type=None, parser_context=None):
content = stream.read()
return DataAndFiles({}, content)
class CSVParser(BaseParser):
media_type = 'text/csv'
def parse(self, stream, media_type=None, parser_context=None):
content = [line.strip().split(';') \
for line in stream.read().split('\n') if line.strip()]
data = [{'uuid':row[1].strip('"'),
'events':[{'datetime':row[0].strip('"'),
'value':row[2].strip('"')}]}
for row in content]
return DataAndFiles(data, None)
|
# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
from rest_framework.parsers import BaseParser, DataAndFiles
class SimpleFileUploadParser(BaseParser):
"""
A naive raw file upload parser.
"""
media_type = '*/*' # Accept anything
def parse(self, stream, media_type=None, parser_context=None):
content = stream.read()
return DataAndFiles({}, content)
class CSVParser(BaseParser):
media_type = 'text/csv'
def parse(self, stream, media_type=None, parser_context=None):
content = [line.strip().split(',') \
for line in stream.read().split('\n') if line.strip()]
data = [{'uuid':row[1].strip('"'),
'events':[{'datetime':row[0].strip('"'),
'value':row[2].strip('"')}]}
for row in content]
return DataAndFiles(data, None)
|
Use comma in CSV POST.
|
Use comma in CSV POST.
|
Python
|
mit
|
ddsc/dikedata-api
|
# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
from rest_framework.parsers import BaseParser, DataAndFiles
class SimpleFileUploadParser(BaseParser):
"""
A naive raw file upload parser.
"""
media_type = '*/*' # Accept anything
def parse(self, stream, media_type=None, parser_context=None):
content = stream.read()
return DataAndFiles({}, content)
class CSVParser(BaseParser):
media_type = 'text/csv'
def parse(self, stream, media_type=None, parser_context=None):
content = [line.strip().split(';') \
for line in stream.read().split('\n') if line.strip()]
data = [{'uuid':row[1].strip('"'),
'events':[{'datetime':row[0].strip('"'),
'value':row[2].strip('"')}]}
for row in content]
return DataAndFiles(data, None)
Use comma in CSV POST.
|
# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
from rest_framework.parsers import BaseParser, DataAndFiles
class SimpleFileUploadParser(BaseParser):
"""
A naive raw file upload parser.
"""
media_type = '*/*' # Accept anything
def parse(self, stream, media_type=None, parser_context=None):
content = stream.read()
return DataAndFiles({}, content)
class CSVParser(BaseParser):
media_type = 'text/csv'
def parse(self, stream, media_type=None, parser_context=None):
content = [line.strip().split(',') \
for line in stream.read().split('\n') if line.strip()]
data = [{'uuid':row[1].strip('"'),
'events':[{'datetime':row[0].strip('"'),
'value':row[2].strip('"')}]}
for row in content]
return DataAndFiles(data, None)
|
<commit_before># (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
from rest_framework.parsers import BaseParser, DataAndFiles
class SimpleFileUploadParser(BaseParser):
"""
A naive raw file upload parser.
"""
media_type = '*/*' # Accept anything
def parse(self, stream, media_type=None, parser_context=None):
content = stream.read()
return DataAndFiles({}, content)
class CSVParser(BaseParser):
media_type = 'text/csv'
def parse(self, stream, media_type=None, parser_context=None):
content = [line.strip().split(';') \
for line in stream.read().split('\n') if line.strip()]
data = [{'uuid':row[1].strip('"'),
'events':[{'datetime':row[0].strip('"'),
'value':row[2].strip('"')}]}
for row in content]
return DataAndFiles(data, None)
<commit_msg>Use comma in CSV POST.<commit_after>
|
# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
from rest_framework.parsers import BaseParser, DataAndFiles
class SimpleFileUploadParser(BaseParser):
"""
A naive raw file upload parser.
"""
media_type = '*/*' # Accept anything
def parse(self, stream, media_type=None, parser_context=None):
content = stream.read()
return DataAndFiles({}, content)
class CSVParser(BaseParser):
media_type = 'text/csv'
def parse(self, stream, media_type=None, parser_context=None):
content = [line.strip().split(',') \
for line in stream.read().split('\n') if line.strip()]
data = [{'uuid':row[1].strip('"'),
'events':[{'datetime':row[0].strip('"'),
'value':row[2].strip('"')}]}
for row in content]
return DataAndFiles(data, None)
|
# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
from rest_framework.parsers import BaseParser, DataAndFiles
class SimpleFileUploadParser(BaseParser):
"""
A naive raw file upload parser.
"""
media_type = '*/*' # Accept anything
def parse(self, stream, media_type=None, parser_context=None):
content = stream.read()
return DataAndFiles({}, content)
class CSVParser(BaseParser):
media_type = 'text/csv'
def parse(self, stream, media_type=None, parser_context=None):
content = [line.strip().split(';') \
for line in stream.read().split('\n') if line.strip()]
data = [{'uuid':row[1].strip('"'),
'events':[{'datetime':row[0].strip('"'),
'value':row[2].strip('"')}]}
for row in content]
return DataAndFiles(data, None)
Use comma in CSV POST.# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
from rest_framework.parsers import BaseParser, DataAndFiles
class SimpleFileUploadParser(BaseParser):
"""
A naive raw file upload parser.
"""
media_type = '*/*' # Accept anything
def parse(self, stream, media_type=None, parser_context=None):
content = stream.read()
return DataAndFiles({}, content)
class CSVParser(BaseParser):
media_type = 'text/csv'
def parse(self, stream, media_type=None, parser_context=None):
content = [line.strip().split(',') \
for line in stream.read().split('\n') if line.strip()]
data = [{'uuid':row[1].strip('"'),
'events':[{'datetime':row[0].strip('"'),
'value':row[2].strip('"')}]}
for row in content]
return DataAndFiles(data, None)
|
<commit_before># (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
from rest_framework.parsers import BaseParser, DataAndFiles
class SimpleFileUploadParser(BaseParser):
"""
A naive raw file upload parser.
"""
media_type = '*/*' # Accept anything
def parse(self, stream, media_type=None, parser_context=None):
content = stream.read()
return DataAndFiles({}, content)
class CSVParser(BaseParser):
media_type = 'text/csv'
def parse(self, stream, media_type=None, parser_context=None):
content = [line.strip().split(';') \
for line in stream.read().split('\n') if line.strip()]
data = [{'uuid':row[1].strip('"'),
'events':[{'datetime':row[0].strip('"'),
'value':row[2].strip('"')}]}
for row in content]
return DataAndFiles(data, None)
<commit_msg>Use comma in CSV POST.<commit_after># (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
from rest_framework.parsers import BaseParser, DataAndFiles
class SimpleFileUploadParser(BaseParser):
"""
A naive raw file upload parser.
"""
media_type = '*/*' # Accept anything
def parse(self, stream, media_type=None, parser_context=None):
content = stream.read()
return DataAndFiles({}, content)
class CSVParser(BaseParser):
media_type = 'text/csv'
def parse(self, stream, media_type=None, parser_context=None):
content = [line.strip().split(',') \
for line in stream.read().split('\n') if line.strip()]
data = [{'uuid':row[1].strip('"'),
'events':[{'datetime':row[0].strip('"'),
'value':row[2].strip('"')}]}
for row in content]
return DataAndFiles(data, None)
|
6d894dc15af674b7814be32664354fb79faf227f
|
gateway_mac.py
|
gateway_mac.py
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(default_gw))
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(g))
|
Fix bugs with code for multiple gateways
|
Fix bugs with code for multiple gateways
|
Python
|
mit
|
nulledbyte/scripts
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(default_gw))
Fix bugs with code for multiple gateways
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(g))
|
<commit_before>import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(default_gw))
<commit_msg>Fix bugs with code for multiple gateways<commit_after>
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(g))
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(default_gw))
Fix bugs with code for multiple gatewaysimport socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(g))
|
<commit_before>import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(default_gw))
<commit_msg>Fix bugs with code for multiple gateways<commit_after>import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(g))
|
706ad8367488104e2e5c32908faaf85a5fb5e00a
|
varify/context_processors.py
|
varify/context_processors.py
|
import os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN')
if SENTRY_PUBLIC_DSN:
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
|
import os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN', None)
if SENTRY_PUBLIC_DSN:
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
|
Add default argument when looking up sentry dsn setting
|
Add default argument when looking up sentry dsn setting
|
Python
|
bsd-2-clause
|
chop-dbhi/varify,chop-dbhi/varify,chop-dbhi/varify,chop-dbhi/varify
|
import os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN')
if SENTRY_PUBLIC_DSN:
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
Add default argument when looking up sentry dsn setting
|
import os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN', None)
if SENTRY_PUBLIC_DSN:
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
|
<commit_before>import os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN')
if SENTRY_PUBLIC_DSN:
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
<commit_msg>Add default argument when looking up sentry dsn setting<commit_after>
|
import os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN', None)
if SENTRY_PUBLIC_DSN:
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
|
import os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN')
if SENTRY_PUBLIC_DSN:
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
Add default argument when looking up sentry dsn settingimport os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN', None)
if SENTRY_PUBLIC_DSN:
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
|
<commit_before>import os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN')
if SENTRY_PUBLIC_DSN:
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
<commit_msg>Add default argument when looking up sentry dsn setting<commit_after>import os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN', None)
if SENTRY_PUBLIC_DSN:
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
|
f857771d98627722bc9c81ee3d039ab11c3e8afb
|
jsonfield/utils.py
|
jsonfield/utils.py
|
import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder, self).default(obj)
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
if isinstance(o, Decimal):
return str(o)
if isinstance(o, datetime.datetime):
if o.tzinfo:
return o.strftime('%Y-%m-%dT%H:%M:%S%z')
return o.strftime("%Y-%m-%dT%H:%M:%S")
if isinstance(o, datetime.date):
return o.strftime("%Y-%m-%d")
if isinstance(o, datetime.time):
if o.tzinfo:
return o.strftime('%H:%M:%S%z')
return o.strftime("%H:%M:%S")
raise TypeError(repr(o) + " is not JSON serializable")
|
import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
DATETIME = (datetime.datetime,)
DATE = (datetime.date,)
TIME = (datetime.time,)
try:
import freezegun.api
except ImportError:
pass
else:
DATETIME += (freezegun.api.FakeDatetime,)
DATE += (freezegun.api.FakeDate,)
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, DATETIME):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder, self).default(obj)
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
if isinstance(o, Decimal):
return str(o)
if isinstance(o, DATETIME):
if o.tzinfo:
return o.strftime('%Y-%m-%dT%H:%M:%S%z')
return o.strftime("%Y-%m-%dT%H:%M:%S")
if isinstance(o, DATE):
return o.strftime("%Y-%m-%d")
if isinstance(o, TIME):
if o.tzinfo:
return o.strftime('%H:%M:%S%z')
return o.strftime("%H:%M:%S")
raise TypeError(repr(o) + " is not JSON serializable")
|
Make compatible with freezegun when testing.
|
Make compatible with freezegun when testing.
|
Python
|
bsd-3-clause
|
SideStudios/django-jsonfield
|
import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder, self).default(obj)
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
if isinstance(o, Decimal):
return str(o)
if isinstance(o, datetime.datetime):
if o.tzinfo:
return o.strftime('%Y-%m-%dT%H:%M:%S%z')
return o.strftime("%Y-%m-%dT%H:%M:%S")
if isinstance(o, datetime.date):
return o.strftime("%Y-%m-%d")
if isinstance(o, datetime.time):
if o.tzinfo:
return o.strftime('%H:%M:%S%z')
return o.strftime("%H:%M:%S")
raise TypeError(repr(o) + " is not JSON serializable")
Make compatible with freezegun when testing.
|
import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
DATETIME = (datetime.datetime,)
DATE = (datetime.date,)
TIME = (datetime.time,)
try:
import freezegun.api
except ImportError:
pass
else:
DATETIME += (freezegun.api.FakeDatetime,)
DATE += (freezegun.api.FakeDate,)
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, DATETIME):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder, self).default(obj)
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
if isinstance(o, Decimal):
return str(o)
if isinstance(o, DATETIME):
if o.tzinfo:
return o.strftime('%Y-%m-%dT%H:%M:%S%z')
return o.strftime("%Y-%m-%dT%H:%M:%S")
if isinstance(o, DATE):
return o.strftime("%Y-%m-%d")
if isinstance(o, TIME):
if o.tzinfo:
return o.strftime('%H:%M:%S%z')
return o.strftime("%H:%M:%S")
raise TypeError(repr(o) + " is not JSON serializable")
|
<commit_before>import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder, self).default(obj)
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
if isinstance(o, Decimal):
return str(o)
if isinstance(o, datetime.datetime):
if o.tzinfo:
return o.strftime('%Y-%m-%dT%H:%M:%S%z')
return o.strftime("%Y-%m-%dT%H:%M:%S")
if isinstance(o, datetime.date):
return o.strftime("%Y-%m-%d")
if isinstance(o, datetime.time):
if o.tzinfo:
return o.strftime('%H:%M:%S%z')
return o.strftime("%H:%M:%S")
raise TypeError(repr(o) + " is not JSON serializable")
<commit_msg>Make compatible with freezegun when testing.<commit_after>
|
import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
DATETIME = (datetime.datetime,)
DATE = (datetime.date,)
TIME = (datetime.time,)
try:
import freezegun.api
except ImportError:
pass
else:
DATETIME += (freezegun.api.FakeDatetime,)
DATE += (freezegun.api.FakeDate,)
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, DATETIME):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder, self).default(obj)
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
if isinstance(o, Decimal):
return str(o)
if isinstance(o, DATETIME):
if o.tzinfo:
return o.strftime('%Y-%m-%dT%H:%M:%S%z')
return o.strftime("%Y-%m-%dT%H:%M:%S")
if isinstance(o, DATE):
return o.strftime("%Y-%m-%d")
if isinstance(o, TIME):
if o.tzinfo:
return o.strftime('%H:%M:%S%z')
return o.strftime("%H:%M:%S")
raise TypeError(repr(o) + " is not JSON serializable")
|
import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder, self).default(obj)
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
if isinstance(o, Decimal):
return str(o)
if isinstance(o, datetime.datetime):
if o.tzinfo:
return o.strftime('%Y-%m-%dT%H:%M:%S%z')
return o.strftime("%Y-%m-%dT%H:%M:%S")
if isinstance(o, datetime.date):
return o.strftime("%Y-%m-%d")
if isinstance(o, datetime.time):
if o.tzinfo:
return o.strftime('%H:%M:%S%z')
return o.strftime("%H:%M:%S")
raise TypeError(repr(o) + " is not JSON serializable")
Make compatible with freezegun when testing.import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
DATETIME = (datetime.datetime,)
DATE = (datetime.date,)
TIME = (datetime.time,)
try:
import freezegun.api
except ImportError:
pass
else:
DATETIME += (freezegun.api.FakeDatetime,)
DATE += (freezegun.api.FakeDate,)
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, DATETIME):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder, self).default(obj)
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
if isinstance(o, Decimal):
return str(o)
if isinstance(o, DATETIME):
if o.tzinfo:
return o.strftime('%Y-%m-%dT%H:%M:%S%z')
return o.strftime("%Y-%m-%dT%H:%M:%S")
if isinstance(o, DATE):
return o.strftime("%Y-%m-%d")
if isinstance(o, TIME):
if o.tzinfo:
return o.strftime('%H:%M:%S%z')
return o.strftime("%H:%M:%S")
raise TypeError(repr(o) + " is not JSON serializable")
|
<commit_before>import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder, self).default(obj)
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
if isinstance(o, Decimal):
return str(o)
if isinstance(o, datetime.datetime):
if o.tzinfo:
return o.strftime('%Y-%m-%dT%H:%M:%S%z')
return o.strftime("%Y-%m-%dT%H:%M:%S")
if isinstance(o, datetime.date):
return o.strftime("%Y-%m-%d")
if isinstance(o, datetime.time):
if o.tzinfo:
return o.strftime('%H:%M:%S%z')
return o.strftime("%H:%M:%S")
raise TypeError(repr(o) + " is not JSON serializable")
<commit_msg>Make compatible with freezegun when testing.<commit_after>import datetime
from decimal import Decimal
from django.core.serializers.json import DjangoJSONEncoder
DATETIME = (datetime.datetime,)
DATE = (datetime.date,)
TIME = (datetime.time,)
try:
import freezegun.api
except ImportError:
pass
else:
DATETIME += (freezegun.api.FakeDatetime,)
DATE += (freezegun.api.FakeDate,)
class TZAwareJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, DATETIME):
return obj.strftime("%Y-%m-%d %H:%M:%S%z")
return super(TZAwareJSONEncoder, self).default(obj)
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
if isinstance(o, Decimal):
return str(o)
if isinstance(o, DATETIME):
if o.tzinfo:
return o.strftime('%Y-%m-%dT%H:%M:%S%z')
return o.strftime("%Y-%m-%dT%H:%M:%S")
if isinstance(o, DATE):
return o.strftime("%Y-%m-%d")
if isinstance(o, TIME):
if o.tzinfo:
return o.strftime('%H:%M:%S%z')
return o.strftime("%H:%M:%S")
raise TypeError(repr(o) + " is not JSON serializable")
|
c2cfb617d9bedf93e2c6dfb5ff6cdfcd35d5c0fe
|
db/shot_attempt.py
|
db/shot_attempt.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from db.common import Base
from db.specific_event import SpecificEvent
class ShotAttempt(Base, SpecificEvent):
__tablename__ = 'shot_attempts'
__autoload__ = True
STANDARD_ATTRS = [
"game_id", "team_id", "event_id", "player_id", "shot_attempt_type",
"plus_minus", "num_situation", "plr_situation", "actual", "score_diff"
]
def __init__(self, game_id, team_id, event_id, player_id, data_dict):
self.shot_attempt_id = uuid.uuid4().urn
self.game_id = game_id
self.team_id = team_id
self.event_id = event_id
self.player_id = player_id
for attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
if attr in ['actual']:
setattr(self, attr, False)
else:
setattr(self, attr, None)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from sqlalchemy import and_
from db.common import Base, session_scope
from db.specific_event import SpecificEvent
class ShotAttempt(Base, SpecificEvent):
__tablename__ = 'shot_attempts'
__autoload__ = True
STANDARD_ATTRS = [
"game_id", "team_id", "event_id", "player_id", "shot_attempt_type",
"plus_minus", "num_situation", "plr_situation", "actual", "score_diff"
]
def __init__(self, game_id, team_id, event_id, player_id, data_dict):
self.shot_attempt_id = uuid.uuid4().urn
self.game_id = game_id
self.team_id = team_id
self.event_id = event_id
self.player_id = player_id
for attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
if attr in ['actual']:
setattr(self, attr, False)
else:
setattr(self, attr, None)
@classmethod
def find_by_event_player_id(self, event_id, player_id):
with session_scope() as session:
try:
shot_attempt = session.query(ShotAttempt).filter(
and_(
ShotAttempt.event_id == event_id,
ShotAttempt.player_id == player_id
)
).one()
except:
shot_attempt = None
return shot_attempt
|
Add method to find by event and player id
|
Add method to find by event and player id
|
Python
|
mit
|
leaffan/pynhldb
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from db.common import Base
from db.specific_event import SpecificEvent
class ShotAttempt(Base, SpecificEvent):
__tablename__ = 'shot_attempts'
__autoload__ = True
STANDARD_ATTRS = [
"game_id", "team_id", "event_id", "player_id", "shot_attempt_type",
"plus_minus", "num_situation", "plr_situation", "actual", "score_diff"
]
def __init__(self, game_id, team_id, event_id, player_id, data_dict):
self.shot_attempt_id = uuid.uuid4().urn
self.game_id = game_id
self.team_id = team_id
self.event_id = event_id
self.player_id = player_id
for attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
if attr in ['actual']:
setattr(self, attr, False)
else:
setattr(self, attr, None)
Add method to find by event and player id
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from sqlalchemy import and_
from db.common import Base, session_scope
from db.specific_event import SpecificEvent
class ShotAttempt(Base, SpecificEvent):
__tablename__ = 'shot_attempts'
__autoload__ = True
STANDARD_ATTRS = [
"game_id", "team_id", "event_id", "player_id", "shot_attempt_type",
"plus_minus", "num_situation", "plr_situation", "actual", "score_diff"
]
def __init__(self, game_id, team_id, event_id, player_id, data_dict):
self.shot_attempt_id = uuid.uuid4().urn
self.game_id = game_id
self.team_id = team_id
self.event_id = event_id
self.player_id = player_id
for attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
if attr in ['actual']:
setattr(self, attr, False)
else:
setattr(self, attr, None)
@classmethod
def find_by_event_player_id(self, event_id, player_id):
with session_scope() as session:
try:
shot_attempt = session.query(ShotAttempt).filter(
and_(
ShotAttempt.event_id == event_id,
ShotAttempt.player_id == player_id
)
).one()
except:
shot_attempt = None
return shot_attempt
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from db.common import Base
from db.specific_event import SpecificEvent
class ShotAttempt(Base, SpecificEvent):
__tablename__ = 'shot_attempts'
__autoload__ = True
STANDARD_ATTRS = [
"game_id", "team_id", "event_id", "player_id", "shot_attempt_type",
"plus_minus", "num_situation", "plr_situation", "actual", "score_diff"
]
def __init__(self, game_id, team_id, event_id, player_id, data_dict):
self.shot_attempt_id = uuid.uuid4().urn
self.game_id = game_id
self.team_id = team_id
self.event_id = event_id
self.player_id = player_id
for attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
if attr in ['actual']:
setattr(self, attr, False)
else:
setattr(self, attr, None)
<commit_msg>Add method to find by event and player id<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from sqlalchemy import and_
from db.common import Base, session_scope
from db.specific_event import SpecificEvent
class ShotAttempt(Base, SpecificEvent):
__tablename__ = 'shot_attempts'
__autoload__ = True
STANDARD_ATTRS = [
"game_id", "team_id", "event_id", "player_id", "shot_attempt_type",
"plus_minus", "num_situation", "plr_situation", "actual", "score_diff"
]
def __init__(self, game_id, team_id, event_id, player_id, data_dict):
self.shot_attempt_id = uuid.uuid4().urn
self.game_id = game_id
self.team_id = team_id
self.event_id = event_id
self.player_id = player_id
for attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
if attr in ['actual']:
setattr(self, attr, False)
else:
setattr(self, attr, None)
@classmethod
def find_by_event_player_id(self, event_id, player_id):
with session_scope() as session:
try:
shot_attempt = session.query(ShotAttempt).filter(
and_(
ShotAttempt.event_id == event_id,
ShotAttempt.player_id == player_id
)
).one()
except:
shot_attempt = None
return shot_attempt
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from db.common import Base
from db.specific_event import SpecificEvent
class ShotAttempt(Base, SpecificEvent):
__tablename__ = 'shot_attempts'
__autoload__ = True
STANDARD_ATTRS = [
"game_id", "team_id", "event_id", "player_id", "shot_attempt_type",
"plus_minus", "num_situation", "plr_situation", "actual", "score_diff"
]
def __init__(self, game_id, team_id, event_id, player_id, data_dict):
self.shot_attempt_id = uuid.uuid4().urn
self.game_id = game_id
self.team_id = team_id
self.event_id = event_id
self.player_id = player_id
for attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
if attr in ['actual']:
setattr(self, attr, False)
else:
setattr(self, attr, None)
Add method to find by event and player id#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from sqlalchemy import and_
from db.common import Base, session_scope
from db.specific_event import SpecificEvent
class ShotAttempt(Base, SpecificEvent):
__tablename__ = 'shot_attempts'
__autoload__ = True
STANDARD_ATTRS = [
"game_id", "team_id", "event_id", "player_id", "shot_attempt_type",
"plus_minus", "num_situation", "plr_situation", "actual", "score_diff"
]
def __init__(self, game_id, team_id, event_id, player_id, data_dict):
self.shot_attempt_id = uuid.uuid4().urn
self.game_id = game_id
self.team_id = team_id
self.event_id = event_id
self.player_id = player_id
for attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
if attr in ['actual']:
setattr(self, attr, False)
else:
setattr(self, attr, None)
@classmethod
def find_by_event_player_id(self, event_id, player_id):
with session_scope() as session:
try:
shot_attempt = session.query(ShotAttempt).filter(
and_(
ShotAttempt.event_id == event_id,
ShotAttempt.player_id == player_id
)
).one()
except:
shot_attempt = None
return shot_attempt
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from db.common import Base
from db.specific_event import SpecificEvent
class ShotAttempt(Base, SpecificEvent):
__tablename__ = 'shot_attempts'
__autoload__ = True
STANDARD_ATTRS = [
"game_id", "team_id", "event_id", "player_id", "shot_attempt_type",
"plus_minus", "num_situation", "plr_situation", "actual", "score_diff"
]
def __init__(self, game_id, team_id, event_id, player_id, data_dict):
self.shot_attempt_id = uuid.uuid4().urn
self.game_id = game_id
self.team_id = team_id
self.event_id = event_id
self.player_id = player_id
for attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
if attr in ['actual']:
setattr(self, attr, False)
else:
setattr(self, attr, None)
<commit_msg>Add method to find by event and player id<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from sqlalchemy import and_
from db.common import Base, session_scope
from db.specific_event import SpecificEvent
class ShotAttempt(Base, SpecificEvent):
__tablename__ = 'shot_attempts'
__autoload__ = True
STANDARD_ATTRS = [
"game_id", "team_id", "event_id", "player_id", "shot_attempt_type",
"plus_minus", "num_situation", "plr_situation", "actual", "score_diff"
]
def __init__(self, game_id, team_id, event_id, player_id, data_dict):
self.shot_attempt_id = uuid.uuid4().urn
self.game_id = game_id
self.team_id = team_id
self.event_id = event_id
self.player_id = player_id
for attr in data_dict:
setattr(self, attr, data_dict[attr])
else:
if attr in ['actual']:
setattr(self, attr, False)
else:
setattr(self, attr, None)
@classmethod
def find_by_event_player_id(self, event_id, player_id):
with session_scope() as session:
try:
shot_attempt = session.query(ShotAttempt).filter(
and_(
ShotAttempt.event_id == event_id,
ShotAttempt.player_id == player_id
)
).one()
except:
shot_attempt = None
return shot_attempt
|
779620e53bd9c71e1c9e078ff46498d363dd392e
|
wagtail/admin/staticfiles.py
|
wagtail/admin/staticfiles.py
|
import hashlib
from django.conf import settings
from django.templatetags.static import static
from wagtail import __version__
if getattr(settings, 'WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS', True):
VERSION_HASH = hashlib.sha1(
(__version__ + settings.SECRET_KEY).encode('utf-8')
).hexdigest()[:8]
else:
VERSION_HASH = None
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
base_url = static(path)
# if URL already contains a querystring, don't add our own, to avoid interfering
# with existing mechanisms
if VERSION_HASH is None or '?' in base_url:
return base_url
else:
return base_url + '?v=' + VERSION_HASH
|
import hashlib
from django.conf import settings
from django.contrib.staticfiles.storage import HashedFilesMixin
from django.core.files.storage import get_storage_class
from django.templatetags.static import static
from wagtail import __version__
# Check whether we should add cache-busting '?v=...' parameters to static file URLs
try:
# If a preference has been explicitly stated in the WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS
# setting, use that
use_version_strings = settings.WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS
except AttributeError:
# If WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS not specified, default to version strings
# enabled, UNLESS we're using a storage backend with hashed filenames; in this case having
# a query parameter is redundant, and in some configurations (e.g. Cloudflare with the
# "No Query String" setting) it could break a previously-working cache setup
if settings.DEBUG:
# Hashed filenames are disabled in debug mode, so keep the querystring
use_version_strings = True
else:
# see if we're using a storage backend using hashed filenames
storage = get_storage_class(settings.STATICFILES_STORAGE)
use_version_strings = not issubclass(storage, HashedFilesMixin)
if use_version_strings:
VERSION_HASH = hashlib.sha1(
(__version__ + settings.SECRET_KEY).encode('utf-8')
).hexdigest()[:8]
else:
VERSION_HASH = None
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
base_url = static(path)
# if URL already contains a querystring, don't add our own, to avoid interfering
# with existing mechanisms
if VERSION_HASH is None or '?' in base_url:
return base_url
else:
return base_url + '?v=' + VERSION_HASH
|
Disable querystrings if a storage backend with hashed filenames is active
|
Disable querystrings if a storage backend with hashed filenames is active
|
Python
|
bsd-3-clause
|
rsalmaso/wagtail,gasman/wagtail,kaedroho/wagtail,rsalmaso/wagtail,torchbox/wagtail,mixxorz/wagtail,timorieber/wagtail,nimasmi/wagtail,rsalmaso/wagtail,jnns/wagtail,torchbox/wagtail,wagtail/wagtail,zerolab/wagtail,mixxorz/wagtail,torchbox/wagtail,kaedroho/wagtail,gasman/wagtail,takeflight/wagtail,zerolab/wagtail,wagtail/wagtail,nimasmi/wagtail,gasman/wagtail,FlipperPA/wagtail,kaedroho/wagtail,timorieber/wagtail,wagtail/wagtail,FlipperPA/wagtail,kaedroho/wagtail,takeflight/wagtail,wagtail/wagtail,takeflight/wagtail,zerolab/wagtail,rsalmaso/wagtail,jnns/wagtail,mixxorz/wagtail,kaedroho/wagtail,jnns/wagtail,rsalmaso/wagtail,nimasmi/wagtail,FlipperPA/wagtail,thenewguy/wagtail,timorieber/wagtail,gasman/wagtail,timorieber/wagtail,torchbox/wagtail,mixxorz/wagtail,takeflight/wagtail,wagtail/wagtail,thenewguy/wagtail,jnns/wagtail,thenewguy/wagtail,zerolab/wagtail,mixxorz/wagtail,gasman/wagtail,FlipperPA/wagtail,thenewguy/wagtail,nimasmi/wagtail,zerolab/wagtail,thenewguy/wagtail
|
import hashlib
from django.conf import settings
from django.templatetags.static import static
from wagtail import __version__
if getattr(settings, 'WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS', True):
VERSION_HASH = hashlib.sha1(
(__version__ + settings.SECRET_KEY).encode('utf-8')
).hexdigest()[:8]
else:
VERSION_HASH = None
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
base_url = static(path)
# if URL already contains a querystring, don't add our own, to avoid interfering
# with existing mechanisms
if VERSION_HASH is None or '?' in base_url:
return base_url
else:
return base_url + '?v=' + VERSION_HASH
Disable querystrings if a storage backend with hashed filenames is active
|
import hashlib
from django.conf import settings
from django.contrib.staticfiles.storage import HashedFilesMixin
from django.core.files.storage import get_storage_class
from django.templatetags.static import static
from wagtail import __version__
# Check whether we should add cache-busting '?v=...' parameters to static file URLs
try:
# If a preference has been explicitly stated in the WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS
# setting, use that
use_version_strings = settings.WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS
except AttributeError:
# If WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS not specified, default to version strings
# enabled, UNLESS we're using a storage backend with hashed filenames; in this case having
# a query parameter is redundant, and in some configurations (e.g. Cloudflare with the
# "No Query String" setting) it could break a previously-working cache setup
if settings.DEBUG:
# Hashed filenames are disabled in debug mode, so keep the querystring
use_version_strings = True
else:
# see if we're using a storage backend using hashed filenames
storage = get_storage_class(settings.STATICFILES_STORAGE)
use_version_strings = not issubclass(storage, HashedFilesMixin)
if use_version_strings:
VERSION_HASH = hashlib.sha1(
(__version__ + settings.SECRET_KEY).encode('utf-8')
).hexdigest()[:8]
else:
VERSION_HASH = None
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
base_url = static(path)
# if URL already contains a querystring, don't add our own, to avoid interfering
# with existing mechanisms
if VERSION_HASH is None or '?' in base_url:
return base_url
else:
return base_url + '?v=' + VERSION_HASH
|
<commit_before>import hashlib
from django.conf import settings
from django.templatetags.static import static
from wagtail import __version__
if getattr(settings, 'WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS', True):
VERSION_HASH = hashlib.sha1(
(__version__ + settings.SECRET_KEY).encode('utf-8')
).hexdigest()[:8]
else:
VERSION_HASH = None
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
base_url = static(path)
# if URL already contains a querystring, don't add our own, to avoid interfering
# with existing mechanisms
if VERSION_HASH is None or '?' in base_url:
return base_url
else:
return base_url + '?v=' + VERSION_HASH
<commit_msg>Disable querystrings if a storage backend with hashed filenames is active<commit_after>
|
import hashlib
from django.conf import settings
from django.contrib.staticfiles.storage import HashedFilesMixin
from django.core.files.storage import get_storage_class
from django.templatetags.static import static
from wagtail import __version__
# Check whether we should add cache-busting '?v=...' parameters to static file URLs
try:
# If a preference has been explicitly stated in the WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS
# setting, use that
use_version_strings = settings.WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS
except AttributeError:
# If WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS not specified, default to version strings
# enabled, UNLESS we're using a storage backend with hashed filenames; in this case having
# a query parameter is redundant, and in some configurations (e.g. Cloudflare with the
# "No Query String" setting) it could break a previously-working cache setup
if settings.DEBUG:
# Hashed filenames are disabled in debug mode, so keep the querystring
use_version_strings = True
else:
# see if we're using a storage backend using hashed filenames
storage = get_storage_class(settings.STATICFILES_STORAGE)
use_version_strings = not issubclass(storage, HashedFilesMixin)
if use_version_strings:
VERSION_HASH = hashlib.sha1(
(__version__ + settings.SECRET_KEY).encode('utf-8')
).hexdigest()[:8]
else:
VERSION_HASH = None
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
base_url = static(path)
# if URL already contains a querystring, don't add our own, to avoid interfering
# with existing mechanisms
if VERSION_HASH is None or '?' in base_url:
return base_url
else:
return base_url + '?v=' + VERSION_HASH
|
import hashlib
from django.conf import settings
from django.templatetags.static import static
from wagtail import __version__
if getattr(settings, 'WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS', True):
VERSION_HASH = hashlib.sha1(
(__version__ + settings.SECRET_KEY).encode('utf-8')
).hexdigest()[:8]
else:
VERSION_HASH = None
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
base_url = static(path)
# if URL already contains a querystring, don't add our own, to avoid interfering
# with existing mechanisms
if VERSION_HASH is None or '?' in base_url:
return base_url
else:
return base_url + '?v=' + VERSION_HASH
Disable querystrings if a storage backend with hashed filenames is activeimport hashlib
from django.conf import settings
from django.contrib.staticfiles.storage import HashedFilesMixin
from django.core.files.storage import get_storage_class
from django.templatetags.static import static
from wagtail import __version__
# Check whether we should add cache-busting '?v=...' parameters to static file URLs
try:
# If a preference has been explicitly stated in the WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS
# setting, use that
use_version_strings = settings.WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS
except AttributeError:
# If WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS not specified, default to version strings
# enabled, UNLESS we're using a storage backend with hashed filenames; in this case having
# a query parameter is redundant, and in some configurations (e.g. Cloudflare with the
# "No Query String" setting) it could break a previously-working cache setup
if settings.DEBUG:
# Hashed filenames are disabled in debug mode, so keep the querystring
use_version_strings = True
else:
# see if we're using a storage backend using hashed filenames
storage = get_storage_class(settings.STATICFILES_STORAGE)
use_version_strings = not issubclass(storage, HashedFilesMixin)
if use_version_strings:
VERSION_HASH = hashlib.sha1(
(__version__ + settings.SECRET_KEY).encode('utf-8')
).hexdigest()[:8]
else:
VERSION_HASH = None
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
base_url = static(path)
# if URL already contains a querystring, don't add our own, to avoid interfering
# with existing mechanisms
if VERSION_HASH is None or '?' in base_url:
return base_url
else:
return base_url + '?v=' + VERSION_HASH
|
<commit_before>import hashlib
from django.conf import settings
from django.templatetags.static import static
from wagtail import __version__
if getattr(settings, 'WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS', True):
VERSION_HASH = hashlib.sha1(
(__version__ + settings.SECRET_KEY).encode('utf-8')
).hexdigest()[:8]
else:
VERSION_HASH = None
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
base_url = static(path)
# if URL already contains a querystring, don't add our own, to avoid interfering
# with existing mechanisms
if VERSION_HASH is None or '?' in base_url:
return base_url
else:
return base_url + '?v=' + VERSION_HASH
<commit_msg>Disable querystrings if a storage backend with hashed filenames is active<commit_after>import hashlib
from django.conf import settings
from django.contrib.staticfiles.storage import HashedFilesMixin
from django.core.files.storage import get_storage_class
from django.templatetags.static import static
from wagtail import __version__
# Check whether we should add cache-busting '?v=...' parameters to static file URLs
try:
# If a preference has been explicitly stated in the WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS
# setting, use that
use_version_strings = settings.WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS
except AttributeError:
# If WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS not specified, default to version strings
# enabled, UNLESS we're using a storage backend with hashed filenames; in this case having
# a query parameter is redundant, and in some configurations (e.g. Cloudflare with the
# "No Query String" setting) it could break a previously-working cache setup
if settings.DEBUG:
# Hashed filenames are disabled in debug mode, so keep the querystring
use_version_strings = True
else:
# see if we're using a storage backend using hashed filenames
storage = get_storage_class(settings.STATICFILES_STORAGE)
use_version_strings = not issubclass(storage, HashedFilesMixin)
if use_version_strings:
VERSION_HASH = hashlib.sha1(
(__version__ + settings.SECRET_KEY).encode('utf-8')
).hexdigest()[:8]
else:
VERSION_HASH = None
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
base_url = static(path)
# if URL already contains a querystring, don't add our own, to avoid interfering
# with existing mechanisms
if VERSION_HASH is None or '?' in base_url:
return base_url
else:
return base_url + '?v=' + VERSION_HASH
|
bf6a4ea469c21e45a8c382ff935e57debfb142f9
|
pyowm/constants.py
|
pyowm/constants.py
|
"""
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.2.0'
LATEST_OWM_API_VERSION = '2.5'
|
"""
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.2.1'
LATEST_OWM_API_VERSION = '2.5'
|
Fix version prior to release
|
Fix version prior to release
|
Python
|
mit
|
LukasBoersma/pyowm,LukasBoersma/pyowm,csparpa/pyowm,csparpa/pyowm,LukasBoersma/pyowm
|
"""
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.2.0'
LATEST_OWM_API_VERSION = '2.5'
Fix version prior to release
|
"""
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.2.1'
LATEST_OWM_API_VERSION = '2.5'
|
<commit_before>"""
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.2.0'
LATEST_OWM_API_VERSION = '2.5'
<commit_msg>Fix version prior to release<commit_after>
|
"""
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.2.1'
LATEST_OWM_API_VERSION = '2.5'
|
"""
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.2.0'
LATEST_OWM_API_VERSION = '2.5'
Fix version prior to release"""
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.2.1'
LATEST_OWM_API_VERSION = '2.5'
|
<commit_before>"""
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.2.0'
LATEST_OWM_API_VERSION = '2.5'
<commit_msg>Fix version prior to release<commit_after>"""
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.2.1'
LATEST_OWM_API_VERSION = '2.5'
|
4d163ab5a2c4c9c6b07d4c0dfea1b91ab5e05fec
|
web-scraper/course_finder.py
|
web-scraper/course_finder.py
|
import requests
import http.cookiejar
import time
def get_raw_data():
url = 'http://coursefinder.utoronto.ca/course-search/search/courseSearch/course/search'
data = {
'queryText': '',
'requirements': '',
'campusParam': 'St. George,Scarborough,Mississauga'
}
cookies = http.cookiejar.CookieJar()
s = requests.Session()
json = ''
good = False
while not good:
r = s.get(url, params=data, cookies=cookies)
if r.status_code == 200:
good = True
json = r.text
else:
time.sleep(0.5)
f = open('raw_data.json', 'wb')
f.write(json.encode('utf-8'))
f.close()
|
Create method that retrieves coursefinder URLS
|
Create method that retrieves coursefinder URLS
|
Python
|
mit
|
cobalt-io/cobalt,cobalt-uoft/cobalt,qasim/cobalt,ivanzhangio/cobalt,cobalt-io/cobalt,kshvmdn/cobalt
|
Create method that retrieves coursefinder URLS
|
import requests
import http.cookiejar
import time
def get_raw_data():
url = 'http://coursefinder.utoronto.ca/course-search/search/courseSearch/course/search'
data = {
'queryText': '',
'requirements': '',
'campusParam': 'St. George,Scarborough,Mississauga'
}
cookies = http.cookiejar.CookieJar()
s = requests.Session()
json = ''
good = False
while not good:
r = s.get(url, params=data, cookies=cookies)
if r.status_code == 200:
good = True
json = r.text
else:
time.sleep(0.5)
f = open('raw_data.json', 'wb')
f.write(json.encode('utf-8'))
f.close()
|
<commit_before><commit_msg>Create method that retrieves coursefinder URLS<commit_after>
|
import requests
import http.cookiejar
import time
def get_raw_data():
url = 'http://coursefinder.utoronto.ca/course-search/search/courseSearch/course/search'
data = {
'queryText': '',
'requirements': '',
'campusParam': 'St. George,Scarborough,Mississauga'
}
cookies = http.cookiejar.CookieJar()
s = requests.Session()
json = ''
good = False
while not good:
r = s.get(url, params=data, cookies=cookies)
if r.status_code == 200:
good = True
json = r.text
else:
time.sleep(0.5)
f = open('raw_data.json', 'wb')
f.write(json.encode('utf-8'))
f.close()
|
Create method that retrieves coursefinder URLSimport requests
import http.cookiejar
import time
def get_raw_data():
url = 'http://coursefinder.utoronto.ca/course-search/search/courseSearch/course/search'
data = {
'queryText': '',
'requirements': '',
'campusParam': 'St. George,Scarborough,Mississauga'
}
cookies = http.cookiejar.CookieJar()
s = requests.Session()
json = ''
good = False
while not good:
r = s.get(url, params=data, cookies=cookies)
if r.status_code == 200:
good = True
json = r.text
else:
time.sleep(0.5)
f = open('raw_data.json', 'wb')
f.write(json.encode('utf-8'))
f.close()
|
<commit_before><commit_msg>Create method that retrieves coursefinder URLS<commit_after>import requests
import http.cookiejar
import time
def get_raw_data():
url = 'http://coursefinder.utoronto.ca/course-search/search/courseSearch/course/search'
data = {
'queryText': '',
'requirements': '',
'campusParam': 'St. George,Scarborough,Mississauga'
}
cookies = http.cookiejar.CookieJar()
s = requests.Session()
json = ''
good = False
while not good:
r = s.get(url, params=data, cookies=cookies)
if r.status_code == 200:
good = True
json = r.text
else:
time.sleep(0.5)
f = open('raw_data.json', 'wb')
f.write(json.encode('utf-8'))
f.close()
|
|
3fe4cb6fbafe69b9e7520466b7e7e2d405cf0ed0
|
bookmarks/forms.py
|
bookmarks/forms.py
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size": 40}))
description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
redirect = forms.BooleanField(label="Redirect", required=False)
tags = TagField(label="Tags", required=False)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
# hack to order fields
self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']
def clean(self):
if 'url' not in self.cleaned_data:
return
if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
raise forms.ValidationError(_("You have already bookmarked this link."))
return self.cleaned_data
def should_redirect(self):
if self.cleaned_data["redirect"]:
return True
else:
return False
def save(self, commit=True):
self.instance.url = self.cleaned_data['url']
return super(BookmarkInstanceForm, self).save(commit)
class Meta:
model = BookmarkInstance
#fields = ('url', 'description', 'note', 'redirect')
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40}))
description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
redirect = forms.BooleanField(label="Redirect", required=False)
tags = TagField(label="Tags", required=False)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
# hack to order fields
self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']
def clean(self):
if 'url' not in self.cleaned_data:
return
if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
raise forms.ValidationError(_("You have already bookmarked this link."))
return self.cleaned_data
def should_redirect(self):
if self.cleaned_data["redirect"]:
return True
else:
return False
def save(self, commit=True):
self.instance.url = self.cleaned_data['url']
return super(BookmarkInstanceForm, self).save(commit)
class Meta:
model = BookmarkInstance
#fields = ('url', 'description', 'note', 'redirect')
|
Make URLField compatible with Django 1.4 and remove verify_exists attribute
|
Make URLField compatible with Django 1.4 and remove verify_exists attribute
|
Python
|
mit
|
incuna/incuna-bookmarks,incuna/incuna-bookmarks
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size": 40}))
description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
redirect = forms.BooleanField(label="Redirect", required=False)
tags = TagField(label="Tags", required=False)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
# hack to order fields
self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']
def clean(self):
if 'url' not in self.cleaned_data:
return
if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
raise forms.ValidationError(_("You have already bookmarked this link."))
return self.cleaned_data
def should_redirect(self):
if self.cleaned_data["redirect"]:
return True
else:
return False
def save(self, commit=True):
self.instance.url = self.cleaned_data['url']
return super(BookmarkInstanceForm, self).save(commit)
class Meta:
model = BookmarkInstance
#fields = ('url', 'description', 'note', 'redirect')
Make URLField compatible with Django 1.4 and remove verify_exists attribute
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40}))
description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
redirect = forms.BooleanField(label="Redirect", required=False)
tags = TagField(label="Tags", required=False)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
# hack to order fields
self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']
def clean(self):
if 'url' not in self.cleaned_data:
return
if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
raise forms.ValidationError(_("You have already bookmarked this link."))
return self.cleaned_data
def should_redirect(self):
if self.cleaned_data["redirect"]:
return True
else:
return False
def save(self, commit=True):
self.instance.url = self.cleaned_data['url']
return super(BookmarkInstanceForm, self).save(commit)
class Meta:
model = BookmarkInstance
#fields = ('url', 'description', 'note', 'redirect')
|
<commit_before>from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size": 40}))
description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
redirect = forms.BooleanField(label="Redirect", required=False)
tags = TagField(label="Tags", required=False)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
# hack to order fields
self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']
def clean(self):
if 'url' not in self.cleaned_data:
return
if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
raise forms.ValidationError(_("You have already bookmarked this link."))
return self.cleaned_data
def should_redirect(self):
if self.cleaned_data["redirect"]:
return True
else:
return False
def save(self, commit=True):
self.instance.url = self.cleaned_data['url']
return super(BookmarkInstanceForm, self).save(commit)
class Meta:
model = BookmarkInstance
#fields = ('url', 'description', 'note', 'redirect')
<commit_msg>Make URLField compatible with Django 1.4 and remove verify_exists attribute<commit_after>
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40}))
description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
redirect = forms.BooleanField(label="Redirect", required=False)
tags = TagField(label="Tags", required=False)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
# hack to order fields
self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']
def clean(self):
if 'url' not in self.cleaned_data:
return
if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
raise forms.ValidationError(_("You have already bookmarked this link."))
return self.cleaned_data
def should_redirect(self):
if self.cleaned_data["redirect"]:
return True
else:
return False
def save(self, commit=True):
self.instance.url = self.cleaned_data['url']
return super(BookmarkInstanceForm, self).save(commit)
class Meta:
model = BookmarkInstance
#fields = ('url', 'description', 'note', 'redirect')
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size": 40}))
description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
redirect = forms.BooleanField(label="Redirect", required=False)
tags = TagField(label="Tags", required=False)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
# hack to order fields
self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']
def clean(self):
if 'url' not in self.cleaned_data:
return
if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
raise forms.ValidationError(_("You have already bookmarked this link."))
return self.cleaned_data
def should_redirect(self):
if self.cleaned_data["redirect"]:
return True
else:
return False
def save(self, commit=True):
self.instance.url = self.cleaned_data['url']
return super(BookmarkInstanceForm, self).save(commit)
class Meta:
model = BookmarkInstance
#fields = ('url', 'description', 'note', 'redirect')
Make URLField compatible with Django 1.4 and remove verify_exists attributefrom django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40}))
description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
redirect = forms.BooleanField(label="Redirect", required=False)
tags = TagField(label="Tags", required=False)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
# hack to order fields
self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']
def clean(self):
if 'url' not in self.cleaned_data:
return
if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
raise forms.ValidationError(_("You have already bookmarked this link."))
return self.cleaned_data
def should_redirect(self):
if self.cleaned_data["redirect"]:
return True
else:
return False
def save(self, commit=True):
self.instance.url = self.cleaned_data['url']
return super(BookmarkInstanceForm, self).save(commit)
class Meta:
model = BookmarkInstance
#fields = ('url', 'description', 'note', 'redirect')
|
<commit_before>from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size": 40}))
description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
redirect = forms.BooleanField(label="Redirect", required=False)
tags = TagField(label="Tags", required=False)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
# hack to order fields
self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']
def clean(self):
if 'url' not in self.cleaned_data:
return
if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
raise forms.ValidationError(_("You have already bookmarked this link."))
return self.cleaned_data
def should_redirect(self):
if self.cleaned_data["redirect"]:
return True
else:
return False
def save(self, commit=True):
self.instance.url = self.cleaned_data['url']
return super(BookmarkInstanceForm, self).save(commit)
class Meta:
model = BookmarkInstance
#fields = ('url', 'description', 'note', 'redirect')
<commit_msg>Make URLField compatible with Django 1.4 and remove verify_exists attribute<commit_after>from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40}))
description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
redirect = forms.BooleanField(label="Redirect", required=False)
tags = TagField(label="Tags", required=False)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
# hack to order fields
self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']
def clean(self):
if 'url' not in self.cleaned_data:
return
if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
raise forms.ValidationError(_("You have already bookmarked this link."))
return self.cleaned_data
def should_redirect(self):
if self.cleaned_data["redirect"]:
return True
else:
return False
def save(self, commit=True):
self.instance.url = self.cleaned_data['url']
return super(BookmarkInstanceForm, self).save(commit)
class Meta:
model = BookmarkInstance
#fields = ('url', 'description', 'note', 'redirect')
|
be9d4292e8357d637ebc7e73e1b2333766db5997
|
braid/postgres.py
|
braid/postgres.py
|
from fabric.api import sudo
from braid import package
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def createUser(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres')
def createDb(name, owner):
sudo('createdb -O {} {}'.format(owner, name), user='postgres')
|
from fabric.api import sudo, quiet
from braid import package
from pipes import quote
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def _runQuery(query):
with quiet():
return sudo('psql --no-align --no-readline --no-password --quiet '
'--tuples-only -c {}'.format(quote(query)),
user='postgres', pty=False, combine_stderr=False)
def _dbExists(name):
res = _runQuery("select count(*) from pg_database "
"where datname = '{}';".format(name))
return res == '1'
def _userExists(name):
res = _runQuery("select count(*) from pg_user "
"where usename = '{}';".format(name))
return res == '1'
def createUser(name):
if not _userExists(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False)
def createDb(name, owner):
if not _dbExists(name):
sudo('createdb -O {} {}'.format(owner, name), user='postgres', pty=False)
|
Make createDb and createUser idempotent.
|
Make createDb and createUser idempotent.
|
Python
|
mit
|
alex/braid,alex/braid
|
from fabric.api import sudo
from braid import package
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def createUser(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres')
def createDb(name, owner):
sudo('createdb -O {} {}'.format(owner, name), user='postgres')
Make createDb and createUser idempotent.
|
from fabric.api import sudo, quiet
from braid import package
from pipes import quote
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def _runQuery(query):
with quiet():
return sudo('psql --no-align --no-readline --no-password --quiet '
'--tuples-only -c {}'.format(quote(query)),
user='postgres', pty=False, combine_stderr=False)
def _dbExists(name):
res = _runQuery("select count(*) from pg_database "
"where datname = '{}';".format(name))
return res == '1'
def _userExists(name):
res = _runQuery("select count(*) from pg_user "
"where usename = '{}';".format(name))
return res == '1'
def createUser(name):
if not _userExists(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False)
def createDb(name, owner):
if not _dbExists(name):
sudo('createdb -O {} {}'.format(owner, name), user='postgres', pty=False)
|
<commit_before>from fabric.api import sudo
from braid import package
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def createUser(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres')
def createDb(name, owner):
sudo('createdb -O {} {}'.format(owner, name), user='postgres')
<commit_msg>Make createDb and createUser idempotent.<commit_after>
|
from fabric.api import sudo, quiet
from braid import package
from pipes import quote
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def _runQuery(query):
with quiet():
return sudo('psql --no-align --no-readline --no-password --quiet '
'--tuples-only -c {}'.format(quote(query)),
user='postgres', pty=False, combine_stderr=False)
def _dbExists(name):
res = _runQuery("select count(*) from pg_database "
"where datname = '{}';".format(name))
return res == '1'
def _userExists(name):
res = _runQuery("select count(*) from pg_user "
"where usename = '{}';".format(name))
return res == '1'
def createUser(name):
if not _userExists(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False)
def createDb(name, owner):
if not _dbExists(name):
sudo('createdb -O {} {}'.format(owner, name), user='postgres', pty=False)
|
from fabric.api import sudo
from braid import package
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def createUser(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres')
def createDb(name, owner):
sudo('createdb -O {} {}'.format(owner, name), user='postgres')
Make createDb and createUser idempotent.from fabric.api import sudo, quiet
from braid import package
from pipes import quote
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def _runQuery(query):
with quiet():
return sudo('psql --no-align --no-readline --no-password --quiet '
'--tuples-only -c {}'.format(quote(query)),
user='postgres', pty=False, combine_stderr=False)
def _dbExists(name):
res = _runQuery("select count(*) from pg_database "
"where datname = '{}';".format(name))
return res == '1'
def _userExists(name):
res = _runQuery("select count(*) from pg_user "
"where usename = '{}';".format(name))
return res == '1'
def createUser(name):
if not _userExists(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False)
def createDb(name, owner):
if not _dbExists(name):
sudo('createdb -O {} {}'.format(owner, name), user='postgres', pty=False)
|
<commit_before>from fabric.api import sudo
from braid import package
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def createUser(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres')
def createDb(name, owner):
sudo('createdb -O {} {}'.format(owner, name), user='postgres')
<commit_msg>Make createDb and createUser idempotent.<commit_after>from fabric.api import sudo, quiet
from braid import package
from pipes import quote
def install():
package.install(['postgresql-9.1', 'postgresql-server-dev-9.1'])
def _runQuery(query):
with quiet():
return sudo('psql --no-align --no-readline --no-password --quiet '
'--tuples-only -c {}'.format(quote(query)),
user='postgres', pty=False, combine_stderr=False)
def _dbExists(name):
res = _runQuery("select count(*) from pg_database "
"where datname = '{}';".format(name))
return res == '1'
def _userExists(name):
res = _runQuery("select count(*) from pg_user "
"where usename = '{}';".format(name))
return res == '1'
def createUser(name):
if not _userExists(name):
sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False)
def createDb(name, owner):
if not _dbExists(name):
sudo('createdb -O {} {}'.format(owner, name), user='postgres', pty=False)
|
b48b41fb9634c7e12b805e8bd3ca4f0abb942c3a
|
django/__init__.py
|
django/__init__.py
|
VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
|
VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
|
Update django.VERSION in trunk per previous discussion
|
Update django.VERSION in trunk per previous discussion
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409103
|
Python
|
bsd-3-clause
|
Belgabor/django,Belgabor/django,Belgabor/django
|
VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
Update django.VERSION in trunk per previous discussion
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409103
|
VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
|
<commit_before>VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
<commit_msg>Update django.VERSION in trunk per previous discussion
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409103<commit_after>
|
VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
|
VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
Update django.VERSION in trunk per previous discussion
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409103VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
|
<commit_before>VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
<commit_msg>Update django.VERSION in trunk per previous discussion
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409103<commit_after>VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
|
a3b31e3ad7358709b27f91a249ac0a622f9661cb
|
server/python_django/file_uploader/__init__.py
|
server/python_django/file_uploader/__init__.py
|
"""
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(request.read(fileSize))
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
|
"""
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
#read the file content, if it is not read when the request is multi part then the client get an error
fileContent = uploaded(fileSize)
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(fileContent)
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
|
Read the file content, if it is not read when the request is multipart then the client get an error
|
Read the file content, if it is not read when the request is multipart then the client get an error
|
Python
|
mit
|
SimonWaldherr/uploader,SimonWaldherr/uploader,FineUploader/fine-uploader,FineUploader/fine-uploader,SimonWaldherr/uploader,SimonWaldherr/uploader,SimonWaldherr/uploader,FineUploader/fine-uploader,SimonWaldherr/uploader,SimonWaldherr/uploader
|
"""
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(request.read(fileSize))
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
Read the file content, if it is not read when the request is multipart then the client get an error
|
"""
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
#read the file content, if it is not read when the request is multi part then the client get an error
fileContent = uploaded(fileSize)
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(fileContent)
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
|
<commit_before>"""
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(request.read(fileSize))
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
<commit_msg>Read the file content, if it is not read when the request is multipart then the client get an error<commit_after>
|
"""
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
#read the file content, if it is not read when the request is multi part then the client get an error
fileContent = uploaded(fileSize)
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(fileContent)
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
|
"""
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(request.read(fileSize))
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
Read the file content, if it is not read when the request is multipart then the client get an error"""
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
#read the file content, if it is not read when the request is multi part then the client get an error
fileContent = uploaded(fileSize)
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(fileContent)
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
|
<commit_before>"""
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(request.read(fileSize))
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
<commit_msg>Read the file content, if it is not read when the request is multipart then the client get an error<commit_after>"""
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
#read the file content, if it is not read when the request is multi part then the client get an error
fileContent = uploaded(fileSize)
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(fileContent)
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
|
073b55113ac91b2f6fcfbebe9550f0740f8149d4
|
jxaas/utils.py
|
jxaas/utils.py
|
import logging
from cliff.command import Command
import jujuxaas.client
def get_jxaas_client(command):
tenant = 'abcdef'
username = '123'
password= '123'
client = jujuxaas.client.Client(url="http://127.0.0.1:8080/xaas", tenant=tenant, username=username, password=password)
return client
|
import logging
import os
from cliff.command import Command
import jujuxaas.client
def get_jxaas_client(command):
tenant = 'abcdef'
username = '123'
password= '123'
url = os.getenv('JXAAS_URL', "http://127.0.0.1:8080/xaas")
client = jujuxaas.client.Client(url=url, tenant=tenant, username=username, password=password)
return client
|
Allow JXAAS_URL to be configured as an env var
|
Allow JXAAS_URL to be configured as an env var
|
Python
|
apache-2.0
|
jxaas/cli
|
import logging
from cliff.command import Command
import jujuxaas.client
def get_jxaas_client(command):
tenant = 'abcdef'
username = '123'
password= '123'
client = jujuxaas.client.Client(url="http://127.0.0.1:8080/xaas", tenant=tenant, username=username, password=password)
return client
Allow JXAAS_URL to be configured as an env var
|
import logging
import os
from cliff.command import Command
import jujuxaas.client
def get_jxaas_client(command):
tenant = 'abcdef'
username = '123'
password= '123'
url = os.getenv('JXAAS_URL', "http://127.0.0.1:8080/xaas")
client = jujuxaas.client.Client(url=url, tenant=tenant, username=username, password=password)
return client
|
<commit_before>import logging
from cliff.command import Command
import jujuxaas.client
def get_jxaas_client(command):
tenant = 'abcdef'
username = '123'
password= '123'
client = jujuxaas.client.Client(url="http://127.0.0.1:8080/xaas", tenant=tenant, username=username, password=password)
return client
<commit_msg>Allow JXAAS_URL to be configured as an env var<commit_after>
|
import logging
import os
from cliff.command import Command
import jujuxaas.client
def get_jxaas_client(command):
tenant = 'abcdef'
username = '123'
password= '123'
url = os.getenv('JXAAS_URL', "http://127.0.0.1:8080/xaas")
client = jujuxaas.client.Client(url=url, tenant=tenant, username=username, password=password)
return client
|
import logging
from cliff.command import Command
import jujuxaas.client
def get_jxaas_client(command):
tenant = 'abcdef'
username = '123'
password= '123'
client = jujuxaas.client.Client(url="http://127.0.0.1:8080/xaas", tenant=tenant, username=username, password=password)
return client
Allow JXAAS_URL to be configured as an env varimport logging
import os
from cliff.command import Command
import jujuxaas.client
def get_jxaas_client(command):
tenant = 'abcdef'
username = '123'
password= '123'
url = os.getenv('JXAAS_URL', "http://127.0.0.1:8080/xaas")
client = jujuxaas.client.Client(url=url, tenant=tenant, username=username, password=password)
return client
|
<commit_before>import logging
from cliff.command import Command
import jujuxaas.client
def get_jxaas_client(command):
tenant = 'abcdef'
username = '123'
password= '123'
client = jujuxaas.client.Client(url="http://127.0.0.1:8080/xaas", tenant=tenant, username=username, password=password)
return client
<commit_msg>Allow JXAAS_URL to be configured as an env var<commit_after>import logging
import os
from cliff.command import Command
import jujuxaas.client
def get_jxaas_client(command):
tenant = 'abcdef'
username = '123'
password= '123'
url = os.getenv('JXAAS_URL', "http://127.0.0.1:8080/xaas")
client = jujuxaas.client.Client(url=url, tenant=tenant, username=username, password=password)
return client
|
c27d799ad81f1a11799c217eae9872880246a24e
|
selenium_screenshot.py
|
selenium_screenshot.py
|
from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Chrome"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
|
from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Firefox"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
|
Revert default webdriver to Firefox
|
Revert default webdriver to Firefox
Chrome doesn't yet work, anyway... :-(
|
Python
|
mit
|
ei-grad/docker-selenium-screenshot,ei-grad/docker-selenium-screenshot
|
from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Chrome"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
Revert default webdriver to Firefox
Chrome doesn't yet work, anyway... :-(
|
from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Firefox"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
|
<commit_before>from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Chrome"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
<commit_msg>Revert default webdriver to Firefox
Chrome doesn't yet work, anyway... :-(<commit_after>
|
from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Firefox"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
|
from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Chrome"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
Revert default webdriver to Firefox
Chrome doesn't yet work, anyway... :-(from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Firefox"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
|
<commit_before>from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Chrome"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
<commit_msg>Revert default webdriver to Firefox
Chrome doesn't yet work, anyway... :-(<commit_after>from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Firefox"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
|
507a4f7f931c12c9883ff1644f5d0cc44270d5c2
|
salt/thorium/status.py
|
salt/thorium/status.py
|
# -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data'][key]
__reg__['status']['val'][event['data']['data']['id']] = idata
ret['changes'][event['data']['data']['id']] = True
return ret
|
# -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data']['data'][key]
__reg__['status']['val'][event['data']['id']] = idata
ret['changes'][event['data']['id']] = True
return ret
|
Reorder keys that were being declared in the wrong place
|
Reorder keys that were being declared in the wrong place
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
# -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data'][key]
__reg__['status']['val'][event['data']['data']['id']] = idata
ret['changes'][event['data']['data']['id']] = True
return ret
Reorder keys that were being declared in the wrong place
|
# -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data']['data'][key]
__reg__['status']['val'][event['data']['id']] = idata
ret['changes'][event['data']['id']] = True
return ret
|
<commit_before># -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data'][key]
__reg__['status']['val'][event['data']['data']['id']] = idata
ret['changes'][event['data']['data']['id']] = True
return ret
<commit_msg>Reorder keys that were being declared in the wrong place<commit_after>
|
# -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data']['data'][key]
__reg__['status']['val'][event['data']['id']] = idata
ret['changes'][event['data']['id']] = True
return ret
|
# -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data'][key]
__reg__['status']['val'][event['data']['data']['id']] = idata
ret['changes'][event['data']['data']['id']] = True
return ret
Reorder keys that were being declared in the wrong place# -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data']['data'][key]
__reg__['status']['val'][event['data']['id']] = idata
ret['changes'][event['data']['id']] = True
return ret
|
<commit_before># -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data'][key]
__reg__['status']['val'][event['data']['data']['id']] = idata
ret['changes'][event['data']['data']['id']] = True
return ret
<commit_msg>Reorder keys that were being declared in the wrong place<commit_after># -*- coding: utf-8 -*-
'''
This thorium state is used to track the status beacon events and keep track of
the active status of minions
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import
import time
import fnmatch
def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data']['data'][key]
__reg__['status']['val'][event['data']['id']] = idata
ret['changes'][event['data']['id']] = True
return ret
|
37d160825b458b466421d2946a3549e7b519976c
|
src/siamese_network_bw/siamese_utils.py
|
src/siamese_network_bw/siamese_utils.py
|
import numpy as np
import constants
def mean_normalize(entry):
"""
Mean normalizes a pixel vector. Entry is a numpy array of unrolled pixel vectors with
two side by side facial images for each entry.
"""
entry -= np.mean(entry, axis=0)
return entry
def get_key(idx):
"""
Each image pair is a top level key with a keyname like 00059999, in increasing
order starting from 00000000.
"""
return "%08d" % (idx,)
|
import numpy as np
import constants
def mean_normalize(entry):
"""
Mean normalizes a pixel vector. Entry is a numpy array of unrolled pixel vectors with
two side by side facial images for each entry.
"""
entry -= np.mean(entry, axis=0)
return entry
def get_key(idx):
"""
Each image pair is a top level key with a keyname like 00000059999, in increasing
order starting from 00000000000.
"""
return "%011d" % (idx,)
|
Increase key length for larger datasets.
|
Increase key length for larger datasets.
|
Python
|
apache-2.0
|
BradNeuberg/personal-photos-model
|
import numpy as np
import constants
def mean_normalize(entry):
"""
Mean normalizes a pixel vector. Entry is a numpy array of unrolled pixel vectors with
two side by side facial images for each entry.
"""
entry -= np.mean(entry, axis=0)
return entry
def get_key(idx):
"""
Each image pair is a top level key with a keyname like 00059999, in increasing
order starting from 00000000.
"""
return "%08d" % (idx,)
Increase key length for larger datasets.
|
import numpy as np
import constants
def mean_normalize(entry):
"""
Mean normalizes a pixel vector. Entry is a numpy array of unrolled pixel vectors with
two side by side facial images for each entry.
"""
entry -= np.mean(entry, axis=0)
return entry
def get_key(idx):
"""
Each image pair is a top level key with a keyname like 00000059999, in increasing
order starting from 00000000000.
"""
return "%011d" % (idx,)
|
<commit_before>import numpy as np
import constants
def mean_normalize(entry):
"""
Mean normalizes a pixel vector. Entry is a numpy array of unrolled pixel vectors with
two side by side facial images for each entry.
"""
entry -= np.mean(entry, axis=0)
return entry
def get_key(idx):
"""
Each image pair is a top level key with a keyname like 00059999, in increasing
order starting from 00000000.
"""
return "%08d" % (idx,)
<commit_msg>Increase key length for larger datasets.<commit_after>
|
import numpy as np
import constants
def mean_normalize(entry):
"""
Mean normalizes a pixel vector. Entry is a numpy array of unrolled pixel vectors with
two side by side facial images for each entry.
"""
entry -= np.mean(entry, axis=0)
return entry
def get_key(idx):
"""
Each image pair is a top level key with a keyname like 00000059999, in increasing
order starting from 00000000000.
"""
return "%011d" % (idx,)
|
import numpy as np
import constants
def mean_normalize(entry):
"""
Mean normalizes a pixel vector. Entry is a numpy array of unrolled pixel vectors with
two side by side facial images for each entry.
"""
entry -= np.mean(entry, axis=0)
return entry
def get_key(idx):
"""
Each image pair is a top level key with a keyname like 00059999, in increasing
order starting from 00000000.
"""
return "%08d" % (idx,)
Increase key length for larger datasets.import numpy as np
import constants
def mean_normalize(entry):
"""
Mean normalizes a pixel vector. Entry is a numpy array of unrolled pixel vectors with
two side by side facial images for each entry.
"""
entry -= np.mean(entry, axis=0)
return entry
def get_key(idx):
"""
Each image pair is a top level key with a keyname like 00000059999, in increasing
order starting from 00000000000.
"""
return "%011d" % (idx,)
|
<commit_before>import numpy as np
import constants
def mean_normalize(entry):
"""
Mean normalizes a pixel vector. Entry is a numpy array of unrolled pixel vectors with
two side by side facial images for each entry.
"""
entry -= np.mean(entry, axis=0)
return entry
def get_key(idx):
"""
Each image pair is a top level key with a keyname like 00059999, in increasing
order starting from 00000000.
"""
return "%08d" % (idx,)
<commit_msg>Increase key length for larger datasets.<commit_after>import numpy as np
import constants
def mean_normalize(entry):
"""
Mean normalizes a pixel vector. Entry is a numpy array of unrolled pixel vectors with
two side by side facial images for each entry.
"""
entry -= np.mean(entry, axis=0)
return entry
def get_key(idx):
"""
Each image pair is a top level key with a keyname like 00000059999, in increasing
order starting from 00000000000.
"""
return "%011d" % (idx,)
|
e5a397033c5720cd7d0ab321c05a8f1d12f4dc99
|
tm/tmux_wrapper.py
|
tm/tmux_wrapper.py
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
p = subprocess.Popen("tmux kill-session -t {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
p = subprocess.Popen("tmux ls",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
p = subprocess.Popen("tmux new -s {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
p = subprocess.Popen("tmux attach-session -t {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
create(session)
except SessionExists:
attach(session)
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
out, err = command("kill-session -t {}".format(session))
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
out, err = command("ls")
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
out, err = command("new -s {}".format(session))
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
out, err = command("attach-session -t {}".format(session))
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
Use raw command method to run all commands in wrapper
|
Use raw command method to run all commands in wrapper
|
Python
|
mit
|
ethanal/tm
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
p = subprocess.Popen("tmux kill-session -t {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
p = subprocess.Popen("tmux ls",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
p = subprocess.Popen("tmux new -s {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
p = subprocess.Popen("tmux attach-session -t {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
create(session)
except SessionExists:
attach(session)
Use raw command method to run all commands in wrapper
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
out, err = command("kill-session -t {}".format(session))
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
out, err = command("ls")
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
out, err = command("new -s {}".format(session))
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
out, err = command("attach-session -t {}".format(session))
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
<commit_before># -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
p = subprocess.Popen("tmux kill-session -t {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
p = subprocess.Popen("tmux ls",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
p = subprocess.Popen("tmux new -s {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
p = subprocess.Popen("tmux attach-session -t {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
create(session)
except SessionExists:
attach(session)
<commit_msg>Use raw command method to run all commands in wrapper<commit_after>
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
out, err = command("kill-session -t {}".format(session))
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
out, err = command("ls")
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
out, err = command("new -s {}".format(session))
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
out, err = command("attach-session -t {}".format(session))
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
p = subprocess.Popen("tmux kill-session -t {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
p = subprocess.Popen("tmux ls",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
p = subprocess.Popen("tmux new -s {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
p = subprocess.Popen("tmux attach-session -t {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
create(session)
except SessionExists:
attach(session)
Use raw command method to run all commands in wrapper# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
out, err = command("kill-session -t {}".format(session))
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
out, err = command("ls")
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
out, err = command("new -s {}".format(session))
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
out, err = command("attach-session -t {}".format(session))
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
<commit_before># -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
p = subprocess.Popen("tmux kill-session -t {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
p = subprocess.Popen("tmux ls",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
p = subprocess.Popen("tmux new -s {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
p = subprocess.Popen("tmux attach-session -t {}".format(session),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
out, err = p.communicate()
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
create(session)
except SessionExists:
attach(session)
<commit_msg>Use raw command method to run all commands in wrapper<commit_after># -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
out, err = command("kill-session -t {}".format(session))
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
out, err = command("ls")
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
out, err = command("new -s {}".format(session))
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
out, err = command("attach-session -t {}".format(session))
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
cd22543319e4c21b693f91768adcc1cd42aa08a3
|
calexicon/fn/overflow.py
|
calexicon/fn/overflow.py
|
class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
return None
|
class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
|
Remove this line - it is redundant and missing code coverage.
|
Remove this line - it is redundant and missing code coverage.
|
Python
|
apache-2.0
|
jwg4/qual,jwg4/calexicon
|
class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
return None
Remove this line - it is redundant and missing code coverage.
|
class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
|
<commit_before>class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
return None
<commit_msg>Remove this line - it is redundant and missing code coverage.<commit_after>
|
class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
|
class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
return None
Remove this line - it is redundant and missing code coverage.class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
|
<commit_before>class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
return None
<commit_msg>Remove this line - it is redundant and missing code coverage.<commit_after>class OverflowDate(object):
def __init__(self, **info):
self.info = info
def isocalendar(self):
if 'isocalendar' in self.info:
return self.info['isocalendar']
|
e201f3179388414d0ac6fc9d3a641dda3a5930be
|
snafu/installations.py
|
snafu/installations.py
|
import contextlib
import itertools
import os
import pathlib
import re
import subprocess
import attr
@attr.s
class Installation:
path = attr.ib(convert=pathlib.Path)
@property
def python(self):
return self.path.joinpath('python.exe')
@property
def scripts_dir(self):
return self.path.joinpath('Scripts')
@property
def pip(self):
return self.scripts_dir.joinpath('pip.exe')
def get_version_info(self):
output = subprocess.check_output(
[str(self.python), '--version'], encoding='ascii',
).strip()
match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output)
return match.groups()
def find_script(self, name):
names = itertools.chain([name], (
'{}{}'.format(name, ext)
for ext in os.environ['PATHEXT'].split(';')
))
for name in names:
with contextlib.suppress(FileNotFoundError):
return self.scripts_dir.joinpath(name).resolve()
raise FileNotFoundError(name)
|
import contextlib
import itertools
import os
import pathlib
import re
import subprocess
import attr
@attr.s
class Installation:
path = attr.ib(convert=pathlib.Path)
@property
def python(self):
return self.path.joinpath('python.exe')
@property
def scripts_dir(self):
return self.path.joinpath('Scripts')
@property
def pip(self):
return self.scripts_dir.joinpath('pip.exe')
def get_version_info(self):
output = subprocess.check_output(
[str(self.python), '--version'], encoding='ascii',
).strip()
match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output)
return tuple(int(x) for x in match.groups())
def find_script(self, name):
names = itertools.chain([name], (
'{}{}'.format(name, ext)
for ext in os.environ['PATHEXT'].split(';')
))
for name in names:
with contextlib.suppress(FileNotFoundError):
return self.scripts_dir.joinpath(name).resolve()
raise FileNotFoundError(name)
|
Fix installation version info type
|
Fix installation version info type
|
Python
|
isc
|
uranusjr/snafu,uranusjr/snafu
|
import contextlib
import itertools
import os
import pathlib
import re
import subprocess
import attr
@attr.s
class Installation:
path = attr.ib(convert=pathlib.Path)
@property
def python(self):
return self.path.joinpath('python.exe')
@property
def scripts_dir(self):
return self.path.joinpath('Scripts')
@property
def pip(self):
return self.scripts_dir.joinpath('pip.exe')
def get_version_info(self):
output = subprocess.check_output(
[str(self.python), '--version'], encoding='ascii',
).strip()
match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output)
return match.groups()
def find_script(self, name):
names = itertools.chain([name], (
'{}{}'.format(name, ext)
for ext in os.environ['PATHEXT'].split(';')
))
for name in names:
with contextlib.suppress(FileNotFoundError):
return self.scripts_dir.joinpath(name).resolve()
raise FileNotFoundError(name)
Fix installation version info type
|
import contextlib
import itertools
import os
import pathlib
import re
import subprocess
import attr
@attr.s
class Installation:
path = attr.ib(convert=pathlib.Path)
@property
def python(self):
return self.path.joinpath('python.exe')
@property
def scripts_dir(self):
return self.path.joinpath('Scripts')
@property
def pip(self):
return self.scripts_dir.joinpath('pip.exe')
def get_version_info(self):
output = subprocess.check_output(
[str(self.python), '--version'], encoding='ascii',
).strip()
match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output)
return tuple(int(x) for x in match.groups())
def find_script(self, name):
names = itertools.chain([name], (
'{}{}'.format(name, ext)
for ext in os.environ['PATHEXT'].split(';')
))
for name in names:
with contextlib.suppress(FileNotFoundError):
return self.scripts_dir.joinpath(name).resolve()
raise FileNotFoundError(name)
|
<commit_before>import contextlib
import itertools
import os
import pathlib
import re
import subprocess
import attr
@attr.s
class Installation:
path = attr.ib(convert=pathlib.Path)
@property
def python(self):
return self.path.joinpath('python.exe')
@property
def scripts_dir(self):
return self.path.joinpath('Scripts')
@property
def pip(self):
return self.scripts_dir.joinpath('pip.exe')
def get_version_info(self):
output = subprocess.check_output(
[str(self.python), '--version'], encoding='ascii',
).strip()
match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output)
return match.groups()
def find_script(self, name):
names = itertools.chain([name], (
'{}{}'.format(name, ext)
for ext in os.environ['PATHEXT'].split(';')
))
for name in names:
with contextlib.suppress(FileNotFoundError):
return self.scripts_dir.joinpath(name).resolve()
raise FileNotFoundError(name)
<commit_msg>Fix installation version info type<commit_after>
|
import contextlib
import itertools
import os
import pathlib
import re
import subprocess
import attr
@attr.s
class Installation:
path = attr.ib(convert=pathlib.Path)
@property
def python(self):
return self.path.joinpath('python.exe')
@property
def scripts_dir(self):
return self.path.joinpath('Scripts')
@property
def pip(self):
return self.scripts_dir.joinpath('pip.exe')
def get_version_info(self):
output = subprocess.check_output(
[str(self.python), '--version'], encoding='ascii',
).strip()
match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output)
return tuple(int(x) for x in match.groups())
def find_script(self, name):
names = itertools.chain([name], (
'{}{}'.format(name, ext)
for ext in os.environ['PATHEXT'].split(';')
))
for name in names:
with contextlib.suppress(FileNotFoundError):
return self.scripts_dir.joinpath(name).resolve()
raise FileNotFoundError(name)
|
import contextlib
import itertools
import os
import pathlib
import re
import subprocess
import attr
@attr.s
class Installation:
path = attr.ib(convert=pathlib.Path)
@property
def python(self):
return self.path.joinpath('python.exe')
@property
def scripts_dir(self):
return self.path.joinpath('Scripts')
@property
def pip(self):
return self.scripts_dir.joinpath('pip.exe')
def get_version_info(self):
output = subprocess.check_output(
[str(self.python), '--version'], encoding='ascii',
).strip()
match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output)
return match.groups()
def find_script(self, name):
names = itertools.chain([name], (
'{}{}'.format(name, ext)
for ext in os.environ['PATHEXT'].split(';')
))
for name in names:
with contextlib.suppress(FileNotFoundError):
return self.scripts_dir.joinpath(name).resolve()
raise FileNotFoundError(name)
Fix installation version info typeimport contextlib
import itertools
import os
import pathlib
import re
import subprocess
import attr
@attr.s
class Installation:
path = attr.ib(convert=pathlib.Path)
@property
def python(self):
return self.path.joinpath('python.exe')
@property
def scripts_dir(self):
return self.path.joinpath('Scripts')
@property
def pip(self):
return self.scripts_dir.joinpath('pip.exe')
def get_version_info(self):
output = subprocess.check_output(
[str(self.python), '--version'], encoding='ascii',
).strip()
match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output)
return tuple(int(x) for x in match.groups())
def find_script(self, name):
names = itertools.chain([name], (
'{}{}'.format(name, ext)
for ext in os.environ['PATHEXT'].split(';')
))
for name in names:
with contextlib.suppress(FileNotFoundError):
return self.scripts_dir.joinpath(name).resolve()
raise FileNotFoundError(name)
|
<commit_before>import contextlib
import itertools
import os
import pathlib
import re
import subprocess
import attr
@attr.s
class Installation:
path = attr.ib(convert=pathlib.Path)
@property
def python(self):
return self.path.joinpath('python.exe')
@property
def scripts_dir(self):
return self.path.joinpath('Scripts')
@property
def pip(self):
return self.scripts_dir.joinpath('pip.exe')
def get_version_info(self):
output = subprocess.check_output(
[str(self.python), '--version'], encoding='ascii',
).strip()
match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output)
return match.groups()
def find_script(self, name):
names = itertools.chain([name], (
'{}{}'.format(name, ext)
for ext in os.environ['PATHEXT'].split(';')
))
for name in names:
with contextlib.suppress(FileNotFoundError):
return self.scripts_dir.joinpath(name).resolve()
raise FileNotFoundError(name)
<commit_msg>Fix installation version info type<commit_after>import contextlib
import itertools
import os
import pathlib
import re
import subprocess
import attr
@attr.s
class Installation:
path = attr.ib(convert=pathlib.Path)
@property
def python(self):
return self.path.joinpath('python.exe')
@property
def scripts_dir(self):
return self.path.joinpath('Scripts')
@property
def pip(self):
return self.scripts_dir.joinpath('pip.exe')
def get_version_info(self):
output = subprocess.check_output(
[str(self.python), '--version'], encoding='ascii',
).strip()
match = re.match(r'^Python (\d+)\.(\d+)\.(\d+)$', output)
return tuple(int(x) for x in match.groups())
def find_script(self, name):
names = itertools.chain([name], (
'{}{}'.format(name, ext)
for ext in os.environ['PATHEXT'].split(';')
))
for name in names:
with contextlib.suppress(FileNotFoundError):
return self.scripts_dir.joinpath(name).resolve()
raise FileNotFoundError(name)
|
5702672ab40ef23089c7a2dfee22aaf539b19a54
|
dpaste/settings/tests.py
|
dpaste/settings/tests.py
|
"""
Settings for the test suite
"""
from .base import *
|
"""
Settings for the test suite
"""
from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
|
Use in-memory sqlite db for testing.
|
Use in-memory sqlite db for testing.
|
Python
|
mit
|
bartTC/dpaste,bartTC/dpaste,bartTC/dpaste
|
"""
Settings for the test suite
"""
from .base import *
Use in-memory sqlite db for testing.
|
"""
Settings for the test suite
"""
from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
|
<commit_before>"""
Settings for the test suite
"""
from .base import *
<commit_msg>Use in-memory sqlite db for testing.<commit_after>
|
"""
Settings for the test suite
"""
from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
|
"""
Settings for the test suite
"""
from .base import *
Use in-memory sqlite db for testing."""
Settings for the test suite
"""
from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
|
<commit_before>"""
Settings for the test suite
"""
from .base import *
<commit_msg>Use in-memory sqlite db for testing.<commit_after>"""
Settings for the test suite
"""
from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
|
ab6293bbe039cb0c939493c3b921f114ad68645b
|
tests/test_plugin_execute.py
|
tests/test_plugin_execute.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_onebot_execute
----------------------------------
Tests for Execute plugin
"""
from irc3.testing import BotTestCase
class ExecutePluginTestCase(BotTestCase):
config = {
'includes': [
'onebot.plugins.execute'
],
'onebot.plugins.execute': {
'commands': [
'command1',
'command2'
]
}
}
def setUp(self):
super(ExecutePluginTestCase, self).setUp()
self.callFTU()
self.bot.db = {}
def test_command_allowed(self):
self.bot.notify('connection_made')
self.assertSent(['command1', 'command2'])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_onebot_execute
----------------------------------
Tests for Execute plugin
"""
from irc3.testing import BotTestCase
class ExecutePluginTestCase(BotTestCase):
config = {
'includes': [
'onebot.plugins.execute'
],
'onebot.plugins.execute': {
'commands': [
'command1',
'command2'
]
}
}
def setUp(self):
super(ExecutePluginTestCase, self).setUp()
self.callFTU()
self.bot.db = {}
def test_connection_made(self):
self.bot.dispatch(':irc.server 376 foo!nick@bar :something')
self.assertSent(['command1', 'command2'])
|
Fix test for connection made
|
Fix test for connection made
|
Python
|
bsd-3-clause
|
thomwiggers/onebot
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_onebot_execute
----------------------------------
Tests for Execute plugin
"""
from irc3.testing import BotTestCase
class ExecutePluginTestCase(BotTestCase):
config = {
'includes': [
'onebot.plugins.execute'
],
'onebot.plugins.execute': {
'commands': [
'command1',
'command2'
]
}
}
def setUp(self):
super(ExecutePluginTestCase, self).setUp()
self.callFTU()
self.bot.db = {}
def test_command_allowed(self):
self.bot.notify('connection_made')
self.assertSent(['command1', 'command2'])
Fix test for connection made
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_onebot_execute
----------------------------------
Tests for Execute plugin
"""
from irc3.testing import BotTestCase
class ExecutePluginTestCase(BotTestCase):
config = {
'includes': [
'onebot.plugins.execute'
],
'onebot.plugins.execute': {
'commands': [
'command1',
'command2'
]
}
}
def setUp(self):
super(ExecutePluginTestCase, self).setUp()
self.callFTU()
self.bot.db = {}
def test_connection_made(self):
self.bot.dispatch(':irc.server 376 foo!nick@bar :something')
self.assertSent(['command1', 'command2'])
|
<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_onebot_execute
----------------------------------
Tests for Execute plugin
"""
from irc3.testing import BotTestCase
class ExecutePluginTestCase(BotTestCase):
config = {
'includes': [
'onebot.plugins.execute'
],
'onebot.plugins.execute': {
'commands': [
'command1',
'command2'
]
}
}
def setUp(self):
super(ExecutePluginTestCase, self).setUp()
self.callFTU()
self.bot.db = {}
def test_command_allowed(self):
self.bot.notify('connection_made')
self.assertSent(['command1', 'command2'])
<commit_msg>Fix test for connection made<commit_after>
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_onebot_execute
----------------------------------
Tests for Execute plugin
"""
from irc3.testing import BotTestCase
class ExecutePluginTestCase(BotTestCase):
config = {
'includes': [
'onebot.plugins.execute'
],
'onebot.plugins.execute': {
'commands': [
'command1',
'command2'
]
}
}
def setUp(self):
super(ExecutePluginTestCase, self).setUp()
self.callFTU()
self.bot.db = {}
def test_connection_made(self):
self.bot.dispatch(':irc.server 376 foo!nick@bar :something')
self.assertSent(['command1', 'command2'])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_onebot_execute
----------------------------------
Tests for Execute plugin
"""
from irc3.testing import BotTestCase
class ExecutePluginTestCase(BotTestCase):
config = {
'includes': [
'onebot.plugins.execute'
],
'onebot.plugins.execute': {
'commands': [
'command1',
'command2'
]
}
}
def setUp(self):
super(ExecutePluginTestCase, self).setUp()
self.callFTU()
self.bot.db = {}
def test_command_allowed(self):
self.bot.notify('connection_made')
self.assertSent(['command1', 'command2'])
Fix test for connection made#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_onebot_execute
----------------------------------
Tests for Execute plugin
"""
from irc3.testing import BotTestCase
class ExecutePluginTestCase(BotTestCase):
config = {
'includes': [
'onebot.plugins.execute'
],
'onebot.plugins.execute': {
'commands': [
'command1',
'command2'
]
}
}
def setUp(self):
super(ExecutePluginTestCase, self).setUp()
self.callFTU()
self.bot.db = {}
def test_connection_made(self):
self.bot.dispatch(':irc.server 376 foo!nick@bar :something')
self.assertSent(['command1', 'command2'])
|
<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_onebot_execute
----------------------------------
Tests for Execute plugin
"""
from irc3.testing import BotTestCase
class ExecutePluginTestCase(BotTestCase):
config = {
'includes': [
'onebot.plugins.execute'
],
'onebot.plugins.execute': {
'commands': [
'command1',
'command2'
]
}
}
def setUp(self):
super(ExecutePluginTestCase, self).setUp()
self.callFTU()
self.bot.db = {}
def test_command_allowed(self):
self.bot.notify('connection_made')
self.assertSent(['command1', 'command2'])
<commit_msg>Fix test for connection made<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_onebot_execute
----------------------------------
Tests for Execute plugin
"""
from irc3.testing import BotTestCase
class ExecutePluginTestCase(BotTestCase):
config = {
'includes': [
'onebot.plugins.execute'
],
'onebot.plugins.execute': {
'commands': [
'command1',
'command2'
]
}
}
def setUp(self):
super(ExecutePluginTestCase, self).setUp()
self.callFTU()
self.bot.db = {}
def test_connection_made(self):
self.bot.dispatch(':irc.server 376 foo!nick@bar :something')
self.assertSent(['command1', 'command2'])
|
dbf1298d3adec2f2aab56bbbccec5de98cbaf15c
|
tools/examples/check-modified.py
|
tools/examples/check-modified.py
|
#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, False, adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
|
#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
FORCE_COMPARISON = 0
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, FORCE_COMPARISON,
adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
|
Fix a broken example script.
|
Fix a broken example script.
* check-modified.py (FORCE_COMPARISON): New variable.
(run): Add FORCE_COMPARISON arg to call to svn_wc_text_modified_p.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@850428 13f79535-47bb-0310-9956-ffa450edef68
|
Python
|
apache-2.0
|
wbond/subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,YueLinHo/Subversion,wbond/subversion
|
#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, False, adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
Fix a broken example script.
* check-modified.py (FORCE_COMPARISON): New variable.
(run): Add FORCE_COMPARISON arg to call to svn_wc_text_modified_p.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@850428 13f79535-47bb-0310-9956-ffa450edef68
|
#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
FORCE_COMPARISON = 0
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, FORCE_COMPARISON,
adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
|
<commit_before>#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, False, adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
<commit_msg>Fix a broken example script.
* check-modified.py (FORCE_COMPARISON): New variable.
(run): Add FORCE_COMPARISON arg to call to svn_wc_text_modified_p.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@850428 13f79535-47bb-0310-9956-ffa450edef68<commit_after>
|
#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
FORCE_COMPARISON = 0
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, FORCE_COMPARISON,
adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
|
#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, False, adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
Fix a broken example script.
* check-modified.py (FORCE_COMPARISON): New variable.
(run): Add FORCE_COMPARISON arg to call to svn_wc_text_modified_p.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@850428 13f79535-47bb-0310-9956-ffa450edef68#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
FORCE_COMPARISON = 0
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, FORCE_COMPARISON,
adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
|
<commit_before>#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, False, adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
<commit_msg>Fix a broken example script.
* check-modified.py (FORCE_COMPARISON): New variable.
(run): Add FORCE_COMPARISON arg to call to svn_wc_text_modified_p.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@850428 13f79535-47bb-0310-9956-ffa450edef68<commit_after>#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
FORCE_COMPARISON = 0
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, FORCE_COMPARISON,
adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
|
9df3f3a2d0660b8e8166aa944bf45f261a51d987
|
ies_base/serializers.py
|
ies_base/serializers.py
|
from rest_framework import serializers
class Tag(object):
def __init__(self, name, related_tags, equivalent_names):
self.name = name
self.related_tags = related_tags
self.equivalent_names = equivalent_names
class TagSerializer(serializers.Serializer):
name = serializers.CharField()
related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True)
equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True)
def create(self, validated_data):
return Tag(**validated_data)
class Followable(object):
def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs):
self.name = name
self.type = type
self.game = game
self.object_id = object_id
self.thumbnail_url = thumbnail_url
for field, value in kwargs.items():
setattr(self, field, value)
class FollowableSerializer(serializers.Serializer):
name = serializers.CharField()
type = serializers.IntegerField()
game = serializers.IntegerField()
object_id = serializers.IntegerField()
default_color = serializers.CharField(allow_null=True, allow_blank=True)
thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True)
def create(self, validated_data):
return Followable(**validated_data)
|
from rest_framework import serializers
class Tag(object):
def __init__(self, name, related_tags, equivalent_names):
self.name = name
self.related_tags = related_tags
self.equivalent_names = equivalent_names
class TagSerializer(serializers.Serializer):
name = serializers.CharField()
related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True)
equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True)
def create(self, validated_data):
return Tag(**validated_data)
class Followable(object):
def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs):
self.name = name
self.type = type
self.game = game
self.object_id = object_id
self.thumbnail_url = thumbnail_url
for field, value in kwargs.items():
setattr(self, field, value)
class FollowableSerializer(serializers.Serializer):
name = serializers.CharField()
type = serializers.IntegerField()
game = serializers.IntegerField()
object_id = serializers.IntegerField()
default_color = serializers.CharField(allow_null=True, allow_blank=True, required=False)
thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True)
def create(self, validated_data):
return Followable(**validated_data)
|
Make default color not required
|
Make default color not required
|
Python
|
mit
|
InstanteSports/ies-django-base
|
from rest_framework import serializers
class Tag(object):
def __init__(self, name, related_tags, equivalent_names):
self.name = name
self.related_tags = related_tags
self.equivalent_names = equivalent_names
class TagSerializer(serializers.Serializer):
name = serializers.CharField()
related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True)
equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True)
def create(self, validated_data):
return Tag(**validated_data)
class Followable(object):
def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs):
self.name = name
self.type = type
self.game = game
self.object_id = object_id
self.thumbnail_url = thumbnail_url
for field, value in kwargs.items():
setattr(self, field, value)
class FollowableSerializer(serializers.Serializer):
name = serializers.CharField()
type = serializers.IntegerField()
game = serializers.IntegerField()
object_id = serializers.IntegerField()
default_color = serializers.CharField(allow_null=True, allow_blank=True)
thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True)
def create(self, validated_data):
return Followable(**validated_data)
Make default color not required
|
from rest_framework import serializers
class Tag(object):
def __init__(self, name, related_tags, equivalent_names):
self.name = name
self.related_tags = related_tags
self.equivalent_names = equivalent_names
class TagSerializer(serializers.Serializer):
name = serializers.CharField()
related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True)
equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True)
def create(self, validated_data):
return Tag(**validated_data)
class Followable(object):
def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs):
self.name = name
self.type = type
self.game = game
self.object_id = object_id
self.thumbnail_url = thumbnail_url
for field, value in kwargs.items():
setattr(self, field, value)
class FollowableSerializer(serializers.Serializer):
name = serializers.CharField()
type = serializers.IntegerField()
game = serializers.IntegerField()
object_id = serializers.IntegerField()
default_color = serializers.CharField(allow_null=True, allow_blank=True, required=False)
thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True)
def create(self, validated_data):
return Followable(**validated_data)
|
<commit_before>from rest_framework import serializers
class Tag(object):
def __init__(self, name, related_tags, equivalent_names):
self.name = name
self.related_tags = related_tags
self.equivalent_names = equivalent_names
class TagSerializer(serializers.Serializer):
name = serializers.CharField()
related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True)
equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True)
def create(self, validated_data):
return Tag(**validated_data)
class Followable(object):
def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs):
self.name = name
self.type = type
self.game = game
self.object_id = object_id
self.thumbnail_url = thumbnail_url
for field, value in kwargs.items():
setattr(self, field, value)
class FollowableSerializer(serializers.Serializer):
name = serializers.CharField()
type = serializers.IntegerField()
game = serializers.IntegerField()
object_id = serializers.IntegerField()
default_color = serializers.CharField(allow_null=True, allow_blank=True)
thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True)
def create(self, validated_data):
return Followable(**validated_data)
<commit_msg>Make default color not required<commit_after>
|
from rest_framework import serializers
class Tag(object):
def __init__(self, name, related_tags, equivalent_names):
self.name = name
self.related_tags = related_tags
self.equivalent_names = equivalent_names
class TagSerializer(serializers.Serializer):
name = serializers.CharField()
related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True)
equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True)
def create(self, validated_data):
return Tag(**validated_data)
class Followable(object):
def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs):
self.name = name
self.type = type
self.game = game
self.object_id = object_id
self.thumbnail_url = thumbnail_url
for field, value in kwargs.items():
setattr(self, field, value)
class FollowableSerializer(serializers.Serializer):
name = serializers.CharField()
type = serializers.IntegerField()
game = serializers.IntegerField()
object_id = serializers.IntegerField()
default_color = serializers.CharField(allow_null=True, allow_blank=True, required=False)
thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True)
def create(self, validated_data):
return Followable(**validated_data)
|
from rest_framework import serializers
class Tag(object):
def __init__(self, name, related_tags, equivalent_names):
self.name = name
self.related_tags = related_tags
self.equivalent_names = equivalent_names
class TagSerializer(serializers.Serializer):
name = serializers.CharField()
related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True)
equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True)
def create(self, validated_data):
return Tag(**validated_data)
class Followable(object):
def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs):
self.name = name
self.type = type
self.game = game
self.object_id = object_id
self.thumbnail_url = thumbnail_url
for field, value in kwargs.items():
setattr(self, field, value)
class FollowableSerializer(serializers.Serializer):
name = serializers.CharField()
type = serializers.IntegerField()
game = serializers.IntegerField()
object_id = serializers.IntegerField()
default_color = serializers.CharField(allow_null=True, allow_blank=True)
thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True)
def create(self, validated_data):
return Followable(**validated_data)
Make default color not requiredfrom rest_framework import serializers
class Tag(object):
def __init__(self, name, related_tags, equivalent_names):
self.name = name
self.related_tags = related_tags
self.equivalent_names = equivalent_names
class TagSerializer(serializers.Serializer):
name = serializers.CharField()
related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True)
equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True)
def create(self, validated_data):
return Tag(**validated_data)
class Followable(object):
def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs):
self.name = name
self.type = type
self.game = game
self.object_id = object_id
self.thumbnail_url = thumbnail_url
for field, value in kwargs.items():
setattr(self, field, value)
class FollowableSerializer(serializers.Serializer):
name = serializers.CharField()
type = serializers.IntegerField()
game = serializers.IntegerField()
object_id = serializers.IntegerField()
default_color = serializers.CharField(allow_null=True, allow_blank=True, required=False)
thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True)
def create(self, validated_data):
return Followable(**validated_data)
|
<commit_before>from rest_framework import serializers
class Tag(object):
def __init__(self, name, related_tags, equivalent_names):
self.name = name
self.related_tags = related_tags
self.equivalent_names = equivalent_names
class TagSerializer(serializers.Serializer):
name = serializers.CharField()
related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True)
equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True)
def create(self, validated_data):
return Tag(**validated_data)
class Followable(object):
def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs):
self.name = name
self.type = type
self.game = game
self.object_id = object_id
self.thumbnail_url = thumbnail_url
for field, value in kwargs.items():
setattr(self, field, value)
class FollowableSerializer(serializers.Serializer):
name = serializers.CharField()
type = serializers.IntegerField()
game = serializers.IntegerField()
object_id = serializers.IntegerField()
default_color = serializers.CharField(allow_null=True, allow_blank=True)
thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True)
def create(self, validated_data):
return Followable(**validated_data)
<commit_msg>Make default color not required<commit_after>from rest_framework import serializers
class Tag(object):
def __init__(self, name, related_tags, equivalent_names):
self.name = name
self.related_tags = related_tags
self.equivalent_names = equivalent_names
class TagSerializer(serializers.Serializer):
name = serializers.CharField()
related_tags = serializers.ListField(child=serializers.CharField(), allow_null=True)
equivalent_names = serializers.ListField(child=serializers.CharField(), allow_null=True)
def create(self, validated_data):
return Tag(**validated_data)
class Followable(object):
def __init__(self, name, type, game, object_id, thumbnail_url="", **kwargs):
self.name = name
self.type = type
self.game = game
self.object_id = object_id
self.thumbnail_url = thumbnail_url
for field, value in kwargs.items():
setattr(self, field, value)
class FollowableSerializer(serializers.Serializer):
name = serializers.CharField()
type = serializers.IntegerField()
game = serializers.IntegerField()
object_id = serializers.IntegerField()
default_color = serializers.CharField(allow_null=True, allow_blank=True, required=False)
thumbnail_url = serializers.CharField(allow_blank=True, allow_null=True)
def create(self, validated_data):
return Followable(**validated_data)
|
218265d65695e777cd3e010c6a0108fad6fea5f6
|
beavy/common/including_hyperlink_related.py
|
beavy/common/including_hyperlink_related.py
|
from marshmallow_jsonapi.fields import HyperlinkRelated
from marshmallow_jsonapi.utils import get_value_or_raise
class IncludingHyperlinkRelated(HyperlinkRelated):
def __init__(self, nestedObj, *args, **kwargs):
if callable(nestedObj):
nestedObj = nestedObj(many=False)
self.nestedObj = nestedObj
super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
def add_resource_linkage(self, value):
def render(item):
attributes = self._extract_attributes(item)
type_ = attributes.pop('type', self.type_)
return {'type': type_,
'id': get_value_or_raise(self.id_field, item),
'attributes': attributes}
if self.many:
included_data = [render(each) for each in value]
else:
included_data = render(value)
return included_data
def _extract_attributes(self, value):
sub = self.nestedObj.dump(value).data
try:
return sub["data"]["attributes"]
except (KeyError, TypeError):
# we are a classic type
pass
return sub
|
from marshmallow_jsonapi.fields import HyperlinkRelated
from marshmallow_jsonapi.utils import get_value_or_raise
class IncludingHyperlinkRelated(HyperlinkRelated):
def __init__(self, nestedObj, *args, **kwargs):
if callable(nestedObj):
nestedObj = nestedObj(many=False)
self.nestedObj = nestedObj
kwargs['type_'] = " "
kwargs['include_data'] = True
super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
def add_resource_linkage(self, value):
def render(item):
attributes = self._extract_attributes(item)
type_ = attributes.pop('type', self.type_)
return {'type': type_,
'id': get_value_or_raise(self.id_field, item),
'attributes': attributes}
if self.many:
included_data = [render(each) for each in value]
else:
included_data = render(value)
return included_data
def _extract_attributes(self, value):
sub = self.nestedObj.dump(value).data
try:
return sub["data"]["attributes"]
except (KeyError, TypeError):
# we are a classic type
pass
return sub
|
Enforce that our Including Hyperlink includes
|
Enforce that our Including Hyperlink includes
|
Python
|
mpl-2.0
|
beavyHQ/beavy,beavyHQ/beavy,beavyHQ/beavy,beavyHQ/beavy
|
from marshmallow_jsonapi.fields import HyperlinkRelated
from marshmallow_jsonapi.utils import get_value_or_raise
class IncludingHyperlinkRelated(HyperlinkRelated):
def __init__(self, nestedObj, *args, **kwargs):
if callable(nestedObj):
nestedObj = nestedObj(many=False)
self.nestedObj = nestedObj
super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
def add_resource_linkage(self, value):
def render(item):
attributes = self._extract_attributes(item)
type_ = attributes.pop('type', self.type_)
return {'type': type_,
'id': get_value_or_raise(self.id_field, item),
'attributes': attributes}
if self.many:
included_data = [render(each) for each in value]
else:
included_data = render(value)
return included_data
def _extract_attributes(self, value):
sub = self.nestedObj.dump(value).data
try:
return sub["data"]["attributes"]
except (KeyError, TypeError):
# we are a classic type
pass
return sub
Enforce that our Including Hyperlink includes
|
from marshmallow_jsonapi.fields import HyperlinkRelated
from marshmallow_jsonapi.utils import get_value_or_raise
class IncludingHyperlinkRelated(HyperlinkRelated):
def __init__(self, nestedObj, *args, **kwargs):
if callable(nestedObj):
nestedObj = nestedObj(many=False)
self.nestedObj = nestedObj
kwargs['type_'] = " "
kwargs['include_data'] = True
super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
def add_resource_linkage(self, value):
def render(item):
attributes = self._extract_attributes(item)
type_ = attributes.pop('type', self.type_)
return {'type': type_,
'id': get_value_or_raise(self.id_field, item),
'attributes': attributes}
if self.many:
included_data = [render(each) for each in value]
else:
included_data = render(value)
return included_data
def _extract_attributes(self, value):
sub = self.nestedObj.dump(value).data
try:
return sub["data"]["attributes"]
except (KeyError, TypeError):
# we are a classic type
pass
return sub
|
<commit_before>
from marshmallow_jsonapi.fields import HyperlinkRelated
from marshmallow_jsonapi.utils import get_value_or_raise
class IncludingHyperlinkRelated(HyperlinkRelated):
def __init__(self, nestedObj, *args, **kwargs):
if callable(nestedObj):
nestedObj = nestedObj(many=False)
self.nestedObj = nestedObj
super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
def add_resource_linkage(self, value):
def render(item):
attributes = self._extract_attributes(item)
type_ = attributes.pop('type', self.type_)
return {'type': type_,
'id': get_value_or_raise(self.id_field, item),
'attributes': attributes}
if self.many:
included_data = [render(each) for each in value]
else:
included_data = render(value)
return included_data
def _extract_attributes(self, value):
sub = self.nestedObj.dump(value).data
try:
return sub["data"]["attributes"]
except (KeyError, TypeError):
# we are a classic type
pass
return sub
<commit_msg>Enforce that our Including Hyperlink includes<commit_after>
|
from marshmallow_jsonapi.fields import HyperlinkRelated
from marshmallow_jsonapi.utils import get_value_or_raise
class IncludingHyperlinkRelated(HyperlinkRelated):
def __init__(self, nestedObj, *args, **kwargs):
if callable(nestedObj):
nestedObj = nestedObj(many=False)
self.nestedObj = nestedObj
kwargs['type_'] = " "
kwargs['include_data'] = True
super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
def add_resource_linkage(self, value):
def render(item):
attributes = self._extract_attributes(item)
type_ = attributes.pop('type', self.type_)
return {'type': type_,
'id': get_value_or_raise(self.id_field, item),
'attributes': attributes}
if self.many:
included_data = [render(each) for each in value]
else:
included_data = render(value)
return included_data
def _extract_attributes(self, value):
sub = self.nestedObj.dump(value).data
try:
return sub["data"]["attributes"]
except (KeyError, TypeError):
# we are a classic type
pass
return sub
|
from marshmallow_jsonapi.fields import HyperlinkRelated
from marshmallow_jsonapi.utils import get_value_or_raise
class IncludingHyperlinkRelated(HyperlinkRelated):
def __init__(self, nestedObj, *args, **kwargs):
if callable(nestedObj):
nestedObj = nestedObj(many=False)
self.nestedObj = nestedObj
super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
def add_resource_linkage(self, value):
def render(item):
attributes = self._extract_attributes(item)
type_ = attributes.pop('type', self.type_)
return {'type': type_,
'id': get_value_or_raise(self.id_field, item),
'attributes': attributes}
if self.many:
included_data = [render(each) for each in value]
else:
included_data = render(value)
return included_data
def _extract_attributes(self, value):
sub = self.nestedObj.dump(value).data
try:
return sub["data"]["attributes"]
except (KeyError, TypeError):
# we are a classic type
pass
return sub
Enforce that our Including Hyperlink includes
from marshmallow_jsonapi.fields import HyperlinkRelated
from marshmallow_jsonapi.utils import get_value_or_raise
class IncludingHyperlinkRelated(HyperlinkRelated):
def __init__(self, nestedObj, *args, **kwargs):
if callable(nestedObj):
nestedObj = nestedObj(many=False)
self.nestedObj = nestedObj
kwargs['type_'] = " "
kwargs['include_data'] = True
super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
def add_resource_linkage(self, value):
def render(item):
attributes = self._extract_attributes(item)
type_ = attributes.pop('type', self.type_)
return {'type': type_,
'id': get_value_or_raise(self.id_field, item),
'attributes': attributes}
if self.many:
included_data = [render(each) for each in value]
else:
included_data = render(value)
return included_data
def _extract_attributes(self, value):
sub = self.nestedObj.dump(value).data
try:
return sub["data"]["attributes"]
except (KeyError, TypeError):
# we are a classic type
pass
return sub
|
<commit_before>
from marshmallow_jsonapi.fields import HyperlinkRelated
from marshmallow_jsonapi.utils import get_value_or_raise
class IncludingHyperlinkRelated(HyperlinkRelated):
def __init__(self, nestedObj, *args, **kwargs):
if callable(nestedObj):
nestedObj = nestedObj(many=False)
self.nestedObj = nestedObj
super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
def add_resource_linkage(self, value):
def render(item):
attributes = self._extract_attributes(item)
type_ = attributes.pop('type', self.type_)
return {'type': type_,
'id': get_value_or_raise(self.id_field, item),
'attributes': attributes}
if self.many:
included_data = [render(each) for each in value]
else:
included_data = render(value)
return included_data
def _extract_attributes(self, value):
sub = self.nestedObj.dump(value).data
try:
return sub["data"]["attributes"]
except (KeyError, TypeError):
# we are a classic type
pass
return sub
<commit_msg>Enforce that our Including Hyperlink includes<commit_after>
from marshmallow_jsonapi.fields import HyperlinkRelated
from marshmallow_jsonapi.utils import get_value_or_raise
class IncludingHyperlinkRelated(HyperlinkRelated):
def __init__(self, nestedObj, *args, **kwargs):
if callable(nestedObj):
nestedObj = nestedObj(many=False)
self.nestedObj = nestedObj
kwargs['type_'] = " "
kwargs['include_data'] = True
super(IncludingHyperlinkRelated, self).__init__(*args, **kwargs)
def add_resource_linkage(self, value):
def render(item):
attributes = self._extract_attributes(item)
type_ = attributes.pop('type', self.type_)
return {'type': type_,
'id': get_value_or_raise(self.id_field, item),
'attributes': attributes}
if self.many:
included_data = [render(each) for each in value]
else:
included_data = render(value)
return included_data
def _extract_attributes(self, value):
sub = self.nestedObj.dump(value).data
try:
return sub["data"]["attributes"]
except (KeyError, TypeError):
# we are a classic type
pass
return sub
|
c9f21a389028ed3b831286dc6c3991f48faa6e81
|
app/soc/mapreduce/convert_project_mentors.py
|
app/soc/mapreduce/convert_project_mentors.py
|
#!/usr/bin/python2.5
#
# Copyright 2011 the Melange authors.
#
# 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.
"""Map reduce to merge mentor and co-mentors properties in GSoCProject.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
import logging
from google.appengine.ext import db
from google.appengine.ext.mapreduce import operation
from soc.modules.gsoc.models.profile import GSoCProfile
from soc.modules.gsoc.models.project import GSoCProject
def process(project):
if not project:
yield operation.counters.Increment("missing_project")
mentor = GSoCProject.mentor.get_value_for_datastore(project)
mentors = [mentor]
for am in project.additional_mentors:
if am not in mentors:
mentors.append(am)
project.mentors = mentors
yield operation.db.Put(project)
yield operation.counters.Increment("projects_updated")
|
#!/usr/bin/python2.5
#
# Copyright 2011 the Melange authors.
#
# 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.
"""Map reduce to merge mentor and co-mentors properties in GSoCProject.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
from google.appengine.ext.mapreduce import operation
from soc.modules.gsoc.models.project import GSoCProject
def process(project):
mentor = GSoCProject.mentor.get_value_for_datastore(project)
mentors = [mentor]
for am in project.additional_mentors:
if am not in mentors:
mentors.append(am)
project.mentors = mentors
yield operation.db.Put(project)
yield operation.counters.Increment("projects_updated")
|
Remove the check for existence of project since mapreduce API guarantees that.
|
Remove the check for existence of project since mapreduce API guarantees that.
Also remove unused imports.
|
Python
|
apache-2.0
|
rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son
|
#!/usr/bin/python2.5
#
# Copyright 2011 the Melange authors.
#
# 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.
"""Map reduce to merge mentor and co-mentors properties in GSoCProject.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
import logging
from google.appengine.ext import db
from google.appengine.ext.mapreduce import operation
from soc.modules.gsoc.models.profile import GSoCProfile
from soc.modules.gsoc.models.project import GSoCProject
def process(project):
if not project:
yield operation.counters.Increment("missing_project")
mentor = GSoCProject.mentor.get_value_for_datastore(project)
mentors = [mentor]
for am in project.additional_mentors:
if am not in mentors:
mentors.append(am)
project.mentors = mentors
yield operation.db.Put(project)
yield operation.counters.Increment("projects_updated")
Remove the check for existence of project since mapreduce API guarantees that.
Also remove unused imports.
|
#!/usr/bin/python2.5
#
# Copyright 2011 the Melange authors.
#
# 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.
"""Map reduce to merge mentor and co-mentors properties in GSoCProject.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
from google.appengine.ext.mapreduce import operation
from soc.modules.gsoc.models.project import GSoCProject
def process(project):
mentor = GSoCProject.mentor.get_value_for_datastore(project)
mentors = [mentor]
for am in project.additional_mentors:
if am not in mentors:
mentors.append(am)
project.mentors = mentors
yield operation.db.Put(project)
yield operation.counters.Increment("projects_updated")
|
<commit_before>#!/usr/bin/python2.5
#
# Copyright 2011 the Melange authors.
#
# 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.
"""Map reduce to merge mentor and co-mentors properties in GSoCProject.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
import logging
from google.appengine.ext import db
from google.appengine.ext.mapreduce import operation
from soc.modules.gsoc.models.profile import GSoCProfile
from soc.modules.gsoc.models.project import GSoCProject
def process(project):
if not project:
yield operation.counters.Increment("missing_project")
mentor = GSoCProject.mentor.get_value_for_datastore(project)
mentors = [mentor]
for am in project.additional_mentors:
if am not in mentors:
mentors.append(am)
project.mentors = mentors
yield operation.db.Put(project)
yield operation.counters.Increment("projects_updated")
<commit_msg>Remove the check for existence of project since mapreduce API guarantees that.
Also remove unused imports.<commit_after>
|
#!/usr/bin/python2.5
#
# Copyright 2011 the Melange authors.
#
# 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.
"""Map reduce to merge mentor and co-mentors properties in GSoCProject.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
from google.appengine.ext.mapreduce import operation
from soc.modules.gsoc.models.project import GSoCProject
def process(project):
mentor = GSoCProject.mentor.get_value_for_datastore(project)
mentors = [mentor]
for am in project.additional_mentors:
if am not in mentors:
mentors.append(am)
project.mentors = mentors
yield operation.db.Put(project)
yield operation.counters.Increment("projects_updated")
|
#!/usr/bin/python2.5
#
# Copyright 2011 the Melange authors.
#
# 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.
"""Map reduce to merge mentor and co-mentors properties in GSoCProject.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
import logging
from google.appengine.ext import db
from google.appengine.ext.mapreduce import operation
from soc.modules.gsoc.models.profile import GSoCProfile
from soc.modules.gsoc.models.project import GSoCProject
def process(project):
if not project:
yield operation.counters.Increment("missing_project")
mentor = GSoCProject.mentor.get_value_for_datastore(project)
mentors = [mentor]
for am in project.additional_mentors:
if am not in mentors:
mentors.append(am)
project.mentors = mentors
yield operation.db.Put(project)
yield operation.counters.Increment("projects_updated")
Remove the check for existence of project since mapreduce API guarantees that.
Also remove unused imports.#!/usr/bin/python2.5
#
# Copyright 2011 the Melange authors.
#
# 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.
"""Map reduce to merge mentor and co-mentors properties in GSoCProject.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
from google.appengine.ext.mapreduce import operation
from soc.modules.gsoc.models.project import GSoCProject
def process(project):
mentor = GSoCProject.mentor.get_value_for_datastore(project)
mentors = [mentor]
for am in project.additional_mentors:
if am not in mentors:
mentors.append(am)
project.mentors = mentors
yield operation.db.Put(project)
yield operation.counters.Increment("projects_updated")
|
<commit_before>#!/usr/bin/python2.5
#
# Copyright 2011 the Melange authors.
#
# 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.
"""Map reduce to merge mentor and co-mentors properties in GSoCProject.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
import logging
from google.appengine.ext import db
from google.appengine.ext.mapreduce import operation
from soc.modules.gsoc.models.profile import GSoCProfile
from soc.modules.gsoc.models.project import GSoCProject
def process(project):
if not project:
yield operation.counters.Increment("missing_project")
mentor = GSoCProject.mentor.get_value_for_datastore(project)
mentors = [mentor]
for am in project.additional_mentors:
if am not in mentors:
mentors.append(am)
project.mentors = mentors
yield operation.db.Put(project)
yield operation.counters.Increment("projects_updated")
<commit_msg>Remove the check for existence of project since mapreduce API guarantees that.
Also remove unused imports.<commit_after>#!/usr/bin/python2.5
#
# Copyright 2011 the Melange authors.
#
# 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.
"""Map reduce to merge mentor and co-mentors properties in GSoCProject.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
from google.appengine.ext.mapreduce import operation
from soc.modules.gsoc.models.project import GSoCProject
def process(project):
mentor = GSoCProject.mentor.get_value_for_datastore(project)
mentors = [mentor]
for am in project.additional_mentors:
if am not in mentors:
mentors.append(am)
project.mentors = mentors
yield operation.db.Put(project)
yield operation.counters.Increment("projects_updated")
|
d056d0e140e05953aaf496aa268e65e642ce3b73
|
ninja/files.py
|
ninja/files.py
|
from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]):
field_schema.update(type="string", format="binary")
|
from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]) -> None:
field_schema.update(type="string", format="binary")
|
Add missing return value type hint
|
Add missing return value type hint
|
Python
|
mit
|
vitalik/django-ninja,vitalik/django-ninja,vitalik/django-ninja
|
from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]):
field_schema.update(type="string", format="binary")
Add missing return value type hint
|
from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]) -> None:
field_schema.update(type="string", format="binary")
|
<commit_before>from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]):
field_schema.update(type="string", format="binary")
<commit_msg>Add missing return value type hint<commit_after>
|
from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]) -> None:
field_schema.update(type="string", format="binary")
|
from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]):
field_schema.update(type="string", format="binary")
Add missing return value type hintfrom typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]) -> None:
field_schema.update(type="string", format="binary")
|
<commit_before>from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]):
field_schema.update(type="string", format="binary")
<commit_msg>Add missing return value type hint<commit_after>from typing import Any, Callable, Dict, Iterable, Optional, Type
from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile
from pydantic.fields import ModelField
__all__ = ["UploadedFile"]
class UploadedFile(DjangoUploadedFile):
@classmethod
def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]:
yield cls._validate
@classmethod
def _validate(cls: Type["UploadedFile"], v: Any) -> Any:
if not isinstance(v, DjangoUploadedFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
@classmethod
def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]) -> None:
field_schema.update(type="string", format="binary")
|
71a2cc9a036cee2b541b149e57d162004500bfbb
|
wagtaildraftail/wagtail_hooks.py
|
wagtaildraftail/wagtail_hooks.py
|
from django.utils.html import format_html
from django.contrib.staticfiles.templatetags.staticfiles import static
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_js')
def draftail_editor_js():
return format_html('<script src="{0}"></script>',
static('wagtaildraftail/wagtaildraftail.bundle.js'))
|
from django.utils.html import format_html
from django.contrib.staticfiles.templatetags.staticfiles import static
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_js')
def draftail_editor_js():
return format_html('<script src="{0}"></script>', static('wagtaildraftail/wagtaildraftail.js'))
@hooks.register('insert_editor_css')
def draftail_editor_css():
return format_html('<link rel="stylesheet" href="{0}">', static('wagtaildraftail/wagtaildraftail.css'))
|
Add hook to load CSS
|
Add hook to load CSS
|
Python
|
mit
|
springload/wagtaildraftail,gasman/wagtaildraftail,gasman/wagtaildraftail,springload/wagtaildraftail,springload/wagtaildraftail,springload/wagtaildraftail,gasman/wagtaildraftail,gasman/wagtaildraftail
|
from django.utils.html import format_html
from django.contrib.staticfiles.templatetags.staticfiles import static
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_js')
def draftail_editor_js():
return format_html('<script src="{0}"></script>',
static('wagtaildraftail/wagtaildraftail.bundle.js'))
Add hook to load CSS
|
from django.utils.html import format_html
from django.contrib.staticfiles.templatetags.staticfiles import static
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_js')
def draftail_editor_js():
return format_html('<script src="{0}"></script>', static('wagtaildraftail/wagtaildraftail.js'))
@hooks.register('insert_editor_css')
def draftail_editor_css():
return format_html('<link rel="stylesheet" href="{0}">', static('wagtaildraftail/wagtaildraftail.css'))
|
<commit_before>from django.utils.html import format_html
from django.contrib.staticfiles.templatetags.staticfiles import static
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_js')
def draftail_editor_js():
return format_html('<script src="{0}"></script>',
static('wagtaildraftail/wagtaildraftail.bundle.js'))
<commit_msg>Add hook to load CSS<commit_after>
|
from django.utils.html import format_html
from django.contrib.staticfiles.templatetags.staticfiles import static
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_js')
def draftail_editor_js():
return format_html('<script src="{0}"></script>', static('wagtaildraftail/wagtaildraftail.js'))
@hooks.register('insert_editor_css')
def draftail_editor_css():
return format_html('<link rel="stylesheet" href="{0}">', static('wagtaildraftail/wagtaildraftail.css'))
|
from django.utils.html import format_html
from django.contrib.staticfiles.templatetags.staticfiles import static
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_js')
def draftail_editor_js():
return format_html('<script src="{0}"></script>',
static('wagtaildraftail/wagtaildraftail.bundle.js'))
Add hook to load CSSfrom django.utils.html import format_html
from django.contrib.staticfiles.templatetags.staticfiles import static
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_js')
def draftail_editor_js():
return format_html('<script src="{0}"></script>', static('wagtaildraftail/wagtaildraftail.js'))
@hooks.register('insert_editor_css')
def draftail_editor_css():
return format_html('<link rel="stylesheet" href="{0}">', static('wagtaildraftail/wagtaildraftail.css'))
|
<commit_before>from django.utils.html import format_html
from django.contrib.staticfiles.templatetags.staticfiles import static
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_js')
def draftail_editor_js():
return format_html('<script src="{0}"></script>',
static('wagtaildraftail/wagtaildraftail.bundle.js'))
<commit_msg>Add hook to load CSS<commit_after>from django.utils.html import format_html
from django.contrib.staticfiles.templatetags.staticfiles import static
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_js')
def draftail_editor_js():
return format_html('<script src="{0}"></script>', static('wagtaildraftail/wagtaildraftail.js'))
@hooks.register('insert_editor_css')
def draftail_editor_css():
return format_html('<link rel="stylesheet" href="{0}">', static('wagtaildraftail/wagtaildraftail.css'))
|
494d35234e30d368a9539910ff3ad6d45ed73125
|
containers/containers.py
|
containers/containers.py
|
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(path, var=None, secure=True):
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
|
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(name, var=None, secure=True):
'''Perform simple discovery and save the discovered ACI locally.
:param name: Name of app.
:type name: str.
:param var: Directory to save app to.
:type var: str.
:param secure: Choose to use HTTPS or HTTP.
:type secure: bool.
:returns: str -- the name of the ACI.
'''
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
|
Add better docstring to simple_discovery
|
Add better docstring to simple_discovery
|
Python
|
mit
|
kragniz/containers
|
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(path, var=None, secure=True):
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
Add better docstring to simple_discovery
|
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(name, var=None, secure=True):
'''Perform simple discovery and save the discovered ACI locally.
:param name: Name of app.
:type name: str.
:param var: Directory to save app to.
:type var: str.
:param secure: Choose to use HTTPS or HTTP.
:type secure: bool.
:returns: str -- the name of the ACI.
'''
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
|
<commit_before>try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(path, var=None, secure=True):
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
<commit_msg>Add better docstring to simple_discovery<commit_after>
|
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(name, var=None, secure=True):
'''Perform simple discovery and save the discovered ACI locally.
:param name: Name of app.
:type name: str.
:param var: Directory to save app to.
:type var: str.
:param secure: Choose to use HTTPS or HTTP.
:type secure: bool.
:returns: str -- the name of the ACI.
'''
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
|
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(path, var=None, secure=True):
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
Add better docstring to simple_discoverytry:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(name, var=None, secure=True):
'''Perform simple discovery and save the discovered ACI locally.
:param name: Name of app.
:type name: str.
:param var: Directory to save app to.
:type var: str.
:param secure: Choose to use HTTPS or HTTP.
:type secure: bool.
:returns: str -- the name of the ACI.
'''
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
|
<commit_before>try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(path, var=None, secure=True):
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
<commit_msg>Add better docstring to simple_discovery<commit_after>try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import os
def simple_discovery(name, var=None, secure=True):
'''Perform simple discovery and save the discovered ACI locally.
:param name: Name of app.
:type name: str.
:param var: Directory to save app to.
:type var: str.
:param secure: Choose to use HTTPS or HTTP.
:type secure: bool.
:returns: str -- the name of the ACI.
'''
if secure:
protocol = 'https'
else:
protocol = 'http'
url = '{protocol}://{path}.aci'.format(path=path, protocol=protocol)
parsed = urlparse(url)
_, local_file = os.path.split(parsed.path)
if var is not None:
local_file = os.path.join(var, local_file)
urlretrieve(url, local_file)
return local_file
class AppContainer(object):
def __init__(self, path=None):
self.path = path
|
999d7a337c0bb2b55da85019abba26edbf5f467a
|
ceviche/__init__.py
|
ceviche/__init__.py
|
# used for setup.py
name = "ceviche"
__version__ = '0.0.1'
from .fdtd import fdtd
from .fdfd import fdfd_ez, fdfd_hz, fdfd_ez_nl
from .jacobians import jacobian
from . import viz
|
# used for setup.py
name = "ceviche"
__version__ = '0.0.1'
from .fdtd import fdtd
from .fdfd import fdfd_ez, fdfd_hz, fdfd_ez_nl
from .jacobians import jacobian
from . import viz
from . import modes
from . import utils
|
Add modes and utils submodules
|
Add modes and utils submodules
|
Python
|
mit
|
fancompute/ceviche,fancompute/ceviche
|
# used for setup.py
name = "ceviche"
__version__ = '0.0.1'
from .fdtd import fdtd
from .fdfd import fdfd_ez, fdfd_hz, fdfd_ez_nl
from .jacobians import jacobian
from . import viz
Add modes and utils submodules
|
# used for setup.py
name = "ceviche"
__version__ = '0.0.1'
from .fdtd import fdtd
from .fdfd import fdfd_ez, fdfd_hz, fdfd_ez_nl
from .jacobians import jacobian
from . import viz
from . import modes
from . import utils
|
<commit_before># used for setup.py
name = "ceviche"
__version__ = '0.0.1'
from .fdtd import fdtd
from .fdfd import fdfd_ez, fdfd_hz, fdfd_ez_nl
from .jacobians import jacobian
from . import viz
<commit_msg>Add modes and utils submodules<commit_after>
|
# used for setup.py
name = "ceviche"
__version__ = '0.0.1'
from .fdtd import fdtd
from .fdfd import fdfd_ez, fdfd_hz, fdfd_ez_nl
from .jacobians import jacobian
from . import viz
from . import modes
from . import utils
|
# used for setup.py
name = "ceviche"
__version__ = '0.0.1'
from .fdtd import fdtd
from .fdfd import fdfd_ez, fdfd_hz, fdfd_ez_nl
from .jacobians import jacobian
from . import viz
Add modes and utils submodules# used for setup.py
name = "ceviche"
__version__ = '0.0.1'
from .fdtd import fdtd
from .fdfd import fdfd_ez, fdfd_hz, fdfd_ez_nl
from .jacobians import jacobian
from . import viz
from . import modes
from . import utils
|
<commit_before># used for setup.py
name = "ceviche"
__version__ = '0.0.1'
from .fdtd import fdtd
from .fdfd import fdfd_ez, fdfd_hz, fdfd_ez_nl
from .jacobians import jacobian
from . import viz
<commit_msg>Add modes and utils submodules<commit_after># used for setup.py
name = "ceviche"
__version__ = '0.0.1'
from .fdtd import fdtd
from .fdfd import fdfd_ez, fdfd_hz, fdfd_ez_nl
from .jacobians import jacobian
from . import viz
from . import modes
from . import utils
|
fc1b14989453cfac9ae42116ac4ba5ef3c00f573
|
dashboard/templatetags/datetime_duration.py
|
dashboard/templatetags/datetime_duration.py
|
from django import template
import datetime
register = template.Library()
# Turn a datetime.timedelta into a string
@register.filter(name='timedelta')
def timedelta(value):
if not value:
return "0"
time = value / 1000000
delta = datetime.timedelta(0, time)
return str(delta)
|
from django import template
import datetime
register = template.Library()
# Turn a datetime.timedelta into a string
@register.filter(name='timedelta')
def timedelta(value):
if not value:
return "0"
int(time = value / 1000000)
delta = datetime.timedelta(0, time)
return str(delta)
|
Fix int() error in datetime value
|
Fix int() error in datetime value
|
Python
|
mit
|
ethanperez/t4k-rms,ethanperez/t4k-rms
|
from django import template
import datetime
register = template.Library()
# Turn a datetime.timedelta into a string
@register.filter(name='timedelta')
def timedelta(value):
if not value:
return "0"
time = value / 1000000
delta = datetime.timedelta(0, time)
return str(delta)
Fix int() error in datetime value
|
from django import template
import datetime
register = template.Library()
# Turn a datetime.timedelta into a string
@register.filter(name='timedelta')
def timedelta(value):
if not value:
return "0"
int(time = value / 1000000)
delta = datetime.timedelta(0, time)
return str(delta)
|
<commit_before>from django import template
import datetime
register = template.Library()
# Turn a datetime.timedelta into a string
@register.filter(name='timedelta')
def timedelta(value):
if not value:
return "0"
time = value / 1000000
delta = datetime.timedelta(0, time)
return str(delta)
<commit_msg>Fix int() error in datetime value<commit_after>
|
from django import template
import datetime
register = template.Library()
# Turn a datetime.timedelta into a string
@register.filter(name='timedelta')
def timedelta(value):
if not value:
return "0"
int(time = value / 1000000)
delta = datetime.timedelta(0, time)
return str(delta)
|
from django import template
import datetime
register = template.Library()
# Turn a datetime.timedelta into a string
@register.filter(name='timedelta')
def timedelta(value):
if not value:
return "0"
time = value / 1000000
delta = datetime.timedelta(0, time)
return str(delta)
Fix int() error in datetime valuefrom django import template
import datetime
register = template.Library()
# Turn a datetime.timedelta into a string
@register.filter(name='timedelta')
def timedelta(value):
if not value:
return "0"
int(time = value / 1000000)
delta = datetime.timedelta(0, time)
return str(delta)
|
<commit_before>from django import template
import datetime
register = template.Library()
# Turn a datetime.timedelta into a string
@register.filter(name='timedelta')
def timedelta(value):
if not value:
return "0"
time = value / 1000000
delta = datetime.timedelta(0, time)
return str(delta)
<commit_msg>Fix int() error in datetime value<commit_after>from django import template
import datetime
register = template.Library()
# Turn a datetime.timedelta into a string
@register.filter(name='timedelta')
def timedelta(value):
if not value:
return "0"
int(time = value / 1000000)
delta = datetime.timedelta(0, time)
return str(delta)
|
388c138950412d309b481d93378266c802b8e98c
|
deploy/deploy.py
|
deploy/deploy.py
|
import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'http://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
|
import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'https://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
|
Change prod url to https
|
Change prod url to https
|
Python
|
mit
|
haystack/eyebrowse-chrome-ext,haystack/eyebrowse-chrome-ext,haystack/eyebrowse-chrome-ext,haystack/eyebrowse-chrome-ext
|
import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'http://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
Change prod url to https
|
import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'https://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
|
<commit_before>import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'http://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
<commit_msg>Change prod url to https<commit_after>
|
import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'https://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
|
import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'http://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
Change prod url to httpsimport json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'https://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
|
<commit_before>import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'http://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
<commit_msg>Change prod url to https<commit_after>import json
MAINJS_PATH = 'js/common.js'
MANIFEST_PATH = 'manifest.json'
DEV_URL = 'http://localhost:8000'
PROD_URL = 'https://eyebrowse.csail.mit.edu'
def rewriteBaseUrl():
with open(MAINJS_PATH, 'r+') as f:
text = f.read()
text = text.replace(DEV_URL, PROD_URL)
f.seek(0)
f.write(text)
f.truncate()
def rewriteManifest():
with open(MANIFEST_PATH, 'r+') as f:
data = json.load(f)
version = data['version'].split('.')
version[2] = str(int(version[2]) + 1)
version = '.'.join(version)
data['version'] = version
f.seek(0)
json.dump(data, f, indent=4, sort_keys=True)
f.truncate()
print version
def main():
''''
rewrite main.js to replace the baseUrl and update manifest.json to have a new manifest
'''
rewriteBaseUrl()
rewriteManifest()
if __name__ == '__main__':
main()
|
1ba4d84fb72a343cdf288d905d2029f1d2fbee12
|
wagtail/api/v2/pagination.py
|
wagtail/api/v2/pagination.py
|
from collections import OrderedDict
from django.conf import settings
from rest_framework.pagination import BasePagination
from rest_framework.response import Response
from .utils import BadRequestError
class WagtailPagination(BasePagination):
def paginate_queryset(self, queryset, request, view=None):
limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20)
try:
offset = int(request.GET.get('offset', 0))
assert offset >= 0
except (ValueError, AssertionError):
raise BadRequestError("offset must be a positive integer")
try:
limit_default = 20 if not limit_max else min(20, limit_max)
limit = int(request.GET.get('limit', limit_default))
if limit_max and limit > limit_max:
raise BadRequestError("limit cannot be higher than %d" % limit_max)
assert limit >= 0
except (ValueError, AssertionError):
raise BadRequestError("limit must be a positive integer")
start = offset
stop = offset + limit
self.view = view
self.total_count = queryset.count()
return queryset[start:stop]
def get_paginated_response(self, data):
data = OrderedDict([
('meta', OrderedDict([
('total_count', self.total_count),
])),
('items', data),
])
return Response(data)
|
from collections import OrderedDict
from django.conf import settings
from rest_framework.pagination import BasePagination
from rest_framework.response import Response
from .utils import BadRequestError
class WagtailPagination(BasePagination):
def paginate_queryset(self, queryset, request, view=None):
limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20)
try:
offset = int(request.GET.get('offset', 0))
if offset < 0:
raise ValueError()
except ValueError:
raise BadRequestError("offset must be a positive integer")
try:
limit_default = 20 if not limit_max else min(20, limit_max)
limit = int(request.GET.get('limit', limit_default))
if limit < 0:
raise ValueError()
except ValueError:
raise BadRequestError("limit must be a positive integer")
if limit_max and limit > limit_max:
raise BadRequestError(
"limit cannot be higher than %d" % limit_max)
start = offset
stop = offset + limit
self.view = view
self.total_count = queryset.count()
return queryset[start:stop]
def get_paginated_response(self, data):
data = OrderedDict([
('meta', OrderedDict([
('total_count', self.total_count),
])),
('items', data),
])
return Response(data)
|
Remove assert from WagtailPagination.paginate_queryset method
|
Remove assert from WagtailPagination.paginate_queryset method
|
Python
|
bsd-3-clause
|
mikedingjan/wagtail,rsalmaso/wagtail,rsalmaso/wagtail,jnns/wagtail,mixxorz/wagtail,wagtail/wagtail,mixxorz/wagtail,FlipperPA/wagtail,wagtail/wagtail,gasman/wagtail,zerolab/wagtail,torchbox/wagtail,mikedingjan/wagtail,timorieber/wagtail,zerolab/wagtail,gasman/wagtail,jnns/wagtail,zerolab/wagtail,kaedroho/wagtail,thenewguy/wagtail,FlipperPA/wagtail,nimasmi/wagtail,thenewguy/wagtail,mixxorz/wagtail,torchbox/wagtail,mikedingjan/wagtail,mixxorz/wagtail,rsalmaso/wagtail,kaedroho/wagtail,nealtodd/wagtail,takeflight/wagtail,mixxorz/wagtail,nimasmi/wagtail,torchbox/wagtail,kaedroho/wagtail,jnns/wagtail,mikedingjan/wagtail,timorieber/wagtail,nealtodd/wagtail,wagtail/wagtail,nealtodd/wagtail,thenewguy/wagtail,thenewguy/wagtail,thenewguy/wagtail,FlipperPA/wagtail,takeflight/wagtail,gasman/wagtail,zerolab/wagtail,torchbox/wagtail,takeflight/wagtail,nimasmi/wagtail,FlipperPA/wagtail,wagtail/wagtail,zerolab/wagtail,jnns/wagtail,rsalmaso/wagtail,nimasmi/wagtail,timorieber/wagtail,takeflight/wagtail,gasman/wagtail,kaedroho/wagtail,rsalmaso/wagtail,gasman/wagtail,timorieber/wagtail,wagtail/wagtail,kaedroho/wagtail,nealtodd/wagtail
|
from collections import OrderedDict
from django.conf import settings
from rest_framework.pagination import BasePagination
from rest_framework.response import Response
from .utils import BadRequestError
class WagtailPagination(BasePagination):
def paginate_queryset(self, queryset, request, view=None):
limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20)
try:
offset = int(request.GET.get('offset', 0))
assert offset >= 0
except (ValueError, AssertionError):
raise BadRequestError("offset must be a positive integer")
try:
limit_default = 20 if not limit_max else min(20, limit_max)
limit = int(request.GET.get('limit', limit_default))
if limit_max and limit > limit_max:
raise BadRequestError("limit cannot be higher than %d" % limit_max)
assert limit >= 0
except (ValueError, AssertionError):
raise BadRequestError("limit must be a positive integer")
start = offset
stop = offset + limit
self.view = view
self.total_count = queryset.count()
return queryset[start:stop]
def get_paginated_response(self, data):
data = OrderedDict([
('meta', OrderedDict([
('total_count', self.total_count),
])),
('items', data),
])
return Response(data)
Remove assert from WagtailPagination.paginate_queryset method
|
from collections import OrderedDict
from django.conf import settings
from rest_framework.pagination import BasePagination
from rest_framework.response import Response
from .utils import BadRequestError
class WagtailPagination(BasePagination):
def paginate_queryset(self, queryset, request, view=None):
limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20)
try:
offset = int(request.GET.get('offset', 0))
if offset < 0:
raise ValueError()
except ValueError:
raise BadRequestError("offset must be a positive integer")
try:
limit_default = 20 if not limit_max else min(20, limit_max)
limit = int(request.GET.get('limit', limit_default))
if limit < 0:
raise ValueError()
except ValueError:
raise BadRequestError("limit must be a positive integer")
if limit_max and limit > limit_max:
raise BadRequestError(
"limit cannot be higher than %d" % limit_max)
start = offset
stop = offset + limit
self.view = view
self.total_count = queryset.count()
return queryset[start:stop]
def get_paginated_response(self, data):
data = OrderedDict([
('meta', OrderedDict([
('total_count', self.total_count),
])),
('items', data),
])
return Response(data)
|
<commit_before>from collections import OrderedDict
from django.conf import settings
from rest_framework.pagination import BasePagination
from rest_framework.response import Response
from .utils import BadRequestError
class WagtailPagination(BasePagination):
def paginate_queryset(self, queryset, request, view=None):
limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20)
try:
offset = int(request.GET.get('offset', 0))
assert offset >= 0
except (ValueError, AssertionError):
raise BadRequestError("offset must be a positive integer")
try:
limit_default = 20 if not limit_max else min(20, limit_max)
limit = int(request.GET.get('limit', limit_default))
if limit_max and limit > limit_max:
raise BadRequestError("limit cannot be higher than %d" % limit_max)
assert limit >= 0
except (ValueError, AssertionError):
raise BadRequestError("limit must be a positive integer")
start = offset
stop = offset + limit
self.view = view
self.total_count = queryset.count()
return queryset[start:stop]
def get_paginated_response(self, data):
data = OrderedDict([
('meta', OrderedDict([
('total_count', self.total_count),
])),
('items', data),
])
return Response(data)
<commit_msg>Remove assert from WagtailPagination.paginate_queryset method<commit_after>
|
from collections import OrderedDict
from django.conf import settings
from rest_framework.pagination import BasePagination
from rest_framework.response import Response
from .utils import BadRequestError
class WagtailPagination(BasePagination):
def paginate_queryset(self, queryset, request, view=None):
limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20)
try:
offset = int(request.GET.get('offset', 0))
if offset < 0:
raise ValueError()
except ValueError:
raise BadRequestError("offset must be a positive integer")
try:
limit_default = 20 if not limit_max else min(20, limit_max)
limit = int(request.GET.get('limit', limit_default))
if limit < 0:
raise ValueError()
except ValueError:
raise BadRequestError("limit must be a positive integer")
if limit_max and limit > limit_max:
raise BadRequestError(
"limit cannot be higher than %d" % limit_max)
start = offset
stop = offset + limit
self.view = view
self.total_count = queryset.count()
return queryset[start:stop]
def get_paginated_response(self, data):
data = OrderedDict([
('meta', OrderedDict([
('total_count', self.total_count),
])),
('items', data),
])
return Response(data)
|
from collections import OrderedDict
from django.conf import settings
from rest_framework.pagination import BasePagination
from rest_framework.response import Response
from .utils import BadRequestError
class WagtailPagination(BasePagination):
def paginate_queryset(self, queryset, request, view=None):
limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20)
try:
offset = int(request.GET.get('offset', 0))
assert offset >= 0
except (ValueError, AssertionError):
raise BadRequestError("offset must be a positive integer")
try:
limit_default = 20 if not limit_max else min(20, limit_max)
limit = int(request.GET.get('limit', limit_default))
if limit_max and limit > limit_max:
raise BadRequestError("limit cannot be higher than %d" % limit_max)
assert limit >= 0
except (ValueError, AssertionError):
raise BadRequestError("limit must be a positive integer")
start = offset
stop = offset + limit
self.view = view
self.total_count = queryset.count()
return queryset[start:stop]
def get_paginated_response(self, data):
data = OrderedDict([
('meta', OrderedDict([
('total_count', self.total_count),
])),
('items', data),
])
return Response(data)
Remove assert from WagtailPagination.paginate_queryset methodfrom collections import OrderedDict
from django.conf import settings
from rest_framework.pagination import BasePagination
from rest_framework.response import Response
from .utils import BadRequestError
class WagtailPagination(BasePagination):
def paginate_queryset(self, queryset, request, view=None):
limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20)
try:
offset = int(request.GET.get('offset', 0))
if offset < 0:
raise ValueError()
except ValueError:
raise BadRequestError("offset must be a positive integer")
try:
limit_default = 20 if not limit_max else min(20, limit_max)
limit = int(request.GET.get('limit', limit_default))
if limit < 0:
raise ValueError()
except ValueError:
raise BadRequestError("limit must be a positive integer")
if limit_max and limit > limit_max:
raise BadRequestError(
"limit cannot be higher than %d" % limit_max)
start = offset
stop = offset + limit
self.view = view
self.total_count = queryset.count()
return queryset[start:stop]
def get_paginated_response(self, data):
data = OrderedDict([
('meta', OrderedDict([
('total_count', self.total_count),
])),
('items', data),
])
return Response(data)
|
<commit_before>from collections import OrderedDict
from django.conf import settings
from rest_framework.pagination import BasePagination
from rest_framework.response import Response
from .utils import BadRequestError
class WagtailPagination(BasePagination):
def paginate_queryset(self, queryset, request, view=None):
limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20)
try:
offset = int(request.GET.get('offset', 0))
assert offset >= 0
except (ValueError, AssertionError):
raise BadRequestError("offset must be a positive integer")
try:
limit_default = 20 if not limit_max else min(20, limit_max)
limit = int(request.GET.get('limit', limit_default))
if limit_max and limit > limit_max:
raise BadRequestError("limit cannot be higher than %d" % limit_max)
assert limit >= 0
except (ValueError, AssertionError):
raise BadRequestError("limit must be a positive integer")
start = offset
stop = offset + limit
self.view = view
self.total_count = queryset.count()
return queryset[start:stop]
def get_paginated_response(self, data):
data = OrderedDict([
('meta', OrderedDict([
('total_count', self.total_count),
])),
('items', data),
])
return Response(data)
<commit_msg>Remove assert from WagtailPagination.paginate_queryset method<commit_after>from collections import OrderedDict
from django.conf import settings
from rest_framework.pagination import BasePagination
from rest_framework.response import Response
from .utils import BadRequestError
class WagtailPagination(BasePagination):
def paginate_queryset(self, queryset, request, view=None):
limit_max = getattr(settings, 'WAGTAILAPI_LIMIT_MAX', 20)
try:
offset = int(request.GET.get('offset', 0))
if offset < 0:
raise ValueError()
except ValueError:
raise BadRequestError("offset must be a positive integer")
try:
limit_default = 20 if not limit_max else min(20, limit_max)
limit = int(request.GET.get('limit', limit_default))
if limit < 0:
raise ValueError()
except ValueError:
raise BadRequestError("limit must be a positive integer")
if limit_max and limit > limit_max:
raise BadRequestError(
"limit cannot be higher than %d" % limit_max)
start = offset
stop = offset + limit
self.view = view
self.total_count = queryset.count()
return queryset[start:stop]
def get_paginated_response(self, data):
data = OrderedDict([
('meta', OrderedDict([
('total_count', self.total_count),
])),
('items', data),
])
return Response(data)
|
75dc15e5c4a9cf6e442dbe9e14d3f78f977b2e68
|
diesel/logmod.py
|
diesel/logmod.py
|
# vim:ts=4:sw=4:expandtab
'''A simple logging module that supports various verbosity
levels and component-specific subloggers.
'''
import sys
import time
from twiggy import log as olog, add_emitters, levels, outputs, formats, emitters
from functools import partial
diesel_format = formats.line_format
diesel_format.traceback_prefix = '\n'
diesel_format.conversion = formats.ConversionTable()
diesel_format.conversion.add("time", partial(time.strftime, "%Y/%m/%d %H:%M:%S"), "[{1}]".format)
diesel_format.conversion.add("name", str, "{{{1}}}".format)
diesel_format.conversion.add("level", str, "{1}".format)
diesel_format.conversion.aggregate = " ".join
diesel_format.conversion.genericValue = str
diesel_format.conversion.genericItem = lambda _1, _2: "%s=%s" % (_1, _2)
diesel_output = outputs.StreamOutput(diesel_format)
def set_log_level(level=levels.INFO):
emitters.clear()
add_emitters(
('*', level, None, diesel_output)
)
log = olog.name("diesel")
set_log_level()
|
# vim:ts=4:sw=4:expandtab
'''A simple logging module that supports various verbosity
levels and component-specific subloggers.
'''
import sys
import time
from twiggy import log as olog, levels, outputs, formats, emitters
try:
from twiggy import add_emitters
except ImportError:
from twiggy import addEmitters as add_emitters
from functools import partial
diesel_format = formats.line_format
diesel_format.traceback_prefix = '\n'
diesel_format.conversion = formats.ConversionTable()
diesel_format.conversion.add("time", partial(time.strftime, "%Y/%m/%d %H:%M:%S"), "[{1}]".format)
diesel_format.conversion.add("name", str, "{{{1}}}".format)
diesel_format.conversion.add("level", str, "{1}".format)
diesel_format.conversion.aggregate = " ".join
diesel_format.conversion.genericValue = str
diesel_format.conversion.genericItem = lambda _1, _2: "%s=%s" % (_1, _2)
diesel_output = outputs.StreamOutput(diesel_format)
def set_log_level(level=levels.INFO):
emitters.clear()
add_emitters(
('*', level, None, diesel_output)
)
log = olog.name("diesel")
set_log_level()
|
Support Twiggy 0.2 and 0.4 APIs
|
Support Twiggy 0.2 and 0.4 APIs
|
Python
|
bsd-3-clause
|
dieseldev/diesel
|
# vim:ts=4:sw=4:expandtab
'''A simple logging module that supports various verbosity
levels and component-specific subloggers.
'''
import sys
import time
from twiggy import log as olog, add_emitters, levels, outputs, formats, emitters
from functools import partial
diesel_format = formats.line_format
diesel_format.traceback_prefix = '\n'
diesel_format.conversion = formats.ConversionTable()
diesel_format.conversion.add("time", partial(time.strftime, "%Y/%m/%d %H:%M:%S"), "[{1}]".format)
diesel_format.conversion.add("name", str, "{{{1}}}".format)
diesel_format.conversion.add("level", str, "{1}".format)
diesel_format.conversion.aggregate = " ".join
diesel_format.conversion.genericValue = str
diesel_format.conversion.genericItem = lambda _1, _2: "%s=%s" % (_1, _2)
diesel_output = outputs.StreamOutput(diesel_format)
def set_log_level(level=levels.INFO):
emitters.clear()
add_emitters(
('*', level, None, diesel_output)
)
log = olog.name("diesel")
set_log_level()
Support Twiggy 0.2 and 0.4 APIs
|
# vim:ts=4:sw=4:expandtab
'''A simple logging module that supports various verbosity
levels and component-specific subloggers.
'''
import sys
import time
from twiggy import log as olog, levels, outputs, formats, emitters
try:
from twiggy import add_emitters
except ImportError:
from twiggy import addEmitters as add_emitters
from functools import partial
diesel_format = formats.line_format
diesel_format.traceback_prefix = '\n'
diesel_format.conversion = formats.ConversionTable()
diesel_format.conversion.add("time", partial(time.strftime, "%Y/%m/%d %H:%M:%S"), "[{1}]".format)
diesel_format.conversion.add("name", str, "{{{1}}}".format)
diesel_format.conversion.add("level", str, "{1}".format)
diesel_format.conversion.aggregate = " ".join
diesel_format.conversion.genericValue = str
diesel_format.conversion.genericItem = lambda _1, _2: "%s=%s" % (_1, _2)
diesel_output = outputs.StreamOutput(diesel_format)
def set_log_level(level=levels.INFO):
emitters.clear()
add_emitters(
('*', level, None, diesel_output)
)
log = olog.name("diesel")
set_log_level()
|
<commit_before># vim:ts=4:sw=4:expandtab
'''A simple logging module that supports various verbosity
levels and component-specific subloggers.
'''
import sys
import time
from twiggy import log as olog, add_emitters, levels, outputs, formats, emitters
from functools import partial
diesel_format = formats.line_format
diesel_format.traceback_prefix = '\n'
diesel_format.conversion = formats.ConversionTable()
diesel_format.conversion.add("time", partial(time.strftime, "%Y/%m/%d %H:%M:%S"), "[{1}]".format)
diesel_format.conversion.add("name", str, "{{{1}}}".format)
diesel_format.conversion.add("level", str, "{1}".format)
diesel_format.conversion.aggregate = " ".join
diesel_format.conversion.genericValue = str
diesel_format.conversion.genericItem = lambda _1, _2: "%s=%s" % (_1, _2)
diesel_output = outputs.StreamOutput(diesel_format)
def set_log_level(level=levels.INFO):
emitters.clear()
add_emitters(
('*', level, None, diesel_output)
)
log = olog.name("diesel")
set_log_level()
<commit_msg>Support Twiggy 0.2 and 0.4 APIs<commit_after>
|
# vim:ts=4:sw=4:expandtab
'''A simple logging module that supports various verbosity
levels and component-specific subloggers.
'''
import sys
import time
from twiggy import log as olog, levels, outputs, formats, emitters
try:
from twiggy import add_emitters
except ImportError:
from twiggy import addEmitters as add_emitters
from functools import partial
diesel_format = formats.line_format
diesel_format.traceback_prefix = '\n'
diesel_format.conversion = formats.ConversionTable()
diesel_format.conversion.add("time", partial(time.strftime, "%Y/%m/%d %H:%M:%S"), "[{1}]".format)
diesel_format.conversion.add("name", str, "{{{1}}}".format)
diesel_format.conversion.add("level", str, "{1}".format)
diesel_format.conversion.aggregate = " ".join
diesel_format.conversion.genericValue = str
diesel_format.conversion.genericItem = lambda _1, _2: "%s=%s" % (_1, _2)
diesel_output = outputs.StreamOutput(diesel_format)
def set_log_level(level=levels.INFO):
emitters.clear()
add_emitters(
('*', level, None, diesel_output)
)
log = olog.name("diesel")
set_log_level()
|
# vim:ts=4:sw=4:expandtab
'''A simple logging module that supports various verbosity
levels and component-specific subloggers.
'''
import sys
import time
from twiggy import log as olog, add_emitters, levels, outputs, formats, emitters
from functools import partial
diesel_format = formats.line_format
diesel_format.traceback_prefix = '\n'
diesel_format.conversion = formats.ConversionTable()
diesel_format.conversion.add("time", partial(time.strftime, "%Y/%m/%d %H:%M:%S"), "[{1}]".format)
diesel_format.conversion.add("name", str, "{{{1}}}".format)
diesel_format.conversion.add("level", str, "{1}".format)
diesel_format.conversion.aggregate = " ".join
diesel_format.conversion.genericValue = str
diesel_format.conversion.genericItem = lambda _1, _2: "%s=%s" % (_1, _2)
diesel_output = outputs.StreamOutput(diesel_format)
def set_log_level(level=levels.INFO):
emitters.clear()
add_emitters(
('*', level, None, diesel_output)
)
log = olog.name("diesel")
set_log_level()
Support Twiggy 0.2 and 0.4 APIs# vim:ts=4:sw=4:expandtab
'''A simple logging module that supports various verbosity
levels and component-specific subloggers.
'''
import sys
import time
from twiggy import log as olog, levels, outputs, formats, emitters
try:
from twiggy import add_emitters
except ImportError:
from twiggy import addEmitters as add_emitters
from functools import partial
diesel_format = formats.line_format
diesel_format.traceback_prefix = '\n'
diesel_format.conversion = formats.ConversionTable()
diesel_format.conversion.add("time", partial(time.strftime, "%Y/%m/%d %H:%M:%S"), "[{1}]".format)
diesel_format.conversion.add("name", str, "{{{1}}}".format)
diesel_format.conversion.add("level", str, "{1}".format)
diesel_format.conversion.aggregate = " ".join
diesel_format.conversion.genericValue = str
diesel_format.conversion.genericItem = lambda _1, _2: "%s=%s" % (_1, _2)
diesel_output = outputs.StreamOutput(diesel_format)
def set_log_level(level=levels.INFO):
emitters.clear()
add_emitters(
('*', level, None, diesel_output)
)
log = olog.name("diesel")
set_log_level()
|
<commit_before># vim:ts=4:sw=4:expandtab
'''A simple logging module that supports various verbosity
levels and component-specific subloggers.
'''
import sys
import time
from twiggy import log as olog, add_emitters, levels, outputs, formats, emitters
from functools import partial
diesel_format = formats.line_format
diesel_format.traceback_prefix = '\n'
diesel_format.conversion = formats.ConversionTable()
diesel_format.conversion.add("time", partial(time.strftime, "%Y/%m/%d %H:%M:%S"), "[{1}]".format)
diesel_format.conversion.add("name", str, "{{{1}}}".format)
diesel_format.conversion.add("level", str, "{1}".format)
diesel_format.conversion.aggregate = " ".join
diesel_format.conversion.genericValue = str
diesel_format.conversion.genericItem = lambda _1, _2: "%s=%s" % (_1, _2)
diesel_output = outputs.StreamOutput(diesel_format)
def set_log_level(level=levels.INFO):
emitters.clear()
add_emitters(
('*', level, None, diesel_output)
)
log = olog.name("diesel")
set_log_level()
<commit_msg>Support Twiggy 0.2 and 0.4 APIs<commit_after># vim:ts=4:sw=4:expandtab
'''A simple logging module that supports various verbosity
levels and component-specific subloggers.
'''
import sys
import time
from twiggy import log as olog, levels, outputs, formats, emitters
try:
from twiggy import add_emitters
except ImportError:
from twiggy import addEmitters as add_emitters
from functools import partial
diesel_format = formats.line_format
diesel_format.traceback_prefix = '\n'
diesel_format.conversion = formats.ConversionTable()
diesel_format.conversion.add("time", partial(time.strftime, "%Y/%m/%d %H:%M:%S"), "[{1}]".format)
diesel_format.conversion.add("name", str, "{{{1}}}".format)
diesel_format.conversion.add("level", str, "{1}".format)
diesel_format.conversion.aggregate = " ".join
diesel_format.conversion.genericValue = str
diesel_format.conversion.genericItem = lambda _1, _2: "%s=%s" % (_1, _2)
diesel_output = outputs.StreamOutput(diesel_format)
def set_log_level(level=levels.INFO):
emitters.clear()
add_emitters(
('*', level, None, diesel_output)
)
log = olog.name("diesel")
set_log_level()
|
690f771ac17bb1b81aaf3b4ae06fd8eac0735ac8
|
myflaskapp/tests/test_unit.py
|
myflaskapp/tests/test_unit.py
|
import unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
|
import unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
class TestMainPage:
"""WebTest test for title"""
def test_main_page_returns_200(self, user, testapp):
"""Login successful."""
# Goes to homepage
res = testapp.get('/')
assert res.status_code == 200
def test_main_page_returns_expected_title(self, user, testapp):
res = testapp.get('/')
assert '<title>\n \n tdd_with_python\n \n \n </title>\n' in res
|
Add TestMainPage using WebTest module
|
Add TestMainPage using WebTest module
|
Python
|
mit
|
terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python
|
import unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
Add TestMainPage using WebTest module
|
import unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
class TestMainPage:
"""WebTest test for title"""
def test_main_page_returns_200(self, user, testapp):
"""Login successful."""
# Goes to homepage
res = testapp.get('/')
assert res.status_code == 200
def test_main_page_returns_expected_title(self, user, testapp):
res = testapp.get('/')
assert '<title>\n \n tdd_with_python\n \n \n </title>\n' in res
|
<commit_before>import unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
<commit_msg>Add TestMainPage using WebTest module<commit_after>
|
import unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
class TestMainPage:
"""WebTest test for title"""
def test_main_page_returns_200(self, user, testapp):
"""Login successful."""
# Goes to homepage
res = testapp.get('/')
assert res.status_code == 200
def test_main_page_returns_expected_title(self, user, testapp):
res = testapp.get('/')
assert '<title>\n \n tdd_with_python\n \n \n </title>\n' in res
|
import unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
Add TestMainPage using WebTest moduleimport unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
class TestMainPage:
"""WebTest test for title"""
def test_main_page_returns_200(self, user, testapp):
"""Login successful."""
# Goes to homepage
res = testapp.get('/')
assert res.status_code == 200
def test_main_page_returns_expected_title(self, user, testapp):
res = testapp.get('/')
assert '<title>\n \n tdd_with_python\n \n \n </title>\n' in res
|
<commit_before>import unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
<commit_msg>Add TestMainPage using WebTest module<commit_after>import unittest
import requests
class SmokeTest(unittest.TestCase):
def test_maths(self):
self.assertEquals(6, 2 + 4)
def test_home_page_is_about_todo_lists(self):
request = requests.get('http://localhost:5000')
self.assertTrue(
request.content.startswith(bytes('\n\n<!doctype html>\n', 'utf-8')))
self.assertIn(
'<title>\n \n tdd_with_python\n \n \n </title>\n',
request.text)
self.assertTrue(
request.content.endswith(bytes('</body>\n</html>\n', 'utf-8')))
class TestMainPage:
"""WebTest test for title"""
def test_main_page_returns_200(self, user, testapp):
"""Login successful."""
# Goes to homepage
res = testapp.get('/')
assert res.status_code == 200
def test_main_page_returns_expected_title(self, user, testapp):
res = testapp.get('/')
assert '<title>\n \n tdd_with_python\n \n \n </title>\n' in res
|
1494bc56008f50f24d9046f7713b27a250b54eeb
|
skimage/transform/setup.py
|
skimage/transform/setup.py
|
#!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'],
extra_compile_args=['-fopenmp'],
extra_link_args=['-fopenmp'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
|
#!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
|
Remove unused fopenmp compile args
|
Remove unused fopenmp compile args
|
Python
|
bsd-3-clause
|
bennlich/scikit-image,rjeli/scikit-image,SamHames/scikit-image,dpshelio/scikit-image,ClinicalGraphics/scikit-image,Hiyorimi/scikit-image,pratapvardhan/scikit-image,emon10005/scikit-image,chintak/scikit-image,michaelaye/scikit-image,newville/scikit-image,ofgulban/scikit-image,chintak/scikit-image,blink1073/scikit-image,michaelaye/scikit-image,robintw/scikit-image,almarklein/scikit-image,WarrenWeckesser/scikits-image,Midafi/scikit-image,vighneshbirodkar/scikit-image,SamHames/scikit-image,paalge/scikit-image,vighneshbirodkar/scikit-image,keflavich/scikit-image,dpshelio/scikit-image,chriscrosscutler/scikit-image,ClinicalGraphics/scikit-image,almarklein/scikit-image,oew1v07/scikit-image,warmspringwinds/scikit-image,ajaybhat/scikit-image,keflavich/scikit-image,bsipocz/scikit-image,SamHames/scikit-image,vighneshbirodkar/scikit-image,robintw/scikit-image,youprofit/scikit-image,chriscrosscutler/scikit-image,almarklein/scikit-image,GaZ3ll3/scikit-image,warmspringwinds/scikit-image,emon10005/scikit-image,Britefury/scikit-image,juliusbierk/scikit-image,paalge/scikit-image,rjeli/scikit-image,ofgulban/scikit-image,ofgulban/scikit-image,jwiggins/scikit-image,SamHames/scikit-image,newville/scikit-image,youprofit/scikit-image,oew1v07/scikit-image,Midafi/scikit-image,michaelpacer/scikit-image,rjeli/scikit-image,Britefury/scikit-image,GaZ3ll3/scikit-image,almarklein/scikit-image,chintak/scikit-image,paalge/scikit-image,bennlich/scikit-image,michaelpacer/scikit-image,pratapvardhan/scikit-image,Hiyorimi/scikit-image,chintak/scikit-image,ajaybhat/scikit-image,jwiggins/scikit-image,juliusbierk/scikit-image,WarrenWeckesser/scikits-image,blink1073/scikit-image,bsipocz/scikit-image
|
#!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'],
extra_compile_args=['-fopenmp'],
extra_link_args=['-fopenmp'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
Remove unused fopenmp compile args
|
#!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
|
<commit_before>#!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'],
extra_compile_args=['-fopenmp'],
extra_link_args=['-fopenmp'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
<commit_msg>Remove unused fopenmp compile args<commit_after>
|
#!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
|
#!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'],
extra_compile_args=['-fopenmp'],
extra_link_args=['-fopenmp'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
Remove unused fopenmp compile args#!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
|
<commit_before>#!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'],
extra_compile_args=['-fopenmp'],
extra_link_args=['-fopenmp'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
<commit_msg>Remove unused fopenmp compile args<commit_after>#!/usr/bin/env python
import os
from skimage._build import cython
base_path = os.path.abspath(os.path.dirname(__file__))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('transform', parent_package, top_path)
config.add_data_dir('tests')
cython(['_hough_transform.pyx'], working_path=base_path)
cython(['_warps_cy.pyx'], working_path=base_path)
config.add_extension('_hough_transform', sources=['_hough_transform.c'],
include_dirs=[get_numpy_include_dirs()])
config.add_extension('_warps_cy', sources=['_warps_cy.c'],
include_dirs=[get_numpy_include_dirs(), '../_shared'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer='Scikits-image Developers',
author='Scikits-image Developers',
maintainer_email='scikits-image@googlegroups.com',
description='Transforms',
url='https://github.com/scikits-image/scikits-image',
license='SciPy License (BSD Style)',
**(configuration(top_path='').todict())
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.