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
31d9644f1f5790e63affd89fd0f2145777e8f0f6
pymodels/__init__.py
pymodels/__init__.py
"""PyModels package.""" import os as _os from . import LI_V01_01 from . import TB_V02_01 from . import BO_V03_02 from . import TS_V03_03 from . import SI_V22_02 from . import coordinate_system with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f: __version__ = _f.read().strip() __all__ = ('LI_V01_01', 'TB_V02_01', 'BO_V03_02', 'TS_V03_03', 'SI_V22_02') li = LI_V01_01 tb = TB_V02_01 bo = BO_V03_02 ts = TS_V03_03 si = SI_V22_02
"""PyModels package.""" import os as _os from . import LI_V01_01 from . import TB_V02_01 from . import BO_V03_02 from . import TS_V03_03 from . import SI_V24_04 from . import coordinate_system with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f: __version__ = _f.read().strip() __all__ = ('LI_V01_01', 'TB_V02_01', 'BO_V03_02', 'TS_V03_03', 'SI_V24_04') li = LI_V01_01 tb = TB_V02_01 bo = BO_V03_02 ts = TS_V03_03 si = SI_V24_04
Update SI version in init
Update SI version in init
Python
mit
lnls-fac/sirius
"""PyModels package.""" import os as _os from . import LI_V01_01 from . import TB_V02_01 from . import BO_V03_02 from . import TS_V03_03 from . import SI_V22_02 from . import coordinate_system with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f: __version__ = _f.read().strip() __all__ = ('LI_V01_01', 'TB_V02_01', 'BO_V03_02', 'TS_V03_03', 'SI_V22_02') li = LI_V01_01 tb = TB_V02_01 bo = BO_V03_02 ts = TS_V03_03 si = SI_V22_02 Update SI version in init
"""PyModels package.""" import os as _os from . import LI_V01_01 from . import TB_V02_01 from . import BO_V03_02 from . import TS_V03_03 from . import SI_V24_04 from . import coordinate_system with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f: __version__ = _f.read().strip() __all__ = ('LI_V01_01', 'TB_V02_01', 'BO_V03_02', 'TS_V03_03', 'SI_V24_04') li = LI_V01_01 tb = TB_V02_01 bo = BO_V03_02 ts = TS_V03_03 si = SI_V24_04
<commit_before>"""PyModels package.""" import os as _os from . import LI_V01_01 from . import TB_V02_01 from . import BO_V03_02 from . import TS_V03_03 from . import SI_V22_02 from . import coordinate_system with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f: __version__ = _f.read().strip() __all__ = ('LI_V01_01', 'TB_V02_01', 'BO_V03_02', 'TS_V03_03', 'SI_V22_02') li = LI_V01_01 tb = TB_V02_01 bo = BO_V03_02 ts = TS_V03_03 si = SI_V22_02 <commit_msg>Update SI version in init<commit_after>
"""PyModels package.""" import os as _os from . import LI_V01_01 from . import TB_V02_01 from . import BO_V03_02 from . import TS_V03_03 from . import SI_V24_04 from . import coordinate_system with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f: __version__ = _f.read().strip() __all__ = ('LI_V01_01', 'TB_V02_01', 'BO_V03_02', 'TS_V03_03', 'SI_V24_04') li = LI_V01_01 tb = TB_V02_01 bo = BO_V03_02 ts = TS_V03_03 si = SI_V24_04
"""PyModels package.""" import os as _os from . import LI_V01_01 from . import TB_V02_01 from . import BO_V03_02 from . import TS_V03_03 from . import SI_V22_02 from . import coordinate_system with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f: __version__ = _f.read().strip() __all__ = ('LI_V01_01', 'TB_V02_01', 'BO_V03_02', 'TS_V03_03', 'SI_V22_02') li = LI_V01_01 tb = TB_V02_01 bo = BO_V03_02 ts = TS_V03_03 si = SI_V22_02 Update SI version in init"""PyModels package.""" import os as _os from . import LI_V01_01 from . import TB_V02_01 from . import BO_V03_02 from . import TS_V03_03 from . import SI_V24_04 from . import coordinate_system with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f: __version__ = _f.read().strip() __all__ = ('LI_V01_01', 'TB_V02_01', 'BO_V03_02', 'TS_V03_03', 'SI_V24_04') li = LI_V01_01 tb = TB_V02_01 bo = BO_V03_02 ts = TS_V03_03 si = SI_V24_04
<commit_before>"""PyModels package.""" import os as _os from . import LI_V01_01 from . import TB_V02_01 from . import BO_V03_02 from . import TS_V03_03 from . import SI_V22_02 from . import coordinate_system with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f: __version__ = _f.read().strip() __all__ = ('LI_V01_01', 'TB_V02_01', 'BO_V03_02', 'TS_V03_03', 'SI_V22_02') li = LI_V01_01 tb = TB_V02_01 bo = BO_V03_02 ts = TS_V03_03 si = SI_V22_02 <commit_msg>Update SI version in init<commit_after>"""PyModels package.""" import os as _os from . import LI_V01_01 from . import TB_V02_01 from . import BO_V03_02 from . import TS_V03_03 from . import SI_V24_04 from . import coordinate_system with open(_os.path.join(__path__[0], 'VERSION'), 'r') as _f: __version__ = _f.read().strip() __all__ = ('LI_V01_01', 'TB_V02_01', 'BO_V03_02', 'TS_V03_03', 'SI_V24_04') li = LI_V01_01 tb = TB_V02_01 bo = BO_V03_02 ts = TS_V03_03 si = SI_V24_04
a1c8326b9e520a9f262360ef97e2d5651c2e973e
inventory.py
inventory.py
from flask import Flask, render_template, url_for, redirect from peewee import * app = Flask(__name__) database = SqliteDatabase('developmentData.db') #class Device(Model): @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ return render_template('inventory.html', inventoryData="", deviceLogData="") if __name__ == '__main__': db.connect() app.run()
from flask import Flask, render_template, url_for, redirect from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') #class Device(Model): @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ return render_template('inventory.html', inventoryData="", deviceLogData="") if __name__ == '__main__': db.connect() app.run()
Add comments for references later
Add comments for references later
Python
mit
lcdi/Inventory,lcdi/Inventory,lcdi/Inventory,lcdi/Inventory
from flask import Flask, render_template, url_for, redirect from peewee import * app = Flask(__name__) database = SqliteDatabase('developmentData.db') #class Device(Model): @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ return render_template('inventory.html', inventoryData="", deviceLogData="") if __name__ == '__main__': db.connect() app.run() Add comments for references later
from flask import Flask, render_template, url_for, redirect from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') #class Device(Model): @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ return render_template('inventory.html', inventoryData="", deviceLogData="") if __name__ == '__main__': db.connect() app.run()
<commit_before>from flask import Flask, render_template, url_for, redirect from peewee import * app = Flask(__name__) database = SqliteDatabase('developmentData.db') #class Device(Model): @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ return render_template('inventory.html', inventoryData="", deviceLogData="") if __name__ == '__main__': db.connect() app.run() <commit_msg>Add comments for references later<commit_after>
from flask import Flask, render_template, url_for, redirect from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') #class Device(Model): @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ return render_template('inventory.html', inventoryData="", deviceLogData="") if __name__ == '__main__': db.connect() app.run()
from flask import Flask, render_template, url_for, redirect from peewee import * app = Flask(__name__) database = SqliteDatabase('developmentData.db') #class Device(Model): @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ return render_template('inventory.html', inventoryData="", deviceLogData="") if __name__ == '__main__': db.connect() app.run() Add comments for references laterfrom flask import Flask, render_template, url_for, redirect from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') #class Device(Model): @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ return render_template('inventory.html', inventoryData="", deviceLogData="") if __name__ == '__main__': db.connect() app.run()
<commit_before>from flask import Flask, render_template, url_for, redirect from peewee import * app = Flask(__name__) database = SqliteDatabase('developmentData.db') #class Device(Model): @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ return render_template('inventory.html', inventoryData="", deviceLogData="") if __name__ == '__main__': db.connect() app.run() <commit_msg>Add comments for references later<commit_after>from flask import Flask, render_template, url_for, redirect from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') #class Device(Model): @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ return render_template('inventory.html', inventoryData="", deviceLogData="") if __name__ == '__main__': db.connect() app.run()
6a246c46f5adadc12fe4034c2b25e79196c3c831
bake/load.py
bake/load.py
# load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines
# load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '').replace('\\n','\n')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines
Allow for user-specified newline breaks in values
Allow for user-specified newline breaks in values
Python
mit
AlexSzatmary/bake
# load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines Allow for user-specified newline breaks in values
# load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '').replace('\\n','\n')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines
<commit_before># load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines <commit_msg>Allow for user-specified newline breaks in values<commit_after>
# load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '').replace('\\n','\n')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines
# load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines Allow for user-specified newline breaks in values# load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '').replace('\\n','\n')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines
<commit_before># load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines <commit_msg>Allow for user-specified newline breaks in values<commit_after># load.py # loads and formats bp files import re import os import os.path def load(iterator): """ Loads lines from an iterator and does line parsing 1 Handles line continuation 2 Handles include statements 3 Handle comments at start of line """ lines = [] for l in iterator: # Handle line continuation with trailing backslash m = re.search(r'(.*)\\\s*$', l) while m: l = m.group(1) + iterator.next().lstrip() m = re.search(r'(.*)\\\s*$', l) # Handle include statements: this removes comments at the end of # include lines m = re.match(r'\s*include\(\s*([^()]+)\s*\)\s*(#.*)?$', l) if m: lines.extend(load_file(m.group(1))) l = '' # Handle comments at start of line elif re.match(r'^\s*#', l): l = '' if l: lines.append(l.replace('\n', '').replace('\\n','\n')) return lines def load_file(f): """ Turn bp file into iterator and do load() on it. """ cd = os.getcwd() if os.path.dirname(f): os.chdir(os.path.dirname(f)) with open(os.path.basename(f)) as hin: lines = load(hin) os.chdir(cd) return lines
1abe172a31805d26a02b4c57d940c9afcc60ce78
etcd3/__init__.py
etcd3/__init__.py
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self): self.channel = grpc.insecure_channel('localhost:2379') self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client()
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self, host='localhost', port=2379): self.channel = grpc.insecure_channel('{host}:{port}'.format( host=host, port=port) ) self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client(host='localhost', port=2379)
Add host and port parameters
Add host and port parameters
Python
apache-2.0
kragniz/python-etcd3
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self): self.channel = grpc.insecure_channel('localhost:2379') self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client() Add host and port parameters
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self, host='localhost', port=2379): self.channel = grpc.insecure_channel('{host}:{port}'.format( host=host, port=port) ) self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client(host='localhost', port=2379)
<commit_before>from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self): self.channel = grpc.insecure_channel('localhost:2379') self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client() <commit_msg>Add host and port parameters<commit_after>
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self, host='localhost', port=2379): self.channel = grpc.insecure_channel('{host}:{port}'.format( host=host, port=port) ) self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client(host='localhost', port=2379)
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self): self.channel = grpc.insecure_channel('localhost:2379') self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client() Add host and port parametersfrom __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self, host='localhost', port=2379): self.channel = grpc.insecure_channel('{host}:{port}'.format( host=host, port=port) ) self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client(host='localhost', port=2379)
<commit_before>from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self): self.channel = grpc.insecure_channel('localhost:2379') self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client() <commit_msg>Add host and port parameters<commit_after>from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' __all__ = ['Etcd3Client', 'client'] import grpc from etcd3.etcdrpc import rpc_pb2 as etcdrpc import etcd3.exceptions as exceptions class Etcd3Client(object): def __init__(self, host='localhost', port=2379): self.channel = grpc.insecure_channel('{host}:{port}'.format( host=host, port=port) ) self.kvstub = etcdrpc.KVStub(self.channel) def get(self, key): ''' Get the value of a key from etcd. ''' raise exceptions.KeyNotFoundError( 'the key "{}" was not found'.format(key)) def put(self, key, value): ''' Save a value to etcd. ''' put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request) def client(): '''Return an instance of an Etcd3Client''' return Etcd3Client(host='localhost', port=2379)
83d4c5b9b1f7ed9b75ae04464423b7ca4b5d627d
nova/db/sqlalchemy/migrate_repo/versions/037_add_config_drive_to_instances.py
nova/db/sqlalchemy/migrate_repo/versions/037_add_config_drive_to_instances.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) config_drive_column = Column("config_drive", String(255)) # matches image_ref def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) rows = migrate_engine.execute(instances.select()) for row in rows: instance_config_drive = None # pre-existing instances don't have one. migrate_engine.execute(instances.update()\ .where(instances.c.id == row[0])\ .values(config_drive=instance_config_drive)) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) # matches the size of an image_ref config_drive_column = Column("config_drive", String(255), nullable=True) def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column)
Fix config_drive migration, per Matt Dietz.
Fix config_drive migration, per Matt Dietz.
Python
apache-2.0
plumgrid/plumgrid-nova,adelina-t/nova,houshengbo/nova_vmware_compute_driver,cyx1231st/nova,redhat-openstack/nova,noironetworks/nova,jeffrey4l/nova,Stavitsky/nova,zaina/nova,CloudServer/nova,openstack/nova,sridevikoushik31/nova,eonpatapon/nova,usc-isi/extra-specs,shail2810/nova,sridevikoushik31/nova,russellb/nova,bclau/nova,ntt-sic/nova,badock/nova,eneabio/nova,CEG-FYP-OpenStack/scheduler,eharney/nova,jianghuaw/nova,BeyondTheClouds/nova,watonyweng/nova,ruslanloman/nova,takeshineshiro/nova,mikalstill/nova,Juniper/nova,KarimAllah/nova,plumgrid/plumgrid-nova,isyippee/nova,TwinkleChawla/nova,maelnor/nova,dims/nova,fnordahl/nova,NewpTone/stacklab-nova,hanlind/nova,vmturbo/nova,devendermishrajio/nova,petrutlucian94/nova,savi-dev/nova,Francis-Liu/animated-broccoli,mahak/nova,noironetworks/nova,rrader/nova-docker-plugin,dawnpower/nova,orbitfp7/nova,scripnichenko/nova,affo/nova,tudorvio/nova,usc-isi/nova,double12gzh/nova,tealover/nova,thomasem/nova,citrix-openstack-build/nova,projectcalico/calico-nova,cyx1231st/nova,aristanetworks/arista-ovs-nova,sacharya/nova,mandeepdhami/nova,cloudbase/nova-virtualbox,jianghuaw/nova,petrutlucian94/nova_dev,eharney/nova,CEG-FYP-OpenStack/scheduler,usc-isi/extra-specs,devoid/nova,usc-isi/nova,blueboxgroup/nova,rahulunair/nova,cloudbau/nova,JianyuWang/nova,edulramirez/nova,NoBodyCam/TftpPxeBootBareMetal,rahulunair/nova,cloudbase/nova-virtualbox,saleemjaveds/https-github.com-openstack-nova,raildo/nova,joker946/nova,vladikr/nova_drafts,felixma/nova,tangfeixiong/nova,aristanetworks/arista-ovs-nova,zhimin711/nova,maheshp/novatest,Metaswitch/calico-nova,BeyondTheClouds/nova,affo/nova,yrobla/nova,tianweizhang/nova,eneabio/nova,NeCTAR-RC/nova,felixma/nova,shahar-stratoscale/nova,NewpTone/stacklab-nova,alaski/nova,DirectXMan12/nova-hacking,blueboxgroup/nova,dstroppa/openstack-smartos-nova-grizzly,varunarya10/nova_test_latest,eneabio/nova,klmitch/nova,silenceli/nova,watonyweng/nova,OpenAcademy-OpenStack/nova-scheduler,NoBodyCam/TftpPxeBootBareMetal,vmturbo/nova,dstroppa/openstack-smartos-nova-grizzly,yatinkumbhare/openstack-nova,TwinkleChawla/nova,dims/nova,ntt-sic/nova,josephsuh/extra-specs,leilihh/novaha,Triv90/Nova,yosshy/nova,ewindisch/nova,cloudbase/nova,apporc/nova,psiwczak/openstack,cloudbase/nova,mmnelemane/nova,salv-orlando/MyRepo,gooddata/openstack-nova,fajoy/nova,russellb/nova,tangfeixiong/nova,akash1808/nova,redhat-openstack/nova,vmturbo/nova,jianghuaw/nova,TieWei/nova,virtualopensystems/nova,rickerc/nova_audit,Francis-Liu/animated-broccoli,rajalokan/nova,fnordahl/nova,maoy/zknova,sebrandon1/nova,yosshy/nova,bgxavier/nova,zzicewind/nova,joker946/nova,apporc/nova,usc-isi/nova,rrader/nova-docker-plugin,shootstar/novatest,SUSE-Cloud/nova,MountainWei/nova,viggates/nova,imsplitbit/nova,imsplitbit/nova,klmitch/nova,sridevikoushik31/nova,fajoy/nova,KarimAllah/nova,kimjaejoong/nova,rajalokan/nova,tianweizhang/nova,savi-dev/nova,josephsuh/extra-specs,psiwczak/openstack,alaski/nova,phenoxim/nova,double12gzh/nova,jianghuaw/nova,angdraug/nova,alvarolopez/nova,akash1808/nova,JioCloud/nova_test_latest,sebrandon1/nova,mgagne/nova,phenoxim/nova,paulmathews/nova,mgagne/nova,CCI-MOC/nova,nikesh-mahalka/nova,BeyondTheClouds/nova,Brocade-OpenSource/OpenStack-DNRM-Nova,leilihh/novaha,whitepages/nova,josephsuh/extra-specs,MountainWei/nova,Juniper/nova,mikalstill/nova,fajoy/nova,isyippee/nova,cernops/nova,sridevikoushik31/openstack,Triv90/Nova,JioCloud/nova_test_latest,scripnichenko/nova,cernops/nova,dawnpower/nova,OpenAcademy-OpenStack/nova-scheduler,zaina/nova,viggates/nova,virtualopensystems/nova,gooddata/openstack-nova,badock/nova,raildo/nova,maheshp/novatest,silenceli/nova,thomasem/nova,eayunstack/nova,maoy/zknova,Triv90/Nova,sridevikoushik31/openstack,LoHChina/nova,barnsnake351/nova,luogangyi/bcec-nova,ewindisch/nova,whitepages/nova,leilihh/nova,sileht/deb-openstack-nova,mahak/nova,cloudbase/nova,petrutlucian94/nova,shail2810/nova,cloudbau/nova,spring-week-topos/nova-week,NewpTone/stacklab-nova,akash1808/nova_test_latest,spring-week-topos/nova-week,gspilio/nova,KarimAllah/nova,alexandrucoman/vbox-nova-driver,Juniper/nova,shahar-stratoscale/nova,ted-gould/nova,CCI-MOC/nova,bigswitch/nova,maelnor/nova,belmiromoreira/nova,angdraug/nova,CloudServer/nova,cernops/nova,openstack/nova,Tehsmash/nova,TieWei/nova,qwefi/nova,dstroppa/openstack-smartos-nova-grizzly,yrobla/nova,projectcalico/calico-nova,edulramirez/nova,psiwczak/openstack,JioCloud/nova,maheshp/novatest,rahulunair/nova,ted-gould/nova,mikalstill/nova,houshengbo/nova_vmware_compute_driver,yatinkumbhare/openstack-nova,DirectXMan12/nova-hacking,Stavitsky/nova,rajalokan/nova,hanlind/nova,barnsnake351/nova,berrange/nova,vmturbo/nova,DirectXMan12/nova-hacking,Juniper/nova,ruslanloman/nova,iuliat/nova,gspilio/nova,citrix-openstack-build/nova,orbitfp7/nova,LoHChina/nova,kimjaejoong/nova,paulmathews/nova,klmitch/nova,JioCloud/nova,tanglei528/nova,devendermishrajio/nova,sacharya/nova,Brocade-OpenSource/OpenStack-DNRM-Nova,j-carpentier/nova,mmnelemane/nova,tealover/nova,qwefi/nova,Yuriy-Leonov/nova,openstack/nova,bclau/nova,houshengbo/nova_vmware_compute_driver,russellb/nova,alexandrucoman/vbox-nova-driver,sileht/deb-openstack-nova,saleemjaveds/https-github.com-openstack-nova,luogangyi/bcec-nova,mahak/nova,leilihh/nova,salv-orlando/MyRepo,paulmathews/nova,sridevikoushik31/nova,klmitch/nova,akash1808/nova_test_latest,CiscoSystems/nova,CiscoSystems/nova,gooddata/openstack-nova,rickerc/nova_audit,tudorvio/nova,NeCTAR-RC/nova,takeshineshiro/nova,sileht/deb-openstack-nova,hanlind/nova,devoid/nova,Tehsmash/nova,eonpatapon/nova,NoBodyCam/TftpPxeBootBareMetal,zzicewind/nova,bgxavier/nova,Yuriy-Leonov/nova,mandeepdhami/nova,iuliat/nova,berrange/nova,usc-isi/extra-specs,alvarolopez/nova,bigswitch/nova,gooddata/openstack-nova,rajalokan/nova,petrutlucian94/nova_dev,tanglei528/nova,SUSE-Cloud/nova,maoy/zknova,sridevikoushik31/openstack,gspilio/nova,vladikr/nova_drafts,jeffrey4l/nova,salv-orlando/MyRepo,yrobla/nova,JianyuWang/nova,Yusuke1987/openstack_template,shootstar/novatest,Yusuke1987/openstack_template,varunarya10/nova_test_latest,belmiromoreira/nova,nikesh-mahalka/nova,devendermishrajio/nova_test_latest,adelina-t/nova,eayunstack/nova,j-carpentier/nova,savi-dev/nova,devendermishrajio/nova_test_latest,Metaswitch/calico-nova,aristanetworks/arista-ovs-nova,sebrandon1/nova,zhimin711/nova
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) config_drive_column = Column("config_drive", String(255)) # matches image_ref def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) rows = migrate_engine.execute(instances.select()) for row in rows: instance_config_drive = None # pre-existing instances don't have one. migrate_engine.execute(instances.update()\ .where(instances.c.id == row[0])\ .values(config_drive=instance_config_drive)) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column) Fix config_drive migration, per Matt Dietz.
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) # matches the size of an image_ref config_drive_column = Column("config_drive", String(255), nullable=True) def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column)
<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) config_drive_column = Column("config_drive", String(255)) # matches image_ref def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) rows = migrate_engine.execute(instances.select()) for row in rows: instance_config_drive = None # pre-existing instances don't have one. migrate_engine.execute(instances.update()\ .where(instances.c.id == row[0])\ .values(config_drive=instance_config_drive)) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column) <commit_msg>Fix config_drive migration, per Matt Dietz.<commit_after>
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) # matches the size of an image_ref config_drive_column = Column("config_drive", String(255), nullable=True) def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) config_drive_column = Column("config_drive", String(255)) # matches image_ref def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) rows = migrate_engine.execute(instances.select()) for row in rows: instance_config_drive = None # pre-existing instances don't have one. migrate_engine.execute(instances.update()\ .where(instances.c.id == row[0])\ .values(config_drive=instance_config_drive)) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column) Fix config_drive migration, per Matt Dietz.# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) # matches the size of an image_ref config_drive_column = Column("config_drive", String(255), nullable=True) def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column)
<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) config_drive_column = Column("config_drive", String(255)) # matches image_ref def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) rows = migrate_engine.execute(instances.select()) for row in rows: instance_config_drive = None # pre-existing instances don't have one. migrate_engine.execute(instances.update()\ .where(instances.c.id == row[0])\ .values(config_drive=instance_config_drive)) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column) <commit_msg>Fix config_drive migration, per Matt Dietz.<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table from nova import utils meta = MetaData() instances = Table("instances", meta, Column("id", Integer(), primary_key=True, nullable=False)) # matches the size of an image_ref config_drive_column = Column("config_drive", String(255), nullable=True) def upgrade(migrate_engine): meta.bind = migrate_engine instances.create_column(config_drive_column) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column(config_drive_column)
4c69afe07533c37c3780b653d343e795cc515c5c
tests/test_examples.py
tests/test_examples.py
# -*- coding: utf8 - *- from __future__ import absolute_import, print_function, unicode_literals import examples.basic_usage import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options): examples.basic_usage.run(unihan_options=unihan_options)
# -*- coding: utf8 - *- from __future__ import absolute_import, print_function, unicode_literals import examples.basic_usage import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys): examples.basic_usage.run(unihan_options=unihan_options) captured = capsys.readouterr() assert 'lookup for 好: good' in captured.out assert 'matches for "good": 好' in captured.out
Add stdout tests for basic usage example
Add stdout tests for basic usage example
Python
mit
cihai/cihai,cihai/cihai-python,cihai/cihai
# -*- coding: utf8 - *- from __future__ import absolute_import, print_function, unicode_literals import examples.basic_usage import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options): examples.basic_usage.run(unihan_options=unihan_options) Add stdout tests for basic usage example
# -*- coding: utf8 - *- from __future__ import absolute_import, print_function, unicode_literals import examples.basic_usage import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys): examples.basic_usage.run(unihan_options=unihan_options) captured = capsys.readouterr() assert 'lookup for 好: good' in captured.out assert 'matches for "good": 好' in captured.out
<commit_before># -*- coding: utf8 - *- from __future__ import absolute_import, print_function, unicode_literals import examples.basic_usage import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options): examples.basic_usage.run(unihan_options=unihan_options) <commit_msg>Add stdout tests for basic usage example<commit_after>
# -*- coding: utf8 - *- from __future__ import absolute_import, print_function, unicode_literals import examples.basic_usage import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys): examples.basic_usage.run(unihan_options=unihan_options) captured = capsys.readouterr() assert 'lookup for 好: good' in captured.out assert 'matches for "good": 好' in captured.out
# -*- coding: utf8 - *- from __future__ import absolute_import, print_function, unicode_literals import examples.basic_usage import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options): examples.basic_usage.run(unihan_options=unihan_options) Add stdout tests for basic usage example# -*- coding: utf8 - *- from __future__ import absolute_import, print_function, unicode_literals import examples.basic_usage import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys): examples.basic_usage.run(unihan_options=unihan_options) captured = capsys.readouterr() assert 'lookup for 好: good' in captured.out assert 'matches for "good": 好' in captured.out
<commit_before># -*- coding: utf8 - *- from __future__ import absolute_import, print_function, unicode_literals import examples.basic_usage import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options): examples.basic_usage.run(unihan_options=unihan_options) <commit_msg>Add stdout tests for basic usage example<commit_after># -*- coding: utf8 - *- from __future__ import absolute_import, print_function, unicode_literals import examples.basic_usage import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys): examples.basic_usage.run(unihan_options=unihan_options) captured = capsys.readouterr() assert 'lookup for 好: good' in captured.out assert 'matches for "good": 好' in captured.out
a64221bbf3ebc2c1be24c82870f1f233bac10cd4
app_v2/client.py
app_v2/client.py
#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "localhost" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value)
#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "192.168.0.1" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value)
Update host to use Pi’s static address
Update host to use Pi’s static address
Python
mit
thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x
#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "localhost" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value) Update host to use Pi’s static address
#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "192.168.0.1" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value)
<commit_before>#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "localhost" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value) <commit_msg>Update host to use Pi’s static address<commit_after>
#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "192.168.0.1" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value)
#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "localhost" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value) Update host to use Pi’s static address#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "192.168.0.1" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value)
<commit_before>#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "localhost" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value) <commit_msg>Update host to use Pi’s static address<commit_after>#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "192.168.0.1" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value)
f6313e28bbf00d65d6a4635b5377f9ad06548de6
appengine_config.py
appengine_config.py
# Copyright 2013 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Configures appstats. https://developers.google.com/appengine/docs/python/tools/appengineconfig """ # Enable appstats and optionally cost calculation. # Change these values and upload again if you want to enable appstats. enable_appstats = False appstats_CALC_RPC_COSTS = False def webapp_add_wsgi_middleware(app): """Overrides the wsgi application with appstats if enabled. https://developers.google.com/appengine/docs/python/tools/appstats """ if enable_appstats: # pylint: disable=E0611,F0401 from google.appengine.ext.appstats import recording return recording.appstats_wsgi_middleware(app) return app
# Copyright 2013 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Configures appstats. https://developers.google.com/appengine/docs/python/tools/appengineconfig """ # The app engine headers are located locally, so don't worry about not finding # them. # pylint: disable=E0611,F0401 from google.appengine.api import app_identity # pylint: enable=E0611,F0401 # Enable appstats and optionally cost calculation on a dev instance. enable_appstats = app_identity.get_application_id().endswith('-dev') appstats_CALC_RPC_COSTS = False def webapp_add_wsgi_middleware(app): """Overrides the wsgi application with appstats if enabled. https://developers.google.com/appengine/docs/python/tools/appstats """ if enable_appstats: # pylint: disable=E0611,F0401 from google.appengine.ext.appstats import recording return recording.appstats_wsgi_middleware(app) return app
Enable app stats on '-dev' instance.
Enable app stats on '-dev' instance. This will also enable them on local dev server as well since default app name in app.yaml is 'isolateserver-dev'. R=maruel@chromium.org Review URL: https://codereview.appspot.com/13457054
Python
apache-2.0
luci/luci-py,luci/luci-py,madecoste/swarming,luci/luci-py,pombreda/swarming,madecoste/swarming,madecoste/swarming,pombreda/swarming,pombreda/swarming,luci/luci-py,pombreda/swarming,madecoste/swarming
# Copyright 2013 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Configures appstats. https://developers.google.com/appengine/docs/python/tools/appengineconfig """ # Enable appstats and optionally cost calculation. # Change these values and upload again if you want to enable appstats. enable_appstats = False appstats_CALC_RPC_COSTS = False def webapp_add_wsgi_middleware(app): """Overrides the wsgi application with appstats if enabled. https://developers.google.com/appengine/docs/python/tools/appstats """ if enable_appstats: # pylint: disable=E0611,F0401 from google.appengine.ext.appstats import recording return recording.appstats_wsgi_middleware(app) return app Enable app stats on '-dev' instance. This will also enable them on local dev server as well since default app name in app.yaml is 'isolateserver-dev'. R=maruel@chromium.org Review URL: https://codereview.appspot.com/13457054
# Copyright 2013 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Configures appstats. https://developers.google.com/appengine/docs/python/tools/appengineconfig """ # The app engine headers are located locally, so don't worry about not finding # them. # pylint: disable=E0611,F0401 from google.appengine.api import app_identity # pylint: enable=E0611,F0401 # Enable appstats and optionally cost calculation on a dev instance. enable_appstats = app_identity.get_application_id().endswith('-dev') appstats_CALC_RPC_COSTS = False def webapp_add_wsgi_middleware(app): """Overrides the wsgi application with appstats if enabled. https://developers.google.com/appengine/docs/python/tools/appstats """ if enable_appstats: # pylint: disable=E0611,F0401 from google.appengine.ext.appstats import recording return recording.appstats_wsgi_middleware(app) return app
<commit_before># Copyright 2013 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Configures appstats. https://developers.google.com/appengine/docs/python/tools/appengineconfig """ # Enable appstats and optionally cost calculation. # Change these values and upload again if you want to enable appstats. enable_appstats = False appstats_CALC_RPC_COSTS = False def webapp_add_wsgi_middleware(app): """Overrides the wsgi application with appstats if enabled. https://developers.google.com/appengine/docs/python/tools/appstats """ if enable_appstats: # pylint: disable=E0611,F0401 from google.appengine.ext.appstats import recording return recording.appstats_wsgi_middleware(app) return app <commit_msg>Enable app stats on '-dev' instance. This will also enable them on local dev server as well since default app name in app.yaml is 'isolateserver-dev'. R=maruel@chromium.org Review URL: https://codereview.appspot.com/13457054<commit_after>
# Copyright 2013 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Configures appstats. https://developers.google.com/appengine/docs/python/tools/appengineconfig """ # The app engine headers are located locally, so don't worry about not finding # them. # pylint: disable=E0611,F0401 from google.appengine.api import app_identity # pylint: enable=E0611,F0401 # Enable appstats and optionally cost calculation on a dev instance. enable_appstats = app_identity.get_application_id().endswith('-dev') appstats_CALC_RPC_COSTS = False def webapp_add_wsgi_middleware(app): """Overrides the wsgi application with appstats if enabled. https://developers.google.com/appengine/docs/python/tools/appstats """ if enable_appstats: # pylint: disable=E0611,F0401 from google.appengine.ext.appstats import recording return recording.appstats_wsgi_middleware(app) return app
# Copyright 2013 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Configures appstats. https://developers.google.com/appengine/docs/python/tools/appengineconfig """ # Enable appstats and optionally cost calculation. # Change these values and upload again if you want to enable appstats. enable_appstats = False appstats_CALC_RPC_COSTS = False def webapp_add_wsgi_middleware(app): """Overrides the wsgi application with appstats if enabled. https://developers.google.com/appengine/docs/python/tools/appstats """ if enable_appstats: # pylint: disable=E0611,F0401 from google.appengine.ext.appstats import recording return recording.appstats_wsgi_middleware(app) return app Enable app stats on '-dev' instance. This will also enable them on local dev server as well since default app name in app.yaml is 'isolateserver-dev'. R=maruel@chromium.org Review URL: https://codereview.appspot.com/13457054# Copyright 2013 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Configures appstats. https://developers.google.com/appengine/docs/python/tools/appengineconfig """ # The app engine headers are located locally, so don't worry about not finding # them. # pylint: disable=E0611,F0401 from google.appengine.api import app_identity # pylint: enable=E0611,F0401 # Enable appstats and optionally cost calculation on a dev instance. enable_appstats = app_identity.get_application_id().endswith('-dev') appstats_CALC_RPC_COSTS = False def webapp_add_wsgi_middleware(app): """Overrides the wsgi application with appstats if enabled. https://developers.google.com/appengine/docs/python/tools/appstats """ if enable_appstats: # pylint: disable=E0611,F0401 from google.appengine.ext.appstats import recording return recording.appstats_wsgi_middleware(app) return app
<commit_before># Copyright 2013 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Configures appstats. https://developers.google.com/appengine/docs/python/tools/appengineconfig """ # Enable appstats and optionally cost calculation. # Change these values and upload again if you want to enable appstats. enable_appstats = False appstats_CALC_RPC_COSTS = False def webapp_add_wsgi_middleware(app): """Overrides the wsgi application with appstats if enabled. https://developers.google.com/appengine/docs/python/tools/appstats """ if enable_appstats: # pylint: disable=E0611,F0401 from google.appengine.ext.appstats import recording return recording.appstats_wsgi_middleware(app) return app <commit_msg>Enable app stats on '-dev' instance. This will also enable them on local dev server as well since default app name in app.yaml is 'isolateserver-dev'. R=maruel@chromium.org Review URL: https://codereview.appspot.com/13457054<commit_after># Copyright 2013 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Configures appstats. https://developers.google.com/appengine/docs/python/tools/appengineconfig """ # The app engine headers are located locally, so don't worry about not finding # them. # pylint: disable=E0611,F0401 from google.appengine.api import app_identity # pylint: enable=E0611,F0401 # Enable appstats and optionally cost calculation on a dev instance. enable_appstats = app_identity.get_application_id().endswith('-dev') appstats_CALC_RPC_COSTS = False def webapp_add_wsgi_middleware(app): """Overrides the wsgi application with appstats if enabled. https://developers.google.com/appengine/docs/python/tools/appstats """ if enable_appstats: # pylint: disable=E0611,F0401 from google.appengine.ext.appstats import recording return recording.appstats_wsgi_middleware(app) return app
215e02ea7a5aecd73fcef39f7aac3e6622dcf906
api/wikia.py
api/wikia.py
import urllib.request import json class Wikia: wiki_name = "" def __init__(self, wiki): self.wiki_name = wiki def search(self, term, limit=1): # Search for a page on Wikia # TODO: make limits over 1 return an array searchTerm = term.replace(" ", "+") url = "http://starvstheforcesofevil.wikia.com/api/v1/Search/List?query={}&limit=1&minArticleQuality=10&batch=1&namespaces=0%2C14".format(searchTerm) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['items'] def getPage(self, page_id): # Get a page on Wikia based on the page ID url = "http://starvstheforcesofevil.wikia.com/api/v1/Articles/AsSimpleJson?id={}".format(page_id) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['sections']
import urllib.request import json class Wikia: wiki_name = "" def __init__(self, wiki): self.wiki_name = wiki def search(self, term, limit=1): # Search for a page on Wikia # TODO: make limits over 1 return an array searchTerm = term.replace(" ", "+") url = "http://{}.wikia.com/api/v1/Search/List?query={}&limit=1&minArticleQuality=10&batch=1&namespaces=0%2C14".format(self.wiki_name, searchTerm) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['items'] def getPage(self, page_id): # Get a page on Wikia based on the page ID url = "http://{}.wikia.com/api/v1/Articles/AsSimpleJson?id={}".format(self.wiki_name, page_id) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['sections']
Fix Wikia API to not be limited to SVTFOE Wikia
Fix Wikia API to not be limited to SVTFOE Wikia
Python
apache-2.0
StarbotDiscord/Starbot,dhinakg/BitSTAR,StarbotDiscord/Starbot,dhinakg/BitSTAR
import urllib.request import json class Wikia: wiki_name = "" def __init__(self, wiki): self.wiki_name = wiki def search(self, term, limit=1): # Search for a page on Wikia # TODO: make limits over 1 return an array searchTerm = term.replace(" ", "+") url = "http://starvstheforcesofevil.wikia.com/api/v1/Search/List?query={}&limit=1&minArticleQuality=10&batch=1&namespaces=0%2C14".format(searchTerm) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['items'] def getPage(self, page_id): # Get a page on Wikia based on the page ID url = "http://starvstheforcesofevil.wikia.com/api/v1/Articles/AsSimpleJson?id={}".format(page_id) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['sections']Fix Wikia API to not be limited to SVTFOE Wikia
import urllib.request import json class Wikia: wiki_name = "" def __init__(self, wiki): self.wiki_name = wiki def search(self, term, limit=1): # Search for a page on Wikia # TODO: make limits over 1 return an array searchTerm = term.replace(" ", "+") url = "http://{}.wikia.com/api/v1/Search/List?query={}&limit=1&minArticleQuality=10&batch=1&namespaces=0%2C14".format(self.wiki_name, searchTerm) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['items'] def getPage(self, page_id): # Get a page on Wikia based on the page ID url = "http://{}.wikia.com/api/v1/Articles/AsSimpleJson?id={}".format(self.wiki_name, page_id) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['sections']
<commit_before>import urllib.request import json class Wikia: wiki_name = "" def __init__(self, wiki): self.wiki_name = wiki def search(self, term, limit=1): # Search for a page on Wikia # TODO: make limits over 1 return an array searchTerm = term.replace(" ", "+") url = "http://starvstheforcesofevil.wikia.com/api/v1/Search/List?query={}&limit=1&minArticleQuality=10&batch=1&namespaces=0%2C14".format(searchTerm) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['items'] def getPage(self, page_id): # Get a page on Wikia based on the page ID url = "http://starvstheforcesofevil.wikia.com/api/v1/Articles/AsSimpleJson?id={}".format(page_id) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['sections']<commit_msg>Fix Wikia API to not be limited to SVTFOE Wikia<commit_after>
import urllib.request import json class Wikia: wiki_name = "" def __init__(self, wiki): self.wiki_name = wiki def search(self, term, limit=1): # Search for a page on Wikia # TODO: make limits over 1 return an array searchTerm = term.replace(" ", "+") url = "http://{}.wikia.com/api/v1/Search/List?query={}&limit=1&minArticleQuality=10&batch=1&namespaces=0%2C14".format(self.wiki_name, searchTerm) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['items'] def getPage(self, page_id): # Get a page on Wikia based on the page ID url = "http://{}.wikia.com/api/v1/Articles/AsSimpleJson?id={}".format(self.wiki_name, page_id) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['sections']
import urllib.request import json class Wikia: wiki_name = "" def __init__(self, wiki): self.wiki_name = wiki def search(self, term, limit=1): # Search for a page on Wikia # TODO: make limits over 1 return an array searchTerm = term.replace(" ", "+") url = "http://starvstheforcesofevil.wikia.com/api/v1/Search/List?query={}&limit=1&minArticleQuality=10&batch=1&namespaces=0%2C14".format(searchTerm) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['items'] def getPage(self, page_id): # Get a page on Wikia based on the page ID url = "http://starvstheforcesofevil.wikia.com/api/v1/Articles/AsSimpleJson?id={}".format(page_id) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['sections']Fix Wikia API to not be limited to SVTFOE Wikiaimport urllib.request import json class Wikia: wiki_name = "" def __init__(self, wiki): self.wiki_name = wiki def search(self, term, limit=1): # Search for a page on Wikia # TODO: make limits over 1 return an array searchTerm = term.replace(" ", "+") url = "http://{}.wikia.com/api/v1/Search/List?query={}&limit=1&minArticleQuality=10&batch=1&namespaces=0%2C14".format(self.wiki_name, searchTerm) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['items'] def getPage(self, page_id): # Get a page on Wikia based on the page ID url = "http://{}.wikia.com/api/v1/Articles/AsSimpleJson?id={}".format(self.wiki_name, page_id) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['sections']
<commit_before>import urllib.request import json class Wikia: wiki_name = "" def __init__(self, wiki): self.wiki_name = wiki def search(self, term, limit=1): # Search for a page on Wikia # TODO: make limits over 1 return an array searchTerm = term.replace(" ", "+") url = "http://starvstheforcesofevil.wikia.com/api/v1/Search/List?query={}&limit=1&minArticleQuality=10&batch=1&namespaces=0%2C14".format(searchTerm) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['items'] def getPage(self, page_id): # Get a page on Wikia based on the page ID url = "http://starvstheforcesofevil.wikia.com/api/v1/Articles/AsSimpleJson?id={}".format(page_id) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['sections']<commit_msg>Fix Wikia API to not be limited to SVTFOE Wikia<commit_after>import urllib.request import json class Wikia: wiki_name = "" def __init__(self, wiki): self.wiki_name = wiki def search(self, term, limit=1): # Search for a page on Wikia # TODO: make limits over 1 return an array searchTerm = term.replace(" ", "+") url = "http://{}.wikia.com/api/v1/Search/List?query={}&limit=1&minArticleQuality=10&batch=1&namespaces=0%2C14".format(self.wiki_name, searchTerm) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['items'] def getPage(self, page_id): # Get a page on Wikia based on the page ID url = "http://{}.wikia.com/api/v1/Articles/AsSimpleJson?id={}".format(self.wiki_name, page_id) jsonString = urllib.request.urlopen(url).read().decode("utf-8") json_d = json.loads(jsonString) return json_d['sections']
1316e3ab69fe3e08de6d6f08a04ce0f4bd94dc04
examples/completion.py
examples/completion.py
import gtk from kiwi.ui.widgets.entry import Entry entry = Entry() entry.set_completion_strings(['apa', 'apapa', 'apbla', 'apppa', 'aaspa']) win = gtk.Window() win.connect('delete-event', gtk.main_quit) win.add(entry) win.show_all() gtk.main()
# encoding: iso-8859-1 import gtk from kiwi.ui.widgets.entry import Entry def on_entry_activate(entry): print 'You selected:', entry.get_text().encode('latin1') gtk.main_quit() entry = Entry() entry.connect('activate', on_entry_activate) entry.set_completion_strings(['Belo Horizonte', u'So Carlos', u'So Paulo', u'Bstad', u'rnskldsvik', 'sanca', 'sampa']) win = gtk.Window() win.connect('delete-event', gtk.main_quit) win.add(entry) win.show_all() gtk.main()
Extend example to include non-ASCII characters
Extend example to include non-ASCII characters
Python
lgpl-2.1
stoq/kiwi
import gtk from kiwi.ui.widgets.entry import Entry entry = Entry() entry.set_completion_strings(['apa', 'apapa', 'apbla', 'apppa', 'aaspa']) win = gtk.Window() win.connect('delete-event', gtk.main_quit) win.add(entry) win.show_all() gtk.main() Extend example to include non-ASCII characters
# encoding: iso-8859-1 import gtk from kiwi.ui.widgets.entry import Entry def on_entry_activate(entry): print 'You selected:', entry.get_text().encode('latin1') gtk.main_quit() entry = Entry() entry.connect('activate', on_entry_activate) entry.set_completion_strings(['Belo Horizonte', u'So Carlos', u'So Paulo', u'Bstad', u'rnskldsvik', 'sanca', 'sampa']) win = gtk.Window() win.connect('delete-event', gtk.main_quit) win.add(entry) win.show_all() gtk.main()
<commit_before>import gtk from kiwi.ui.widgets.entry import Entry entry = Entry() entry.set_completion_strings(['apa', 'apapa', 'apbla', 'apppa', 'aaspa']) win = gtk.Window() win.connect('delete-event', gtk.main_quit) win.add(entry) win.show_all() gtk.main() <commit_msg>Extend example to include non-ASCII characters<commit_after>
# encoding: iso-8859-1 import gtk from kiwi.ui.widgets.entry import Entry def on_entry_activate(entry): print 'You selected:', entry.get_text().encode('latin1') gtk.main_quit() entry = Entry() entry.connect('activate', on_entry_activate) entry.set_completion_strings(['Belo Horizonte', u'So Carlos', u'So Paulo', u'Bstad', u'rnskldsvik', 'sanca', 'sampa']) win = gtk.Window() win.connect('delete-event', gtk.main_quit) win.add(entry) win.show_all() gtk.main()
import gtk from kiwi.ui.widgets.entry import Entry entry = Entry() entry.set_completion_strings(['apa', 'apapa', 'apbla', 'apppa', 'aaspa']) win = gtk.Window() win.connect('delete-event', gtk.main_quit) win.add(entry) win.show_all() gtk.main() Extend example to include non-ASCII characters# encoding: iso-8859-1 import gtk from kiwi.ui.widgets.entry import Entry def on_entry_activate(entry): print 'You selected:', entry.get_text().encode('latin1') gtk.main_quit() entry = Entry() entry.connect('activate', on_entry_activate) entry.set_completion_strings(['Belo Horizonte', u'So Carlos', u'So Paulo', u'Bstad', u'rnskldsvik', 'sanca', 'sampa']) win = gtk.Window() win.connect('delete-event', gtk.main_quit) win.add(entry) win.show_all() gtk.main()
<commit_before>import gtk from kiwi.ui.widgets.entry import Entry entry = Entry() entry.set_completion_strings(['apa', 'apapa', 'apbla', 'apppa', 'aaspa']) win = gtk.Window() win.connect('delete-event', gtk.main_quit) win.add(entry) win.show_all() gtk.main() <commit_msg>Extend example to include non-ASCII characters<commit_after># encoding: iso-8859-1 import gtk from kiwi.ui.widgets.entry import Entry def on_entry_activate(entry): print 'You selected:', entry.get_text().encode('latin1') gtk.main_quit() entry = Entry() entry.connect('activate', on_entry_activate) entry.set_completion_strings(['Belo Horizonte', u'So Carlos', u'So Paulo', u'Bstad', u'rnskldsvik', 'sanca', 'sampa']) win = gtk.Window() win.connect('delete-event', gtk.main_quit) win.add(entry) win.show_all() gtk.main()
c55b587667887732f7b64b6dcf3a8c806c1c85c0
esp32/modules/tasks/badgeeventreminder.py
esp32/modules/tasks/badgeeventreminder.py
# File: badgeeventreminder.py # Version: 1 # Description: Easter egg # License: MIT # Authors: Renze Nicolai <renze@rnplus.nl> import virtualtimers, time, appglue, badge # Tue Aug 8 13:30:00 2017 (CEST) whenToTrigger = 1502191800 - 600 def ber_task(): global whenToTrigger now = time.time() if now>=whenToTrigger: badge.nvs_set_u8('badge','evrt',1) print("BADGE EVENT REMINDER ACTIVATED") appglue.start_app("badge_event_reminder") idleFor = whenToTrigger - now if idleFor<0: idleFor = 0 return idleFor def enable(): if badge.nvs_get_u8('badge','evrt',0)==0: virtualtimers.new(1, ber_task) def disable(): virtualtimers.delete(ber_task)
# File: badgeeventreminder.py # Version: 1 # Description: Easter egg # License: MIT # Authors: Renze Nicolai <renze@rnplus.nl> import virtualtimers, time, appglue, badge # Tue Aug 8 13:30:00 2017 (CEST) whenToTrigger = 1502191800 - 600 def ber_task(): global whenToTrigger now = time.time() if now>=whenToTrigger: badge.nvs_set_u8('badge','evrt',1) print("BADGE EVENT REMINDER ACTIVATED") appglue.start_app("badge_event_reminder") idleFor = whenToTrigger - now if idleFor<0: idleFor = 0 return idleFor * 1000 def enable(): if badge.nvs_get_u8('badge','evrt',0)==0: virtualtimers.new(1, ber_task) def disable(): virtualtimers.delete(ber_task)
Return the number of ms, not seconds.
Return the number of ms, not seconds.
Python
mit
SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32
# File: badgeeventreminder.py # Version: 1 # Description: Easter egg # License: MIT # Authors: Renze Nicolai <renze@rnplus.nl> import virtualtimers, time, appglue, badge # Tue Aug 8 13:30:00 2017 (CEST) whenToTrigger = 1502191800 - 600 def ber_task(): global whenToTrigger now = time.time() if now>=whenToTrigger: badge.nvs_set_u8('badge','evrt',1) print("BADGE EVENT REMINDER ACTIVATED") appglue.start_app("badge_event_reminder") idleFor = whenToTrigger - now if idleFor<0: idleFor = 0 return idleFor def enable(): if badge.nvs_get_u8('badge','evrt',0)==0: virtualtimers.new(1, ber_task) def disable(): virtualtimers.delete(ber_task) Return the number of ms, not seconds.
# File: badgeeventreminder.py # Version: 1 # Description: Easter egg # License: MIT # Authors: Renze Nicolai <renze@rnplus.nl> import virtualtimers, time, appglue, badge # Tue Aug 8 13:30:00 2017 (CEST) whenToTrigger = 1502191800 - 600 def ber_task(): global whenToTrigger now = time.time() if now>=whenToTrigger: badge.nvs_set_u8('badge','evrt',1) print("BADGE EVENT REMINDER ACTIVATED") appglue.start_app("badge_event_reminder") idleFor = whenToTrigger - now if idleFor<0: idleFor = 0 return idleFor * 1000 def enable(): if badge.nvs_get_u8('badge','evrt',0)==0: virtualtimers.new(1, ber_task) def disable(): virtualtimers.delete(ber_task)
<commit_before># File: badgeeventreminder.py # Version: 1 # Description: Easter egg # License: MIT # Authors: Renze Nicolai <renze@rnplus.nl> import virtualtimers, time, appglue, badge # Tue Aug 8 13:30:00 2017 (CEST) whenToTrigger = 1502191800 - 600 def ber_task(): global whenToTrigger now = time.time() if now>=whenToTrigger: badge.nvs_set_u8('badge','evrt',1) print("BADGE EVENT REMINDER ACTIVATED") appglue.start_app("badge_event_reminder") idleFor = whenToTrigger - now if idleFor<0: idleFor = 0 return idleFor def enable(): if badge.nvs_get_u8('badge','evrt',0)==0: virtualtimers.new(1, ber_task) def disable(): virtualtimers.delete(ber_task) <commit_msg>Return the number of ms, not seconds.<commit_after>
# File: badgeeventreminder.py # Version: 1 # Description: Easter egg # License: MIT # Authors: Renze Nicolai <renze@rnplus.nl> import virtualtimers, time, appglue, badge # Tue Aug 8 13:30:00 2017 (CEST) whenToTrigger = 1502191800 - 600 def ber_task(): global whenToTrigger now = time.time() if now>=whenToTrigger: badge.nvs_set_u8('badge','evrt',1) print("BADGE EVENT REMINDER ACTIVATED") appglue.start_app("badge_event_reminder") idleFor = whenToTrigger - now if idleFor<0: idleFor = 0 return idleFor * 1000 def enable(): if badge.nvs_get_u8('badge','evrt',0)==0: virtualtimers.new(1, ber_task) def disable(): virtualtimers.delete(ber_task)
# File: badgeeventreminder.py # Version: 1 # Description: Easter egg # License: MIT # Authors: Renze Nicolai <renze@rnplus.nl> import virtualtimers, time, appglue, badge # Tue Aug 8 13:30:00 2017 (CEST) whenToTrigger = 1502191800 - 600 def ber_task(): global whenToTrigger now = time.time() if now>=whenToTrigger: badge.nvs_set_u8('badge','evrt',1) print("BADGE EVENT REMINDER ACTIVATED") appglue.start_app("badge_event_reminder") idleFor = whenToTrigger - now if idleFor<0: idleFor = 0 return idleFor def enable(): if badge.nvs_get_u8('badge','evrt',0)==0: virtualtimers.new(1, ber_task) def disable(): virtualtimers.delete(ber_task) Return the number of ms, not seconds.# File: badgeeventreminder.py # Version: 1 # Description: Easter egg # License: MIT # Authors: Renze Nicolai <renze@rnplus.nl> import virtualtimers, time, appglue, badge # Tue Aug 8 13:30:00 2017 (CEST) whenToTrigger = 1502191800 - 600 def ber_task(): global whenToTrigger now = time.time() if now>=whenToTrigger: badge.nvs_set_u8('badge','evrt',1) print("BADGE EVENT REMINDER ACTIVATED") appglue.start_app("badge_event_reminder") idleFor = whenToTrigger - now if idleFor<0: idleFor = 0 return idleFor * 1000 def enable(): if badge.nvs_get_u8('badge','evrt',0)==0: virtualtimers.new(1, ber_task) def disable(): virtualtimers.delete(ber_task)
<commit_before># File: badgeeventreminder.py # Version: 1 # Description: Easter egg # License: MIT # Authors: Renze Nicolai <renze@rnplus.nl> import virtualtimers, time, appglue, badge # Tue Aug 8 13:30:00 2017 (CEST) whenToTrigger = 1502191800 - 600 def ber_task(): global whenToTrigger now = time.time() if now>=whenToTrigger: badge.nvs_set_u8('badge','evrt',1) print("BADGE EVENT REMINDER ACTIVATED") appglue.start_app("badge_event_reminder") idleFor = whenToTrigger - now if idleFor<0: idleFor = 0 return idleFor def enable(): if badge.nvs_get_u8('badge','evrt',0)==0: virtualtimers.new(1, ber_task) def disable(): virtualtimers.delete(ber_task) <commit_msg>Return the number of ms, not seconds.<commit_after># File: badgeeventreminder.py # Version: 1 # Description: Easter egg # License: MIT # Authors: Renze Nicolai <renze@rnplus.nl> import virtualtimers, time, appglue, badge # Tue Aug 8 13:30:00 2017 (CEST) whenToTrigger = 1502191800 - 600 def ber_task(): global whenToTrigger now = time.time() if now>=whenToTrigger: badge.nvs_set_u8('badge','evrt',1) print("BADGE EVENT REMINDER ACTIVATED") appglue.start_app("badge_event_reminder") idleFor = whenToTrigger - now if idleFor<0: idleFor = 0 return idleFor * 1000 def enable(): if badge.nvs_get_u8('badge','evrt',0)==0: virtualtimers.new(1, ber_task) def disable(): virtualtimers.delete(ber_task)
5b892de6093de62615e327a805948b76ce806cb4
protoplot-test/test_options_resolving.py
protoplot-test/test_options_resolving.py
import unittest from protoplot.engine.item import Item from protoplot.engine.item_container import ItemContainer class Series(Item): pass Series.options.register("color", True) Series.options.register("lineWidth", False) Series.options.register("lineStyle", False) class TestOptionsResolving(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testOptionsResolving(self): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
import unittest from protoplot.engine.item import Item from protoplot.engine.item_container import ItemContainer # class Series(Item): # pass # # Series.options.register("color", True) # Series.options.register("lineWidth", False) # Series.options.register("lineStyle", False) class TestOptionsResolving(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testOptionsResolving(self): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
Disable code made for old engine model
Disable code made for old engine model
Python
agpl-3.0
deffi/protoplot
import unittest from protoplot.engine.item import Item from protoplot.engine.item_container import ItemContainer class Series(Item): pass Series.options.register("color", True) Series.options.register("lineWidth", False) Series.options.register("lineStyle", False) class TestOptionsResolving(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testOptionsResolving(self): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main() Disable code made for old engine model
import unittest from protoplot.engine.item import Item from protoplot.engine.item_container import ItemContainer # class Series(Item): # pass # # Series.options.register("color", True) # Series.options.register("lineWidth", False) # Series.options.register("lineStyle", False) class TestOptionsResolving(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testOptionsResolving(self): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
<commit_before>import unittest from protoplot.engine.item import Item from protoplot.engine.item_container import ItemContainer class Series(Item): pass Series.options.register("color", True) Series.options.register("lineWidth", False) Series.options.register("lineStyle", False) class TestOptionsResolving(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testOptionsResolving(self): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main() <commit_msg>Disable code made for old engine model<commit_after>
import unittest from protoplot.engine.item import Item from protoplot.engine.item_container import ItemContainer # class Series(Item): # pass # # Series.options.register("color", True) # Series.options.register("lineWidth", False) # Series.options.register("lineStyle", False) class TestOptionsResolving(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testOptionsResolving(self): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
import unittest from protoplot.engine.item import Item from protoplot.engine.item_container import ItemContainer class Series(Item): pass Series.options.register("color", True) Series.options.register("lineWidth", False) Series.options.register("lineStyle", False) class TestOptionsResolving(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testOptionsResolving(self): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main() Disable code made for old engine modelimport unittest from protoplot.engine.item import Item from protoplot.engine.item_container import ItemContainer # class Series(Item): # pass # # Series.options.register("color", True) # Series.options.register("lineWidth", False) # Series.options.register("lineStyle", False) class TestOptionsResolving(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testOptionsResolving(self): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
<commit_before>import unittest from protoplot.engine.item import Item from protoplot.engine.item_container import ItemContainer class Series(Item): pass Series.options.register("color", True) Series.options.register("lineWidth", False) Series.options.register("lineStyle", False) class TestOptionsResolving(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testOptionsResolving(self): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main() <commit_msg>Disable code made for old engine model<commit_after>import unittest from protoplot.engine.item import Item from protoplot.engine.item_container import ItemContainer # class Series(Item): # pass # # Series.options.register("color", True) # Series.options.register("lineWidth", False) # Series.options.register("lineStyle", False) class TestOptionsResolving(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testOptionsResolving(self): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
3a80d6670b32912e091c6f5ca102e33899de117e
terms/managers.py
terms/managers.py
# coding: utf-8 from django.db.models import Manager from django.template.loader import render_to_string import re class TermManager(Manager): def replace_dict(self): t = 'terms/term_replace.html' d = {} for term in self.get_query_set().iterator(): d[term.name] = render_to_string(t, {'term': term}) return d def replace_regexp(self): replace_dict = self.replace_dict() return re.compile('(?P<before>\W)(?P<term>%s)(?P<after>\W)' % '|'.join(map(re.escape, replace_dict)))
# coding: utf-8 from django.db.models import Manager from django.template.loader import render_to_string import re class TermManager(Manager): def replace_dict(self): t = 'terms/term_replace.html' d = {} for term in self.get_query_set().iterator(): d[term.name] = render_to_string(t, {'term': term}) return d def replace_regexp(self): replace_dict = self.replace_dict() return re.compile('(?P<before>^|\W)(?P<term>%s)(?P<after>\W|$)' % '|'.join(map(re.escape, replace_dict)))
Allow replacements in terms at the start and/or end of a text.
Allow replacements in terms at the start and/or end of a text.
Python
bsd-3-clause
philippeowagner/django-terms,BertrandBordage/django-terms,philippeowagner/django-terms,BertrandBordage/django-terms
# coding: utf-8 from django.db.models import Manager from django.template.loader import render_to_string import re class TermManager(Manager): def replace_dict(self): t = 'terms/term_replace.html' d = {} for term in self.get_query_set().iterator(): d[term.name] = render_to_string(t, {'term': term}) return d def replace_regexp(self): replace_dict = self.replace_dict() return re.compile('(?P<before>\W)(?P<term>%s)(?P<after>\W)' % '|'.join(map(re.escape, replace_dict))) Allow replacements in terms at the start and/or end of a text.
# coding: utf-8 from django.db.models import Manager from django.template.loader import render_to_string import re class TermManager(Manager): def replace_dict(self): t = 'terms/term_replace.html' d = {} for term in self.get_query_set().iterator(): d[term.name] = render_to_string(t, {'term': term}) return d def replace_regexp(self): replace_dict = self.replace_dict() return re.compile('(?P<before>^|\W)(?P<term>%s)(?P<after>\W|$)' % '|'.join(map(re.escape, replace_dict)))
<commit_before># coding: utf-8 from django.db.models import Manager from django.template.loader import render_to_string import re class TermManager(Manager): def replace_dict(self): t = 'terms/term_replace.html' d = {} for term in self.get_query_set().iterator(): d[term.name] = render_to_string(t, {'term': term}) return d def replace_regexp(self): replace_dict = self.replace_dict() return re.compile('(?P<before>\W)(?P<term>%s)(?P<after>\W)' % '|'.join(map(re.escape, replace_dict))) <commit_msg>Allow replacements in terms at the start and/or end of a text.<commit_after>
# coding: utf-8 from django.db.models import Manager from django.template.loader import render_to_string import re class TermManager(Manager): def replace_dict(self): t = 'terms/term_replace.html' d = {} for term in self.get_query_set().iterator(): d[term.name] = render_to_string(t, {'term': term}) return d def replace_regexp(self): replace_dict = self.replace_dict() return re.compile('(?P<before>^|\W)(?P<term>%s)(?P<after>\W|$)' % '|'.join(map(re.escape, replace_dict)))
# coding: utf-8 from django.db.models import Manager from django.template.loader import render_to_string import re class TermManager(Manager): def replace_dict(self): t = 'terms/term_replace.html' d = {} for term in self.get_query_set().iterator(): d[term.name] = render_to_string(t, {'term': term}) return d def replace_regexp(self): replace_dict = self.replace_dict() return re.compile('(?P<before>\W)(?P<term>%s)(?P<after>\W)' % '|'.join(map(re.escape, replace_dict))) Allow replacements in terms at the start and/or end of a text.# coding: utf-8 from django.db.models import Manager from django.template.loader import render_to_string import re class TermManager(Manager): def replace_dict(self): t = 'terms/term_replace.html' d = {} for term in self.get_query_set().iterator(): d[term.name] = render_to_string(t, {'term': term}) return d def replace_regexp(self): replace_dict = self.replace_dict() return re.compile('(?P<before>^|\W)(?P<term>%s)(?P<after>\W|$)' % '|'.join(map(re.escape, replace_dict)))
<commit_before># coding: utf-8 from django.db.models import Manager from django.template.loader import render_to_string import re class TermManager(Manager): def replace_dict(self): t = 'terms/term_replace.html' d = {} for term in self.get_query_set().iterator(): d[term.name] = render_to_string(t, {'term': term}) return d def replace_regexp(self): replace_dict = self.replace_dict() return re.compile('(?P<before>\W)(?P<term>%s)(?P<after>\W)' % '|'.join(map(re.escape, replace_dict))) <commit_msg>Allow replacements in terms at the start and/or end of a text.<commit_after># coding: utf-8 from django.db.models import Manager from django.template.loader import render_to_string import re class TermManager(Manager): def replace_dict(self): t = 'terms/term_replace.html' d = {} for term in self.get_query_set().iterator(): d[term.name] = render_to_string(t, {'term': term}) return d def replace_regexp(self): replace_dict = self.replace_dict() return re.compile('(?P<before>^|\W)(?P<term>%s)(?P<after>\W|$)' % '|'.join(map(re.escape, replace_dict)))
5d7a70d2d5e5934d1804d7aac69fd6c79d2ac9a7
src/waldur_core/logging/migrations/0008_drop_sec_group_rules_pulling_events.py
src/waldur_core/logging/migrations/0008_drop_sec_group_rules_pulling_events.py
from django.db import migrations def drop_events(apps, schema_editor): Event = apps.get_model('logging', 'Event') Event.objects.filter(event_type='openstack_security_group_rule_pulled').delete() class Migration(migrations.Migration): dependencies = [ ('logging', '0007_drop_alerts'), ] operations = [migrations.RunPython(drop_events)]
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('logging', '0007_drop_alerts'), ] # Run SQL instead of Run Python is used to avoid OOM error # See also: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.delete operations = [ migrations.RunSQL( "DELETE FROM logging_feed WHERE event_id in (SELECT id from logging_event WHERE event_type='openstack_security_group_rule_pulled')" ), migrations.RunSQL( "DELETE FROM logging_event WHERE event_type='openstack_security_group_rule_pulled'" ), ]
Fix migration script to avoid OOM error.
Fix migration script to avoid OOM error.
Python
mit
opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind
from django.db import migrations def drop_events(apps, schema_editor): Event = apps.get_model('logging', 'Event') Event.objects.filter(event_type='openstack_security_group_rule_pulled').delete() class Migration(migrations.Migration): dependencies = [ ('logging', '0007_drop_alerts'), ] operations = [migrations.RunPython(drop_events)] Fix migration script to avoid OOM error.
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('logging', '0007_drop_alerts'), ] # Run SQL instead of Run Python is used to avoid OOM error # See also: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.delete operations = [ migrations.RunSQL( "DELETE FROM logging_feed WHERE event_id in (SELECT id from logging_event WHERE event_type='openstack_security_group_rule_pulled')" ), migrations.RunSQL( "DELETE FROM logging_event WHERE event_type='openstack_security_group_rule_pulled'" ), ]
<commit_before>from django.db import migrations def drop_events(apps, schema_editor): Event = apps.get_model('logging', 'Event') Event.objects.filter(event_type='openstack_security_group_rule_pulled').delete() class Migration(migrations.Migration): dependencies = [ ('logging', '0007_drop_alerts'), ] operations = [migrations.RunPython(drop_events)] <commit_msg>Fix migration script to avoid OOM error.<commit_after>
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('logging', '0007_drop_alerts'), ] # Run SQL instead of Run Python is used to avoid OOM error # See also: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.delete operations = [ migrations.RunSQL( "DELETE FROM logging_feed WHERE event_id in (SELECT id from logging_event WHERE event_type='openstack_security_group_rule_pulled')" ), migrations.RunSQL( "DELETE FROM logging_event WHERE event_type='openstack_security_group_rule_pulled'" ), ]
from django.db import migrations def drop_events(apps, schema_editor): Event = apps.get_model('logging', 'Event') Event.objects.filter(event_type='openstack_security_group_rule_pulled').delete() class Migration(migrations.Migration): dependencies = [ ('logging', '0007_drop_alerts'), ] operations = [migrations.RunPython(drop_events)] Fix migration script to avoid OOM error.from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('logging', '0007_drop_alerts'), ] # Run SQL instead of Run Python is used to avoid OOM error # See also: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.delete operations = [ migrations.RunSQL( "DELETE FROM logging_feed WHERE event_id in (SELECT id from logging_event WHERE event_type='openstack_security_group_rule_pulled')" ), migrations.RunSQL( "DELETE FROM logging_event WHERE event_type='openstack_security_group_rule_pulled'" ), ]
<commit_before>from django.db import migrations def drop_events(apps, schema_editor): Event = apps.get_model('logging', 'Event') Event.objects.filter(event_type='openstack_security_group_rule_pulled').delete() class Migration(migrations.Migration): dependencies = [ ('logging', '0007_drop_alerts'), ] operations = [migrations.RunPython(drop_events)] <commit_msg>Fix migration script to avoid OOM error.<commit_after>from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('logging', '0007_drop_alerts'), ] # Run SQL instead of Run Python is used to avoid OOM error # See also: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.delete operations = [ migrations.RunSQL( "DELETE FROM logging_feed WHERE event_id in (SELECT id from logging_event WHERE event_type='openstack_security_group_rule_pulled')" ), migrations.RunSQL( "DELETE FROM logging_event WHERE event_type='openstack_security_group_rule_pulled'" ), ]
49e89bee4a7c5e241402766072ae60697c136ca6
guild/__init__.py
guild/__init__.py
import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") if raw else [] def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
Fix to git status info
Fix to git status info
Python
apache-2.0
guildai/guild,guildai/guild,guildai/guild,guildai/guild
import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs() Fix to git status info
import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") if raw else [] def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
<commit_before>import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs() <commit_msg>Fix to git status info<commit_after>
import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") if raw else [] def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs() Fix to git status infoimport os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") if raw else [] def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
<commit_before>import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs() <commit_msg>Fix to git status info<commit_after>import os import subprocess __version__ = "0.1.0-1" def _try_init_git_attrs(): try: _init_git_commit() except (OSError, subprocess.CalledProcessError): pass else: try: _init_git_status() except (OSError, subprocess.CalledProcessError): pass def _init_git_commit(): commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1") globals()["__git_commit__"] = commit def _init_git_status(): raw = _git_cmd("git -C \"%(repo)s\" status -s") globals()["__git_status__"] = raw.split("\n") if raw else [] def _git_cmd(cmd, **kw): repo = os.path.dirname(__file__) cmd = cmd % dict(repo=repo, **kw) return subprocess.check_output(cmd, shell=True).strip() def version(): git_commit = globals().get("__git_commit__") if git_commit: git_status = globals().get("__git_status__", []) workspace_changed_marker = "*" if git_status else "" return "%s (dev %s%s)" % (__version__, git_commit, workspace_changed_marker) else: return __version__ _try_init_git_attrs()
f90467edaf02ae66cdfd01a34f7e03f20073c12d
tests/__init__.py
tests/__init__.py
# tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs from mock import patch yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs') yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json') os.mkdir(yvs.ALFRED_DATA_DIR) def mock_open(path, mode): if path.endswith('preferences.json'): path = yvs.PREFS_PATH return open(path, mode) patch_open = patch('yvs.shared.open', mock_open, create=True) def setup(): patch_open.start() def teardown(): patch_open.stop() shutil.rmtree(yvs.ALFRED_DATA_DIR)
# tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs from mock import patch yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs') yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json') def mock_open(path, mode): if path.endswith('preferences.json'): path = yvs.PREFS_PATH return open(path, mode) patch_open = patch('yvs.shared.open', mock_open, create=True) def setup(): os.mkdir(yvs.ALFRED_DATA_DIR) patch_open.start() def teardown(): patch_open.stop() shutil.rmtree(yvs.ALFRED_DATA_DIR)
Create Alfred data dir on test setup
Create Alfred data dir on test setup
Python
mit
caleb531/youversion-suggest,caleb531/youversion-suggest
# tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs from mock import patch yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs') yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json') os.mkdir(yvs.ALFRED_DATA_DIR) def mock_open(path, mode): if path.endswith('preferences.json'): path = yvs.PREFS_PATH return open(path, mode) patch_open = patch('yvs.shared.open', mock_open, create=True) def setup(): patch_open.start() def teardown(): patch_open.stop() shutil.rmtree(yvs.ALFRED_DATA_DIR) Create Alfred data dir on test setup
# tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs from mock import patch yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs') yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json') def mock_open(path, mode): if path.endswith('preferences.json'): path = yvs.PREFS_PATH return open(path, mode) patch_open = patch('yvs.shared.open', mock_open, create=True) def setup(): os.mkdir(yvs.ALFRED_DATA_DIR) patch_open.start() def teardown(): patch_open.stop() shutil.rmtree(yvs.ALFRED_DATA_DIR)
<commit_before># tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs from mock import patch yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs') yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json') os.mkdir(yvs.ALFRED_DATA_DIR) def mock_open(path, mode): if path.endswith('preferences.json'): path = yvs.PREFS_PATH return open(path, mode) patch_open = patch('yvs.shared.open', mock_open, create=True) def setup(): patch_open.start() def teardown(): patch_open.stop() shutil.rmtree(yvs.ALFRED_DATA_DIR) <commit_msg>Create Alfred data dir on test setup<commit_after>
# tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs from mock import patch yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs') yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json') def mock_open(path, mode): if path.endswith('preferences.json'): path = yvs.PREFS_PATH return open(path, mode) patch_open = patch('yvs.shared.open', mock_open, create=True) def setup(): os.mkdir(yvs.ALFRED_DATA_DIR) patch_open.start() def teardown(): patch_open.stop() shutil.rmtree(yvs.ALFRED_DATA_DIR)
# tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs from mock import patch yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs') yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json') os.mkdir(yvs.ALFRED_DATA_DIR) def mock_open(path, mode): if path.endswith('preferences.json'): path = yvs.PREFS_PATH return open(path, mode) patch_open = patch('yvs.shared.open', mock_open, create=True) def setup(): patch_open.start() def teardown(): patch_open.stop() shutil.rmtree(yvs.ALFRED_DATA_DIR) Create Alfred data dir on test setup# tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs from mock import patch yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs') yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json') def mock_open(path, mode): if path.endswith('preferences.json'): path = yvs.PREFS_PATH return open(path, mode) patch_open = patch('yvs.shared.open', mock_open, create=True) def setup(): os.mkdir(yvs.ALFRED_DATA_DIR) patch_open.start() def teardown(): patch_open.stop() shutil.rmtree(yvs.ALFRED_DATA_DIR)
<commit_before># tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs from mock import patch yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs') yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json') os.mkdir(yvs.ALFRED_DATA_DIR) def mock_open(path, mode): if path.endswith('preferences.json'): path = yvs.PREFS_PATH return open(path, mode) patch_open = patch('yvs.shared.open', mock_open, create=True) def setup(): patch_open.start() def teardown(): patch_open.stop() shutil.rmtree(yvs.ALFRED_DATA_DIR) <commit_msg>Create Alfred data dir on test setup<commit_after># tests.__init__ import os import os.path import shutil import tempfile import yvs.shared as yvs from mock import patch yvs.ALFRED_DATA_DIR = os.path.join(tempfile.gettempdir(), 'yvs') yvs.PREFS_PATH = os.path.join(yvs.ALFRED_DATA_DIR, 'preferences.json') def mock_open(path, mode): if path.endswith('preferences.json'): path = yvs.PREFS_PATH return open(path, mode) patch_open = patch('yvs.shared.open', mock_open, create=True) def setup(): os.mkdir(yvs.ALFRED_DATA_DIR) patch_open.start() def teardown(): patch_open.stop() shutil.rmtree(yvs.ALFRED_DATA_DIR)
587cfa978eb2d2d6708061016836710ca7e3057b
scrapple/utils/exceptions.py
scrapple/utils/exceptions.py
""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re class InvalidType(ValueError): """Exception class for invalid type in arguments.""" pass class InvalidSelector(ValueError): """Exception class for invalid in arguments.""" pass def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise InvalidType("--type has to be 'scraper' or 'crawler'") if args['--selector'] not in ['xpath', 'css']: raise InvalidSelector("--selector has to be 'xpath' or 'css'") if args['generate'] or args['run']: if args['--output_type'] not in ['json', 'csv']: raise Exception("--output_type has to be 'json' or 'csv'") if args['genconfig'] or args['generate'] or args['run']: if projectname_re.search(args['<projectname>']) is not None: raise Exception("<projectname> should consist of letters, digits or _") if int(args['--levels']) < 1: raise Exception("--levels should be greater than, or equal to 1") return
""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re class InvalidType(ValueError): """Exception class for invalid type in arguments.""" pass class InvalidSelector(ValueError): """Exception class for invalid in arguments.""" pass class InvalidOutputType(ValueError): """Exception class for invalid output_type in arguments.""" pass def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise InvalidType("--type has to be 'scraper' or 'crawler'") if args['--selector'] not in ['xpath', 'css']: raise InvalidSelector("--selector has to be 'xpath' or 'css'") if args['generate'] or args['run']: if args['--output_type'] not in ['json', 'csv']: raise InvalidOutputType("--output_type has to be 'json' or 'csv'") if args['genconfig'] or args['generate'] or args['run']: if projectname_re.search(args['<projectname>']) is not None: raise Exception("<projectname> should consist of letters, digits or _") if int(args['--levels']) < 1: raise Exception("--levels should be greater than, or equal to 1") return
Add custom error class 'InvalidOutputType'
Add custom error class 'InvalidOutputType'
Python
mit
AlexMathew/scrapple,AlexMathew/scrapple,scrappleapp/scrapple,scrappleapp/scrapple,AlexMathew/scrapple
""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re class InvalidType(ValueError): """Exception class for invalid type in arguments.""" pass class InvalidSelector(ValueError): """Exception class for invalid in arguments.""" pass def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise InvalidType("--type has to be 'scraper' or 'crawler'") if args['--selector'] not in ['xpath', 'css']: raise InvalidSelector("--selector has to be 'xpath' or 'css'") if args['generate'] or args['run']: if args['--output_type'] not in ['json', 'csv']: raise Exception("--output_type has to be 'json' or 'csv'") if args['genconfig'] or args['generate'] or args['run']: if projectname_re.search(args['<projectname>']) is not None: raise Exception("<projectname> should consist of letters, digits or _") if int(args['--levels']) < 1: raise Exception("--levels should be greater than, or equal to 1") return Add custom error class 'InvalidOutputType'
""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re class InvalidType(ValueError): """Exception class for invalid type in arguments.""" pass class InvalidSelector(ValueError): """Exception class for invalid in arguments.""" pass class InvalidOutputType(ValueError): """Exception class for invalid output_type in arguments.""" pass def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise InvalidType("--type has to be 'scraper' or 'crawler'") if args['--selector'] not in ['xpath', 'css']: raise InvalidSelector("--selector has to be 'xpath' or 'css'") if args['generate'] or args['run']: if args['--output_type'] not in ['json', 'csv']: raise InvalidOutputType("--output_type has to be 'json' or 'csv'") if args['genconfig'] or args['generate'] or args['run']: if projectname_re.search(args['<projectname>']) is not None: raise Exception("<projectname> should consist of letters, digits or _") if int(args['--levels']) < 1: raise Exception("--levels should be greater than, or equal to 1") return
<commit_before>""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re class InvalidType(ValueError): """Exception class for invalid type in arguments.""" pass class InvalidSelector(ValueError): """Exception class for invalid in arguments.""" pass def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise InvalidType("--type has to be 'scraper' or 'crawler'") if args['--selector'] not in ['xpath', 'css']: raise InvalidSelector("--selector has to be 'xpath' or 'css'") if args['generate'] or args['run']: if args['--output_type'] not in ['json', 'csv']: raise Exception("--output_type has to be 'json' or 'csv'") if args['genconfig'] or args['generate'] or args['run']: if projectname_re.search(args['<projectname>']) is not None: raise Exception("<projectname> should consist of letters, digits or _") if int(args['--levels']) < 1: raise Exception("--levels should be greater than, or equal to 1") return <commit_msg>Add custom error class 'InvalidOutputType'<commit_after>
""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re class InvalidType(ValueError): """Exception class for invalid type in arguments.""" pass class InvalidSelector(ValueError): """Exception class for invalid in arguments.""" pass class InvalidOutputType(ValueError): """Exception class for invalid output_type in arguments.""" pass def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise InvalidType("--type has to be 'scraper' or 'crawler'") if args['--selector'] not in ['xpath', 'css']: raise InvalidSelector("--selector has to be 'xpath' or 'css'") if args['generate'] or args['run']: if args['--output_type'] not in ['json', 'csv']: raise InvalidOutputType("--output_type has to be 'json' or 'csv'") if args['genconfig'] or args['generate'] or args['run']: if projectname_re.search(args['<projectname>']) is not None: raise Exception("<projectname> should consist of letters, digits or _") if int(args['--levels']) < 1: raise Exception("--levels should be greater than, or equal to 1") return
""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re class InvalidType(ValueError): """Exception class for invalid type in arguments.""" pass class InvalidSelector(ValueError): """Exception class for invalid in arguments.""" pass def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise InvalidType("--type has to be 'scraper' or 'crawler'") if args['--selector'] not in ['xpath', 'css']: raise InvalidSelector("--selector has to be 'xpath' or 'css'") if args['generate'] or args['run']: if args['--output_type'] not in ['json', 'csv']: raise Exception("--output_type has to be 'json' or 'csv'") if args['genconfig'] or args['generate'] or args['run']: if projectname_re.search(args['<projectname>']) is not None: raise Exception("<projectname> should consist of letters, digits or _") if int(args['--levels']) < 1: raise Exception("--levels should be greater than, or equal to 1") return Add custom error class 'InvalidOutputType'""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re class InvalidType(ValueError): """Exception class for invalid type in arguments.""" pass class InvalidSelector(ValueError): """Exception class for invalid in arguments.""" pass class InvalidOutputType(ValueError): """Exception class for invalid output_type in arguments.""" pass def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise InvalidType("--type has to be 'scraper' or 'crawler'") if args['--selector'] not in ['xpath', 'css']: raise InvalidSelector("--selector has to be 'xpath' or 'css'") if args['generate'] or args['run']: if args['--output_type'] not in ['json', 'csv']: raise InvalidOutputType("--output_type has to be 'json' or 'csv'") if args['genconfig'] or args['generate'] or args['run']: if projectname_re.search(args['<projectname>']) is not None: raise Exception("<projectname> should consist of letters, digits or _") if int(args['--levels']) < 1: raise Exception("--levels should be greater than, or equal to 1") return
<commit_before>""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re class InvalidType(ValueError): """Exception class for invalid type in arguments.""" pass class InvalidSelector(ValueError): """Exception class for invalid in arguments.""" pass def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise InvalidType("--type has to be 'scraper' or 'crawler'") if args['--selector'] not in ['xpath', 'css']: raise InvalidSelector("--selector has to be 'xpath' or 'css'") if args['generate'] or args['run']: if args['--output_type'] not in ['json', 'csv']: raise Exception("--output_type has to be 'json' or 'csv'") if args['genconfig'] or args['generate'] or args['run']: if projectname_re.search(args['<projectname>']) is not None: raise Exception("<projectname> should consist of letters, digits or _") if int(args['--levels']) < 1: raise Exception("--levels should be greater than, or equal to 1") return <commit_msg>Add custom error class 'InvalidOutputType'<commit_after>""" scrapple.utils.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~ Functions related to handling exceptions in the input arguments """ import re class InvalidType(ValueError): """Exception class for invalid type in arguments.""" pass class InvalidSelector(ValueError): """Exception class for invalid in arguments.""" pass class InvalidOutputType(ValueError): """Exception class for invalid output_type in arguments.""" pass def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise InvalidType("--type has to be 'scraper' or 'crawler'") if args['--selector'] not in ['xpath', 'css']: raise InvalidSelector("--selector has to be 'xpath' or 'css'") if args['generate'] or args['run']: if args['--output_type'] not in ['json', 'csv']: raise InvalidOutputType("--output_type has to be 'json' or 'csv'") if args['genconfig'] or args['generate'] or args['run']: if projectname_re.search(args['<projectname>']) is not None: raise Exception("<projectname> should consist of letters, digits or _") if int(args['--levels']) < 1: raise Exception("--levels should be greater than, or equal to 1") return
98e5aa7e5964c827bc58fffde8008bb9795b2238
socorro/cron/jobs/truncate_partitions.py
socorro/cron/jobs/truncate_partitions.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ def run(self, connection): # number of weeks of partitions to keep weeks = 2 cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (weeks,) )
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from configman import Namespace from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ required_config = Namespace() required_config.add_option( 'weeks_to_keep', default=2, doc='Number of weeks of raw crash data to keep in Postgres') def run(self, connection): cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (self.config.weeks_to_keep,) )
Add config option for weeks to truncate and default to 2 weeks
Add config option for weeks to truncate and default to 2 weeks
Python
mpl-2.0
cliqz/socorro,pcabido/socorro,Tchanders/socorro,Serg09/socorro,AdrianGaudebert/socorro,spthaolt/socorro,cliqz/socorro,linearregression/socorro,Serg09/socorro,Tayamarn/socorro,mozilla/socorro,Tayamarn/socorro,lonnen/socorro,twobraids/socorro,m8ttyB/socorro,adngdb/socorro,luser/socorro,adngdb/socorro,AdrianGaudebert/socorro,mozilla/socorro,pcabido/socorro,luser/socorro,yglazko/socorro,m8ttyB/socorro,twobraids/socorro,rhelmer/socorro,Serg09/socorro,cliqz/socorro,Tchanders/socorro,rhelmer/socorro,pcabido/socorro,adngdb/socorro,KaiRo-at/socorro,m8ttyB/socorro,KaiRo-at/socorro,linearregression/socorro,linearregression/socorro,adngdb/socorro,mozilla/socorro,Serg09/socorro,spthaolt/socorro,AdrianGaudebert/socorro,luser/socorro,mozilla/socorro,AdrianGaudebert/socorro,Tayamarn/socorro,Tayamarn/socorro,yglazko/socorro,Tchanders/socorro,rhelmer/socorro,Serg09/socorro,linearregression/socorro,spthaolt/socorro,twobraids/socorro,adngdb/socorro,lonnen/socorro,luser/socorro,mozilla/socorro,KaiRo-at/socorro,lonnen/socorro,Tayamarn/socorro,twobraids/socorro,KaiRo-at/socorro,yglazko/socorro,luser/socorro,cliqz/socorro,Tayamarn/socorro,twobraids/socorro,yglazko/socorro,pcabido/socorro,Tchanders/socorro,mozilla/socorro,spthaolt/socorro,rhelmer/socorro,Tchanders/socorro,cliqz/socorro,rhelmer/socorro,spthaolt/socorro,pcabido/socorro,Serg09/socorro,m8ttyB/socorro,AdrianGaudebert/socorro,twobraids/socorro,rhelmer/socorro,linearregression/socorro,yglazko/socorro,KaiRo-at/socorro,AdrianGaudebert/socorro,linearregression/socorro,m8ttyB/socorro,luser/socorro,m8ttyB/socorro,pcabido/socorro,cliqz/socorro,Tchanders/socorro,KaiRo-at/socorro,spthaolt/socorro,adngdb/socorro,lonnen/socorro,yglazko/socorro
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ def run(self, connection): # number of weeks of partitions to keep weeks = 2 cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (weeks,) ) Add config option for weeks to truncate and default to 2 weeks
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from configman import Namespace from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ required_config = Namespace() required_config.add_option( 'weeks_to_keep', default=2, doc='Number of weeks of raw crash data to keep in Postgres') def run(self, connection): cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (self.config.weeks_to_keep,) )
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ def run(self, connection): # number of weeks of partitions to keep weeks = 2 cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (weeks,) ) <commit_msg>Add config option for weeks to truncate and default to 2 weeks<commit_after>
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from configman import Namespace from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ required_config = Namespace() required_config.add_option( 'weeks_to_keep', default=2, doc='Number of weeks of raw crash data to keep in Postgres') def run(self, connection): cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (self.config.weeks_to_keep,) )
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ def run(self, connection): # number of weeks of partitions to keep weeks = 2 cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (weeks,) ) Add config option for weeks to truncate and default to 2 weeks# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from configman import Namespace from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ required_config = Namespace() required_config.add_option( 'weeks_to_keep', default=2, doc='Number of weeks of raw crash data to keep in Postgres') def run(self, connection): cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (self.config.weeks_to_keep,) )
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ def run(self, connection): # number of weeks of partitions to keep weeks = 2 cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (weeks,) ) <commit_msg>Add config option for weeks to truncate and default to 2 weeks<commit_after># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from configman import Namespace from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ required_config = Namespace() required_config.add_option( 'weeks_to_keep', default=2, doc='Number of weeks of raw crash data to keep in Postgres') def run(self, connection): cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (self.config.weeks_to_keep,) )
cefbcda91d6f9d5a0fce97c7b72844f8dcb8d8cf
tests/conftest.py
tests/conftest.py
import pytest from .fixtures import * def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_runtest_setup(item): if "slow" in item.keywords and not item.config.getoption("--runslow"): pytest.skip("need --runslow option to run")
import pytest import os.path from functools import lru_cache from django.conf import settings from .fixtures import * def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_runtest_setup(item): if "slow" in item.keywords and not item.config.getoption("--runslow"): pytest.skip("need --runslow option to run") @lru_cache(maxsize=4) def _get_sql(): path = os.path.join(settings.BASE_DIR, "sql", "tags.sql") with open(path, "r") as f: return f.read() def on_db_connect(sender, connection, **kwargs): cursor = connection.cursor() cursor.execute(_get_sql()) from django.db.backends import signals signals.connection_created.connect(on_db_connect)
Load tags sql on connection is created on tests.
Load tags sql on connection is created on tests.
Python
agpl-3.0
seanchen/taiga-back,obimod/taiga-back,frt-arch/taiga-back,CoolCloud/taiga-back,EvgeneOskin/taiga-back,rajiteh/taiga-back,bdang2012/taiga-back-casting,dayatz/taiga-back,astronaut1712/taiga-back,gauravjns/taiga-back,dayatz/taiga-back,forging2012/taiga-back,bdang2012/taiga-back-casting,dycodedev/taiga-back,taigaio/taiga-back,crr0004/taiga-back,xdevelsistemas/taiga-back-community,coopsource/taiga-back,WALR/taiga-back,jeffdwyatt/taiga-back,Tigerwhit4/taiga-back,CoolCloud/taiga-back,obimod/taiga-back,astagi/taiga-back,WALR/taiga-back,astagi/taiga-back,rajiteh/taiga-back,Tigerwhit4/taiga-back,joshisa/taiga-back,CMLL/taiga-back,jeffdwyatt/taiga-back,taigaio/taiga-back,Zaneh-/bearded-tribble-back,gam-phon/taiga-back,bdang2012/taiga-back-casting,19kestier/taiga-back,dycodedev/taiga-back,Zaneh-/bearded-tribble-back,rajiteh/taiga-back,EvgeneOskin/taiga-back,frt-arch/taiga-back,gam-phon/taiga-back,astagi/taiga-back,coopsource/taiga-back,seanchen/taiga-back,xdevelsistemas/taiga-back-community,gauravjns/taiga-back,astronaut1712/taiga-back,WALR/taiga-back,forging2012/taiga-back,19kestier/taiga-back,obimod/taiga-back,CMLL/taiga-back,astronaut1712/taiga-back,obimod/taiga-back,gam-phon/taiga-back,dycodedev/taiga-back,Rademade/taiga-back,gauravjns/taiga-back,coopsource/taiga-back,CMLL/taiga-back,forging2012/taiga-back,astronaut1712/taiga-back,19kestier/taiga-back,dayatz/taiga-back,CoolCloud/taiga-back,jeffdwyatt/taiga-back,seanchen/taiga-back,Rademade/taiga-back,crr0004/taiga-back,xdevelsistemas/taiga-back-community,coopsource/taiga-back,Tigerwhit4/taiga-back,crr0004/taiga-back,CoolCloud/taiga-back,EvgeneOskin/taiga-back,WALR/taiga-back,frt-arch/taiga-back,astagi/taiga-back,EvgeneOskin/taiga-back,Rademade/taiga-back,crr0004/taiga-back,joshisa/taiga-back,rajiteh/taiga-back,Rademade/taiga-back,joshisa/taiga-back,jeffdwyatt/taiga-back,seanchen/taiga-back,forging2012/taiga-back,Tigerwhit4/taiga-back,dycodedev/taiga-back,gauravjns/taiga-back,joshisa/taiga-back,bdang2012/taiga-back-casting,gam-phon/taiga-back,CMLL/taiga-back,taigaio/taiga-back,Zaneh-/bearded-tribble-back,Rademade/taiga-back
import pytest from .fixtures import * def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_runtest_setup(item): if "slow" in item.keywords and not item.config.getoption("--runslow"): pytest.skip("need --runslow option to run") Load tags sql on connection is created on tests.
import pytest import os.path from functools import lru_cache from django.conf import settings from .fixtures import * def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_runtest_setup(item): if "slow" in item.keywords and not item.config.getoption("--runslow"): pytest.skip("need --runslow option to run") @lru_cache(maxsize=4) def _get_sql(): path = os.path.join(settings.BASE_DIR, "sql", "tags.sql") with open(path, "r") as f: return f.read() def on_db_connect(sender, connection, **kwargs): cursor = connection.cursor() cursor.execute(_get_sql()) from django.db.backends import signals signals.connection_created.connect(on_db_connect)
<commit_before>import pytest from .fixtures import * def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_runtest_setup(item): if "slow" in item.keywords and not item.config.getoption("--runslow"): pytest.skip("need --runslow option to run") <commit_msg>Load tags sql on connection is created on tests.<commit_after>
import pytest import os.path from functools import lru_cache from django.conf import settings from .fixtures import * def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_runtest_setup(item): if "slow" in item.keywords and not item.config.getoption("--runslow"): pytest.skip("need --runslow option to run") @lru_cache(maxsize=4) def _get_sql(): path = os.path.join(settings.BASE_DIR, "sql", "tags.sql") with open(path, "r") as f: return f.read() def on_db_connect(sender, connection, **kwargs): cursor = connection.cursor() cursor.execute(_get_sql()) from django.db.backends import signals signals.connection_created.connect(on_db_connect)
import pytest from .fixtures import * def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_runtest_setup(item): if "slow" in item.keywords and not item.config.getoption("--runslow"): pytest.skip("need --runslow option to run") Load tags sql on connection is created on tests.import pytest import os.path from functools import lru_cache from django.conf import settings from .fixtures import * def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_runtest_setup(item): if "slow" in item.keywords and not item.config.getoption("--runslow"): pytest.skip("need --runslow option to run") @lru_cache(maxsize=4) def _get_sql(): path = os.path.join(settings.BASE_DIR, "sql", "tags.sql") with open(path, "r") as f: return f.read() def on_db_connect(sender, connection, **kwargs): cursor = connection.cursor() cursor.execute(_get_sql()) from django.db.backends import signals signals.connection_created.connect(on_db_connect)
<commit_before>import pytest from .fixtures import * def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_runtest_setup(item): if "slow" in item.keywords and not item.config.getoption("--runslow"): pytest.skip("need --runslow option to run") <commit_msg>Load tags sql on connection is created on tests.<commit_after>import pytest import os.path from functools import lru_cache from django.conf import settings from .fixtures import * def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_runtest_setup(item): if "slow" in item.keywords and not item.config.getoption("--runslow"): pytest.skip("need --runslow option to run") @lru_cache(maxsize=4) def _get_sql(): path = os.path.join(settings.BASE_DIR, "sql", "tags.sql") with open(path, "r") as f: return f.read() def on_db_connect(sender, connection, **kwargs): cursor = connection.cursor() cursor.execute(_get_sql()) from django.db.backends import signals signals.connection_created.connect(on_db_connect)
9cbc1b41506b54b7cc60278907c8d9346bfc0b25
app/main/views/feedback.py
app/main/views/feedback.py
import requests from werkzeug.exceptions import ServiceUnavailable from werkzeug.datastructures import MultiDict from werkzeug.urls import url_parse from flask import current_app, request, redirect, flash, Markup from .. import main @main.route('/feedback', methods=["POST"]) def send_feedback(): feedback_config = current_app.config['DM_FEEDBACK_FORM'] form_data = MultiDict() for field, google_form_field in feedback_config['fields'].items(): form_data.setlist(google_form_field, request.form.getlist(field)) result = requests.post(feedback_config['uri'], list(form_data.iteritems(multi=True))) if result.status_code != 200: raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code)) came_from = url_parse(request.form['uri']) # strip netloc and scheme as we should ignore attempts to make us redirect elsewhere replaced = came_from._replace(scheme='', netloc='') flash(Markup( """Thank you for your message. If you have more extensive feedback, please <a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or <a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>. """)) return redirect(replaced, code=303)
import requests from werkzeug.exceptions import ServiceUnavailable from werkzeug.datastructures import MultiDict from werkzeug.urls import url_parse from flask import current_app, request, redirect, flash, Markup from .. import main @main.route('/feedback', methods=["POST"]) def send_feedback(): feedback_config = current_app.config['DM_FEEDBACK_FORM'] form_data = MultiDict() for field, google_form_field in feedback_config['fields'].items(): form_data.setlist(google_form_field, request.form.getlist(field)) result = requests.post(feedback_config['uri'], list(form_data.items(multi=True))) if result.status_code != 200: raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code)) came_from = url_parse(request.form['uri']) # strip netloc and scheme as we should ignore attempts to make us redirect elsewhere replaced = came_from._replace(scheme='', netloc='') flash(Markup( """Thank you for your message. If you have more extensive feedback, please <a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or <a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>. """)) return redirect(replaced, code=303)
Fix broken submission on Python 3.
Fix broken submission on Python 3. - this breaks Python 2, but we don't care any more. https://trello.com/c/Uak7y047/8-feedback-forms
Python
mit
alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend
import requests from werkzeug.exceptions import ServiceUnavailable from werkzeug.datastructures import MultiDict from werkzeug.urls import url_parse from flask import current_app, request, redirect, flash, Markup from .. import main @main.route('/feedback', methods=["POST"]) def send_feedback(): feedback_config = current_app.config['DM_FEEDBACK_FORM'] form_data = MultiDict() for field, google_form_field in feedback_config['fields'].items(): form_data.setlist(google_form_field, request.form.getlist(field)) result = requests.post(feedback_config['uri'], list(form_data.iteritems(multi=True))) if result.status_code != 200: raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code)) came_from = url_parse(request.form['uri']) # strip netloc and scheme as we should ignore attempts to make us redirect elsewhere replaced = came_from._replace(scheme='', netloc='') flash(Markup( """Thank you for your message. If you have more extensive feedback, please <a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or <a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>. """)) return redirect(replaced, code=303) Fix broken submission on Python 3. - this breaks Python 2, but we don't care any more. https://trello.com/c/Uak7y047/8-feedback-forms
import requests from werkzeug.exceptions import ServiceUnavailable from werkzeug.datastructures import MultiDict from werkzeug.urls import url_parse from flask import current_app, request, redirect, flash, Markup from .. import main @main.route('/feedback', methods=["POST"]) def send_feedback(): feedback_config = current_app.config['DM_FEEDBACK_FORM'] form_data = MultiDict() for field, google_form_field in feedback_config['fields'].items(): form_data.setlist(google_form_field, request.form.getlist(field)) result = requests.post(feedback_config['uri'], list(form_data.items(multi=True))) if result.status_code != 200: raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code)) came_from = url_parse(request.form['uri']) # strip netloc and scheme as we should ignore attempts to make us redirect elsewhere replaced = came_from._replace(scheme='', netloc='') flash(Markup( """Thank you for your message. If you have more extensive feedback, please <a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or <a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>. """)) return redirect(replaced, code=303)
<commit_before>import requests from werkzeug.exceptions import ServiceUnavailable from werkzeug.datastructures import MultiDict from werkzeug.urls import url_parse from flask import current_app, request, redirect, flash, Markup from .. import main @main.route('/feedback', methods=["POST"]) def send_feedback(): feedback_config = current_app.config['DM_FEEDBACK_FORM'] form_data = MultiDict() for field, google_form_field in feedback_config['fields'].items(): form_data.setlist(google_form_field, request.form.getlist(field)) result = requests.post(feedback_config['uri'], list(form_data.iteritems(multi=True))) if result.status_code != 200: raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code)) came_from = url_parse(request.form['uri']) # strip netloc and scheme as we should ignore attempts to make us redirect elsewhere replaced = came_from._replace(scheme='', netloc='') flash(Markup( """Thank you for your message. If you have more extensive feedback, please <a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or <a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>. """)) return redirect(replaced, code=303) <commit_msg>Fix broken submission on Python 3. - this breaks Python 2, but we don't care any more. https://trello.com/c/Uak7y047/8-feedback-forms<commit_after>
import requests from werkzeug.exceptions import ServiceUnavailable from werkzeug.datastructures import MultiDict from werkzeug.urls import url_parse from flask import current_app, request, redirect, flash, Markup from .. import main @main.route('/feedback', methods=["POST"]) def send_feedback(): feedback_config = current_app.config['DM_FEEDBACK_FORM'] form_data = MultiDict() for field, google_form_field in feedback_config['fields'].items(): form_data.setlist(google_form_field, request.form.getlist(field)) result = requests.post(feedback_config['uri'], list(form_data.items(multi=True))) if result.status_code != 200: raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code)) came_from = url_parse(request.form['uri']) # strip netloc and scheme as we should ignore attempts to make us redirect elsewhere replaced = came_from._replace(scheme='', netloc='') flash(Markup( """Thank you for your message. If you have more extensive feedback, please <a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or <a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>. """)) return redirect(replaced, code=303)
import requests from werkzeug.exceptions import ServiceUnavailable from werkzeug.datastructures import MultiDict from werkzeug.urls import url_parse from flask import current_app, request, redirect, flash, Markup from .. import main @main.route('/feedback', methods=["POST"]) def send_feedback(): feedback_config = current_app.config['DM_FEEDBACK_FORM'] form_data = MultiDict() for field, google_form_field in feedback_config['fields'].items(): form_data.setlist(google_form_field, request.form.getlist(field)) result = requests.post(feedback_config['uri'], list(form_data.iteritems(multi=True))) if result.status_code != 200: raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code)) came_from = url_parse(request.form['uri']) # strip netloc and scheme as we should ignore attempts to make us redirect elsewhere replaced = came_from._replace(scheme='', netloc='') flash(Markup( """Thank you for your message. If you have more extensive feedback, please <a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or <a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>. """)) return redirect(replaced, code=303) Fix broken submission on Python 3. - this breaks Python 2, but we don't care any more. https://trello.com/c/Uak7y047/8-feedback-formsimport requests from werkzeug.exceptions import ServiceUnavailable from werkzeug.datastructures import MultiDict from werkzeug.urls import url_parse from flask import current_app, request, redirect, flash, Markup from .. import main @main.route('/feedback', methods=["POST"]) def send_feedback(): feedback_config = current_app.config['DM_FEEDBACK_FORM'] form_data = MultiDict() for field, google_form_field in feedback_config['fields'].items(): form_data.setlist(google_form_field, request.form.getlist(field)) result = requests.post(feedback_config['uri'], list(form_data.items(multi=True))) if result.status_code != 200: raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code)) came_from = url_parse(request.form['uri']) # strip netloc and scheme as we should ignore attempts to make us redirect elsewhere replaced = came_from._replace(scheme='', netloc='') flash(Markup( """Thank you for your message. If you have more extensive feedback, please <a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or <a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>. """)) return redirect(replaced, code=303)
<commit_before>import requests from werkzeug.exceptions import ServiceUnavailable from werkzeug.datastructures import MultiDict from werkzeug.urls import url_parse from flask import current_app, request, redirect, flash, Markup from .. import main @main.route('/feedback', methods=["POST"]) def send_feedback(): feedback_config = current_app.config['DM_FEEDBACK_FORM'] form_data = MultiDict() for field, google_form_field in feedback_config['fields'].items(): form_data.setlist(google_form_field, request.form.getlist(field)) result = requests.post(feedback_config['uri'], list(form_data.iteritems(multi=True))) if result.status_code != 200: raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code)) came_from = url_parse(request.form['uri']) # strip netloc and scheme as we should ignore attempts to make us redirect elsewhere replaced = came_from._replace(scheme='', netloc='') flash(Markup( """Thank you for your message. If you have more extensive feedback, please <a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or <a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>. """)) return redirect(replaced, code=303) <commit_msg>Fix broken submission on Python 3. - this breaks Python 2, but we don't care any more. https://trello.com/c/Uak7y047/8-feedback-forms<commit_after>import requests from werkzeug.exceptions import ServiceUnavailable from werkzeug.datastructures import MultiDict from werkzeug.urls import url_parse from flask import current_app, request, redirect, flash, Markup from .. import main @main.route('/feedback', methods=["POST"]) def send_feedback(): feedback_config = current_app.config['DM_FEEDBACK_FORM'] form_data = MultiDict() for field, google_form_field in feedback_config['fields'].items(): form_data.setlist(google_form_field, request.form.getlist(field)) result = requests.post(feedback_config['uri'], list(form_data.items(multi=True))) if result.status_code != 200: raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code)) came_from = url_parse(request.form['uri']) # strip netloc and scheme as we should ignore attempts to make us redirect elsewhere replaced = came_from._replace(scheme='', netloc='') flash(Markup( """Thank you for your message. If you have more extensive feedback, please <a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or <a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>. """)) return redirect(replaced, code=303)
5fd879dbd5278d54a6659eb060f959af36556e1e
tests/test_usb.py
tests/test_usb.py
import unittest from openxc.sources import UsbDataSource, DataSourceError class UsbDataSourceTests(unittest.TestCase): def setUp(self): super(UsbDataSourceTests, self).setUp() def test_create(self): def callback(message): pass try: UsbDataSource(callback) except DataSourceError as e: pass
import unittest from openxc.sources import UsbDataSource, DataSourceError class UsbDataSourceTests(unittest.TestCase): def setUp(self): super(UsbDataSourceTests, self).setUp() def test_create(self): def callback(message): pass
Disable trivial USB test case to get suite running on CI.
Disable trivial USB test case to get suite running on CI.
Python
bsd-3-clause
openxc/openxc-python,openxc/openxc-python,openxc/openxc-python
import unittest from openxc.sources import UsbDataSource, DataSourceError class UsbDataSourceTests(unittest.TestCase): def setUp(self): super(UsbDataSourceTests, self).setUp() def test_create(self): def callback(message): pass try: UsbDataSource(callback) except DataSourceError as e: pass Disable trivial USB test case to get suite running on CI.
import unittest from openxc.sources import UsbDataSource, DataSourceError class UsbDataSourceTests(unittest.TestCase): def setUp(self): super(UsbDataSourceTests, self).setUp() def test_create(self): def callback(message): pass
<commit_before>import unittest from openxc.sources import UsbDataSource, DataSourceError class UsbDataSourceTests(unittest.TestCase): def setUp(self): super(UsbDataSourceTests, self).setUp() def test_create(self): def callback(message): pass try: UsbDataSource(callback) except DataSourceError as e: pass <commit_msg>Disable trivial USB test case to get suite running on CI.<commit_after>
import unittest from openxc.sources import UsbDataSource, DataSourceError class UsbDataSourceTests(unittest.TestCase): def setUp(self): super(UsbDataSourceTests, self).setUp() def test_create(self): def callback(message): pass
import unittest from openxc.sources import UsbDataSource, DataSourceError class UsbDataSourceTests(unittest.TestCase): def setUp(self): super(UsbDataSourceTests, self).setUp() def test_create(self): def callback(message): pass try: UsbDataSource(callback) except DataSourceError as e: pass Disable trivial USB test case to get suite running on CI.import unittest from openxc.sources import UsbDataSource, DataSourceError class UsbDataSourceTests(unittest.TestCase): def setUp(self): super(UsbDataSourceTests, self).setUp() def test_create(self): def callback(message): pass
<commit_before>import unittest from openxc.sources import UsbDataSource, DataSourceError class UsbDataSourceTests(unittest.TestCase): def setUp(self): super(UsbDataSourceTests, self).setUp() def test_create(self): def callback(message): pass try: UsbDataSource(callback) except DataSourceError as e: pass <commit_msg>Disable trivial USB test case to get suite running on CI.<commit_after>import unittest from openxc.sources import UsbDataSource, DataSourceError class UsbDataSourceTests(unittest.TestCase): def setUp(self): super(UsbDataSourceTests, self).setUp() def test_create(self): def callback(message): pass
555d557b71792c94a605b64c2da45eb4902e406d
lib/rpnpy/__init__.py
lib/rpnpy/__init__.py
import sys import ctypes as _ct if sys.version_info < (3,): integer_types = (int, long,) range = xrange else: integer_types = (int,) long = int # xrange = range C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii')) C_WCHAR2CHAR.__doc__ = 'Convert str to bytes' C_CHAR2WCHAR = lambda x: str(x.decode('ascii')) C_CHAR2WCHAR.__doc__ = 'Convert bytes to str' C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x)) C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
import sys import ctypes as _ct if sys.version_info < (3,): integer_types = (int, long,) range = xrange else: integer_types = (int,) long = int range = range C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii')) C_WCHAR2CHAR.__doc__ = 'Convert str to bytes' C_CHAR2WCHAR = lambda x: str(x.decode('ascii')) C_CHAR2WCHAR.__doc__ = 'Convert bytes to str' C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x)) C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
Add missing rpnpy.range reference for Python 3.
Add missing rpnpy.range reference for Python 3. Signed-off-by: Stephane_Chamberland <1054841519c328088796c1f3c72c14f95c4efe35@science.gc.ca> (cherry picked from commit 23860277c006d9635dedcaaa5e065c7aad199d8c) (cherry picked from commit b613c799afbf95e15f99cee50c2f76516a264f32)
Python
lgpl-2.1
meteokid/python-rpn,meteokid/python-rpn,meteokid/python-rpn,meteokid/python-rpn
import sys import ctypes as _ct if sys.version_info < (3,): integer_types = (int, long,) range = xrange else: integer_types = (int,) long = int # xrange = range C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii')) C_WCHAR2CHAR.__doc__ = 'Convert str to bytes' C_CHAR2WCHAR = lambda x: str(x.decode('ascii')) C_CHAR2WCHAR.__doc__ = 'Convert bytes to str' C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x)) C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided' Add missing rpnpy.range reference for Python 3. Signed-off-by: Stephane_Chamberland <1054841519c328088796c1f3c72c14f95c4efe35@science.gc.ca> (cherry picked from commit 23860277c006d9635dedcaaa5e065c7aad199d8c) (cherry picked from commit b613c799afbf95e15f99cee50c2f76516a264f32)
import sys import ctypes as _ct if sys.version_info < (3,): integer_types = (int, long,) range = xrange else: integer_types = (int,) long = int range = range C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii')) C_WCHAR2CHAR.__doc__ = 'Convert str to bytes' C_CHAR2WCHAR = lambda x: str(x.decode('ascii')) C_CHAR2WCHAR.__doc__ = 'Convert bytes to str' C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x)) C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
<commit_before>import sys import ctypes as _ct if sys.version_info < (3,): integer_types = (int, long,) range = xrange else: integer_types = (int,) long = int # xrange = range C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii')) C_WCHAR2CHAR.__doc__ = 'Convert str to bytes' C_CHAR2WCHAR = lambda x: str(x.decode('ascii')) C_CHAR2WCHAR.__doc__ = 'Convert bytes to str' C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x)) C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided' <commit_msg>Add missing rpnpy.range reference for Python 3. Signed-off-by: Stephane_Chamberland <1054841519c328088796c1f3c72c14f95c4efe35@science.gc.ca> (cherry picked from commit 23860277c006d9635dedcaaa5e065c7aad199d8c) (cherry picked from commit b613c799afbf95e15f99cee50c2f76516a264f32)<commit_after>
import sys import ctypes as _ct if sys.version_info < (3,): integer_types = (int, long,) range = xrange else: integer_types = (int,) long = int range = range C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii')) C_WCHAR2CHAR.__doc__ = 'Convert str to bytes' C_CHAR2WCHAR = lambda x: str(x.decode('ascii')) C_CHAR2WCHAR.__doc__ = 'Convert bytes to str' C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x)) C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
import sys import ctypes as _ct if sys.version_info < (3,): integer_types = (int, long,) range = xrange else: integer_types = (int,) long = int # xrange = range C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii')) C_WCHAR2CHAR.__doc__ = 'Convert str to bytes' C_CHAR2WCHAR = lambda x: str(x.decode('ascii')) C_CHAR2WCHAR.__doc__ = 'Convert bytes to str' C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x)) C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided' Add missing rpnpy.range reference for Python 3. Signed-off-by: Stephane_Chamberland <1054841519c328088796c1f3c72c14f95c4efe35@science.gc.ca> (cherry picked from commit 23860277c006d9635dedcaaa5e065c7aad199d8c) (cherry picked from commit b613c799afbf95e15f99cee50c2f76516a264f32)import sys import ctypes as _ct if sys.version_info < (3,): integer_types = (int, long,) range = xrange else: integer_types = (int,) long = int range = range C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii')) C_WCHAR2CHAR.__doc__ = 'Convert str to bytes' C_CHAR2WCHAR = lambda x: str(x.decode('ascii')) C_CHAR2WCHAR.__doc__ = 'Convert bytes to str' C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x)) C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
<commit_before>import sys import ctypes as _ct if sys.version_info < (3,): integer_types = (int, long,) range = xrange else: integer_types = (int,) long = int # xrange = range C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii')) C_WCHAR2CHAR.__doc__ = 'Convert str to bytes' C_CHAR2WCHAR = lambda x: str(x.decode('ascii')) C_CHAR2WCHAR.__doc__ = 'Convert bytes to str' C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x)) C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided' <commit_msg>Add missing rpnpy.range reference for Python 3. Signed-off-by: Stephane_Chamberland <1054841519c328088796c1f3c72c14f95c4efe35@science.gc.ca> (cherry picked from commit 23860277c006d9635dedcaaa5e065c7aad199d8c) (cherry picked from commit b613c799afbf95e15f99cee50c2f76516a264f32)<commit_after>import sys import ctypes as _ct if sys.version_info < (3,): integer_types = (int, long,) range = xrange else: integer_types = (int,) long = int range = range C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii')) C_WCHAR2CHAR.__doc__ = 'Convert str to bytes' C_CHAR2WCHAR = lambda x: str(x.decode('ascii')) C_CHAR2WCHAR.__doc__ = 'Convert bytes to str' C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x)) C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
c191101ff26a9931c8aeb92bc6ff68f7a0baf95a
wordbridge/mappings.py
wordbridge/mappings.py
from wordbridge.html import HtmlBuilder html = HtmlBuilder() def top_level_element(tag_name): return TopLevelElement(tag_name) class TopLevelElement(object): def __init__(self, tag_name): self._tag_name = tag_name def start(self, html_stack): html_stack.open_element(self._tag_name) def end(self, html_stack): html_stack.close_element() def unordered_list(): return UnorderedList() class UnorderedList(object): def start(self, html_stack): current_element = html_stack.current_element() if current_element is None or current_element.tag_name != "ul": html_stack.open_element("ul") html_stack.open_element("li") def end(self, html_stack): html_stack.close_element()
from wordbridge.html import HtmlBuilder html = HtmlBuilder() def top_level_element(tag_name): return Style( on_start=_sequence(_clear_stack, _open_element(tag_name)), on_end=_clear_stack ) def _clear_stack(html_stack): while html_stack.current_element() is not None: html_stack.close_element() def _open_element(tag_name): def apply(html_stack): html_stack.open_element(tag_name) return apply def _sequence(*funcs): def apply(html_stack): for func in funcs: func(html_stack) return apply def unordered_list(): return UnorderedList() class UnorderedList(object): def start(self, html_stack): current_element = html_stack.current_element() if current_element is None or current_element.tag_name != "ul": html_stack.open_element("ul") html_stack.open_element("li") def end(self, html_stack): html_stack.close_element() class Style(object): def __init__(self, on_start, on_end): self._on_start = on_start self._on_end = on_end def start(self, html_stack): return self._on_start(html_stack) def end(self, html_stack): return self._on_end(html_stack)
Build up style from composable functions
Build up style from composable functions
Python
bsd-2-clause
mwilliamson/wordbridge
from wordbridge.html import HtmlBuilder html = HtmlBuilder() def top_level_element(tag_name): return TopLevelElement(tag_name) class TopLevelElement(object): def __init__(self, tag_name): self._tag_name = tag_name def start(self, html_stack): html_stack.open_element(self._tag_name) def end(self, html_stack): html_stack.close_element() def unordered_list(): return UnorderedList() class UnorderedList(object): def start(self, html_stack): current_element = html_stack.current_element() if current_element is None or current_element.tag_name != "ul": html_stack.open_element("ul") html_stack.open_element("li") def end(self, html_stack): html_stack.close_element() Build up style from composable functions
from wordbridge.html import HtmlBuilder html = HtmlBuilder() def top_level_element(tag_name): return Style( on_start=_sequence(_clear_stack, _open_element(tag_name)), on_end=_clear_stack ) def _clear_stack(html_stack): while html_stack.current_element() is not None: html_stack.close_element() def _open_element(tag_name): def apply(html_stack): html_stack.open_element(tag_name) return apply def _sequence(*funcs): def apply(html_stack): for func in funcs: func(html_stack) return apply def unordered_list(): return UnorderedList() class UnorderedList(object): def start(self, html_stack): current_element = html_stack.current_element() if current_element is None or current_element.tag_name != "ul": html_stack.open_element("ul") html_stack.open_element("li") def end(self, html_stack): html_stack.close_element() class Style(object): def __init__(self, on_start, on_end): self._on_start = on_start self._on_end = on_end def start(self, html_stack): return self._on_start(html_stack) def end(self, html_stack): return self._on_end(html_stack)
<commit_before>from wordbridge.html import HtmlBuilder html = HtmlBuilder() def top_level_element(tag_name): return TopLevelElement(tag_name) class TopLevelElement(object): def __init__(self, tag_name): self._tag_name = tag_name def start(self, html_stack): html_stack.open_element(self._tag_name) def end(self, html_stack): html_stack.close_element() def unordered_list(): return UnorderedList() class UnorderedList(object): def start(self, html_stack): current_element = html_stack.current_element() if current_element is None or current_element.tag_name != "ul": html_stack.open_element("ul") html_stack.open_element("li") def end(self, html_stack): html_stack.close_element() <commit_msg>Build up style from composable functions<commit_after>
from wordbridge.html import HtmlBuilder html = HtmlBuilder() def top_level_element(tag_name): return Style( on_start=_sequence(_clear_stack, _open_element(tag_name)), on_end=_clear_stack ) def _clear_stack(html_stack): while html_stack.current_element() is not None: html_stack.close_element() def _open_element(tag_name): def apply(html_stack): html_stack.open_element(tag_name) return apply def _sequence(*funcs): def apply(html_stack): for func in funcs: func(html_stack) return apply def unordered_list(): return UnorderedList() class UnorderedList(object): def start(self, html_stack): current_element = html_stack.current_element() if current_element is None or current_element.tag_name != "ul": html_stack.open_element("ul") html_stack.open_element("li") def end(self, html_stack): html_stack.close_element() class Style(object): def __init__(self, on_start, on_end): self._on_start = on_start self._on_end = on_end def start(self, html_stack): return self._on_start(html_stack) def end(self, html_stack): return self._on_end(html_stack)
from wordbridge.html import HtmlBuilder html = HtmlBuilder() def top_level_element(tag_name): return TopLevelElement(tag_name) class TopLevelElement(object): def __init__(self, tag_name): self._tag_name = tag_name def start(self, html_stack): html_stack.open_element(self._tag_name) def end(self, html_stack): html_stack.close_element() def unordered_list(): return UnorderedList() class UnorderedList(object): def start(self, html_stack): current_element = html_stack.current_element() if current_element is None or current_element.tag_name != "ul": html_stack.open_element("ul") html_stack.open_element("li") def end(self, html_stack): html_stack.close_element() Build up style from composable functionsfrom wordbridge.html import HtmlBuilder html = HtmlBuilder() def top_level_element(tag_name): return Style( on_start=_sequence(_clear_stack, _open_element(tag_name)), on_end=_clear_stack ) def _clear_stack(html_stack): while html_stack.current_element() is not None: html_stack.close_element() def _open_element(tag_name): def apply(html_stack): html_stack.open_element(tag_name) return apply def _sequence(*funcs): def apply(html_stack): for func in funcs: func(html_stack) return apply def unordered_list(): return UnorderedList() class UnorderedList(object): def start(self, html_stack): current_element = html_stack.current_element() if current_element is None or current_element.tag_name != "ul": html_stack.open_element("ul") html_stack.open_element("li") def end(self, html_stack): html_stack.close_element() class Style(object): def __init__(self, on_start, on_end): self._on_start = on_start self._on_end = on_end def start(self, html_stack): return self._on_start(html_stack) def end(self, html_stack): return self._on_end(html_stack)
<commit_before>from wordbridge.html import HtmlBuilder html = HtmlBuilder() def top_level_element(tag_name): return TopLevelElement(tag_name) class TopLevelElement(object): def __init__(self, tag_name): self._tag_name = tag_name def start(self, html_stack): html_stack.open_element(self._tag_name) def end(self, html_stack): html_stack.close_element() def unordered_list(): return UnorderedList() class UnorderedList(object): def start(self, html_stack): current_element = html_stack.current_element() if current_element is None or current_element.tag_name != "ul": html_stack.open_element("ul") html_stack.open_element("li") def end(self, html_stack): html_stack.close_element() <commit_msg>Build up style from composable functions<commit_after>from wordbridge.html import HtmlBuilder html = HtmlBuilder() def top_level_element(tag_name): return Style( on_start=_sequence(_clear_stack, _open_element(tag_name)), on_end=_clear_stack ) def _clear_stack(html_stack): while html_stack.current_element() is not None: html_stack.close_element() def _open_element(tag_name): def apply(html_stack): html_stack.open_element(tag_name) return apply def _sequence(*funcs): def apply(html_stack): for func in funcs: func(html_stack) return apply def unordered_list(): return UnorderedList() class UnorderedList(object): def start(self, html_stack): current_element = html_stack.current_element() if current_element is None or current_element.tag_name != "ul": html_stack.open_element("ul") html_stack.open_element("li") def end(self, html_stack): html_stack.close_element() class Style(object): def __init__(self, on_start, on_end): self._on_start = on_start self._on_end = on_end def start(self, html_stack): return self._on_start(html_stack) def end(self, html_stack): return self._on_end(html_stack)
6c9fa6a8d82a57b51e963c453fece5f445b3a3ba
spicedham/split_tokenizer.py
spicedham/split_tokenizer.py
from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) is_not_blank = lambda x: x != '' text = filter(is_not_blank, text) lower_case = lambda x: x.lower() text = map(lower_case, text) return text
from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) text = [token.lower() for token in text if token] return text
Make mapping & filtering into a list comprehension
Make mapping & filtering into a list comprehension
Python
mpl-2.0
mozilla/spicedham,mozilla/spicedham
from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) is_not_blank = lambda x: x != '' text = filter(is_not_blank, text) lower_case = lambda x: x.lower() text = map(lower_case, text) return text Make mapping & filtering into a list comprehension
from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) text = [token.lower() for token in text if token] return text
<commit_before>from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) is_not_blank = lambda x: x != '' text = filter(is_not_blank, text) lower_case = lambda x: x.lower() text = map(lower_case, text) return text <commit_msg>Make mapping & filtering into a list comprehension<commit_after>
from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) text = [token.lower() for token in text if token] return text
from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) is_not_blank = lambda x: x != '' text = filter(is_not_blank, text) lower_case = lambda x: x.lower() text = map(lower_case, text) return text Make mapping & filtering into a list comprehensionfrom re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) text = [token.lower() for token in text if token] return text
<commit_before>from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) is_not_blank = lambda x: x != '' text = filter(is_not_blank, text) lower_case = lambda x: x.lower() text = map(lower_case, text) return text <commit_msg>Make mapping & filtering into a list comprehension<commit_after>from re import split from spicedham.tokenizer import BaseTokenizer class SplitTokenizer(BaseTokenizer): """ Split the text on punctuation and newlines, lowercase everything, and filter the empty strings """ def tokenize(self, text): text = split('[ ,.?!\n\r]', text) text = [token.lower() for token in text if token] return text
66f467c64a0dbfcbb81d9edc74e506c076aac439
onadata/apps/logger/migrations/0006_add-index-to-instance-uuid_and_xform_uuid.py
onadata/apps/logger/migrations/0006_add-index-to-instance-uuid_and_xform_uuid.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # This custom migration must be run on Postgres 9.5+. # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ]
Remove incorrect remark about Postgres 9.5
Remove incorrect remark about Postgres 9.5
Python
bsd-2-clause
kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # This custom migration must be run on Postgres 9.5+. # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ] Remove incorrect remark about Postgres 9.5
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # This custom migration must be run on Postgres 9.5+. # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ] <commit_msg>Remove incorrect remark about Postgres 9.5<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # This custom migration must be run on Postgres 9.5+. # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ] Remove incorrect remark about Postgres 9.5# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # This custom migration must be run on Postgres 9.5+. # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ] <commit_msg>Remove incorrect remark about Postgres 9.5<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0005_instance_xml_hash'), ] # Because some servers already have these modifications applied by Django South migration, # we need to delete old indexes to let django recreate them according to Django migration requirements. # # see old migration in onadata/apps/logger/south_migrations/0032_index_uuid.py operations = [ migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_xform_uuid_idx;" ), migrations.RunSQL( "DROP INDEX IF EXISTS odk_logger_instance_uuid_idx;" ), migrations.AlterField( model_name='instance', name='uuid', field=models.CharField(default='', max_length=249, db_index=True), ), migrations.AlterField( model_name='xform', name='uuid', field=models.CharField(default='', max_length=32, db_index=True), ), ]
b75751d1c4ec58027173c66a869eac1319a36d7a
src/anypytools/utils/py3k.py
src/anypytools/utils/py3k.py
try: from future_builtins import * except ImportError: pass try: input = raw_input range = xrange except NameError: pass try: string_types = basestring except NameError: string_types = str # This handles pprint always returns string witout ' prefix # important when running doctest in both python 2 og python 2 import pprint as _pprint class MyPrettyPrinter(_pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): try: if isinstance(object, unicode): rep = u"'" + object + u"'" return ( rep.encode('utf8'), True, False) except NameError: pass return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level) def py3k_pprint(s): printer = MyPrettyPrinter(width = 110) printer.pprint(s)
# try: # from future.builtins import * # except ImportError: # pass try: input = raw_input range = xrange except NameError: pass try: string_types = basestring except NameError: string_types = str # This handles pprint always returns string witout ' prefix # important when running doctest in both python 2 og python 2 import pprint as _pprint class MyPrettyPrinter(_pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): try: if isinstance(object, unicode): rep = u"'" + object + u"'" return ( rep.encode('utf8'), True, False) except NameError: pass return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level) def py3k_pprint(s): printer = MyPrettyPrinter(width = 110) printer.pprint(s)
Remove all use of python-future package due to a bug which prevents the IPython notebook interrupt the program
Remove all use of python-future package due to a bug which prevents the IPython notebook interrupt the program
Python
mit
AnyBody-Research-Group/AnyPyTools
try: from future_builtins import * except ImportError: pass try: input = raw_input range = xrange except NameError: pass try: string_types = basestring except NameError: string_types = str # This handles pprint always returns string witout ' prefix # important when running doctest in both python 2 og python 2 import pprint as _pprint class MyPrettyPrinter(_pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): try: if isinstance(object, unicode): rep = u"'" + object + u"'" return ( rep.encode('utf8'), True, False) except NameError: pass return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level) def py3k_pprint(s): printer = MyPrettyPrinter(width = 110) printer.pprint(s) Remove all use of python-future package due to a bug which prevents the IPython notebook interrupt the program
# try: # from future.builtins import * # except ImportError: # pass try: input = raw_input range = xrange except NameError: pass try: string_types = basestring except NameError: string_types = str # This handles pprint always returns string witout ' prefix # important when running doctest in both python 2 og python 2 import pprint as _pprint class MyPrettyPrinter(_pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): try: if isinstance(object, unicode): rep = u"'" + object + u"'" return ( rep.encode('utf8'), True, False) except NameError: pass return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level) def py3k_pprint(s): printer = MyPrettyPrinter(width = 110) printer.pprint(s)
<commit_before>try: from future_builtins import * except ImportError: pass try: input = raw_input range = xrange except NameError: pass try: string_types = basestring except NameError: string_types = str # This handles pprint always returns string witout ' prefix # important when running doctest in both python 2 og python 2 import pprint as _pprint class MyPrettyPrinter(_pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): try: if isinstance(object, unicode): rep = u"'" + object + u"'" return ( rep.encode('utf8'), True, False) except NameError: pass return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level) def py3k_pprint(s): printer = MyPrettyPrinter(width = 110) printer.pprint(s) <commit_msg>Remove all use of python-future package due to a bug which prevents the IPython notebook interrupt the program<commit_after>
# try: # from future.builtins import * # except ImportError: # pass try: input = raw_input range = xrange except NameError: pass try: string_types = basestring except NameError: string_types = str # This handles pprint always returns string witout ' prefix # important when running doctest in both python 2 og python 2 import pprint as _pprint class MyPrettyPrinter(_pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): try: if isinstance(object, unicode): rep = u"'" + object + u"'" return ( rep.encode('utf8'), True, False) except NameError: pass return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level) def py3k_pprint(s): printer = MyPrettyPrinter(width = 110) printer.pprint(s)
try: from future_builtins import * except ImportError: pass try: input = raw_input range = xrange except NameError: pass try: string_types = basestring except NameError: string_types = str # This handles pprint always returns string witout ' prefix # important when running doctest in both python 2 og python 2 import pprint as _pprint class MyPrettyPrinter(_pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): try: if isinstance(object, unicode): rep = u"'" + object + u"'" return ( rep.encode('utf8'), True, False) except NameError: pass return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level) def py3k_pprint(s): printer = MyPrettyPrinter(width = 110) printer.pprint(s) Remove all use of python-future package due to a bug which prevents the IPython notebook interrupt the program# try: # from future.builtins import * # except ImportError: # pass try: input = raw_input range = xrange except NameError: pass try: string_types = basestring except NameError: string_types = str # This handles pprint always returns string witout ' prefix # important when running doctest in both python 2 og python 2 import pprint as _pprint class MyPrettyPrinter(_pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): try: if isinstance(object, unicode): rep = u"'" + object + u"'" return ( rep.encode('utf8'), True, False) except NameError: pass return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level) def py3k_pprint(s): printer = MyPrettyPrinter(width = 110) printer.pprint(s)
<commit_before>try: from future_builtins import * except ImportError: pass try: input = raw_input range = xrange except NameError: pass try: string_types = basestring except NameError: string_types = str # This handles pprint always returns string witout ' prefix # important when running doctest in both python 2 og python 2 import pprint as _pprint class MyPrettyPrinter(_pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): try: if isinstance(object, unicode): rep = u"'" + object + u"'" return ( rep.encode('utf8'), True, False) except NameError: pass return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level) def py3k_pprint(s): printer = MyPrettyPrinter(width = 110) printer.pprint(s) <commit_msg>Remove all use of python-future package due to a bug which prevents the IPython notebook interrupt the program<commit_after># try: # from future.builtins import * # except ImportError: # pass try: input = raw_input range = xrange except NameError: pass try: string_types = basestring except NameError: string_types = str # This handles pprint always returns string witout ' prefix # important when running doctest in both python 2 og python 2 import pprint as _pprint class MyPrettyPrinter(_pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): try: if isinstance(object, unicode): rep = u"'" + object + u"'" return ( rep.encode('utf8'), True, False) except NameError: pass return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level) def py3k_pprint(s): printer = MyPrettyPrinter(width = 110) printer.pprint(s)
ee3b11a7a15535ffe52a6bdd493819fbd76b2300
vroom/graphics.py
vroom/graphics.py
import pygame class Graphic: car_color = (255, 50, 50) car_width = 3 road_color = (255, 255, 255) road_width = 6 draw_methods = { 'Car': 'draw_car', 'Road': 'draw_road', } def __init__(self, surface): self.surface = surface def draw(self, obj): object_class = obj.__class__.__name__ method_name = self.draw_methods.get(object_class, None) if method_name: method = getattr(self, method_name) method(obj) def draw_car(self, car): coord = car.coordinates acceleration_rate = car.acceleration_rate rect = pygame.Rect(coord.x, coord.y, self.car_width, self.car_width) # Change car color depending on acceleration if acceleration_rate > 0: rate = min(1, acceleration_rate) color = (0, 0, int(rate * 255)) else: rate = max(-1, acceleration_rate) color = (int(-rate * 255), 0, 0) pygame.draw.rect(self.surface, color, rect, 0) def draw_road(self, road): pointlist = road.pointlist() closed = False pygame.draw.lines(self.surface, self.road_color, closed, pointlist, self.road_width)
import pygame class Graphic: car_color = (255, 50, 50) car_width = 3 road_color = (255, 255, 255) road_width = 6 draw_methods = { 'Car': 'draw_car', 'Road': 'draw_road', } def __init__(self, surface): self.surface = surface def draw(self, obj): object_class = obj.__class__.__name__ method_name = self.draw_methods.get(object_class, None) if method_name: method = getattr(self, method_name) method(obj) def draw_car(self, car): coord = car.coordinates acceleration_rate = car.acceleration_rate rect = pygame.Rect(coord.x, coord.y, self.car_width, self.car_width) # Change car color depending on acceleration if acceleration_rate > 0: color = (0, 0, 255) else: color = (255, 0, 0) pygame.draw.rect(self.surface, color, rect, 0) def draw_road(self, road): pointlist = road.pointlist() closed = False pygame.draw.lines(self.surface, self.road_color, closed, pointlist, self.road_width)
Make color easier to read
Make color easier to read
Python
mit
thibault/vroom
import pygame class Graphic: car_color = (255, 50, 50) car_width = 3 road_color = (255, 255, 255) road_width = 6 draw_methods = { 'Car': 'draw_car', 'Road': 'draw_road', } def __init__(self, surface): self.surface = surface def draw(self, obj): object_class = obj.__class__.__name__ method_name = self.draw_methods.get(object_class, None) if method_name: method = getattr(self, method_name) method(obj) def draw_car(self, car): coord = car.coordinates acceleration_rate = car.acceleration_rate rect = pygame.Rect(coord.x, coord.y, self.car_width, self.car_width) # Change car color depending on acceleration if acceleration_rate > 0: rate = min(1, acceleration_rate) color = (0, 0, int(rate * 255)) else: rate = max(-1, acceleration_rate) color = (int(-rate * 255), 0, 0) pygame.draw.rect(self.surface, color, rect, 0) def draw_road(self, road): pointlist = road.pointlist() closed = False pygame.draw.lines(self.surface, self.road_color, closed, pointlist, self.road_width) Make color easier to read
import pygame class Graphic: car_color = (255, 50, 50) car_width = 3 road_color = (255, 255, 255) road_width = 6 draw_methods = { 'Car': 'draw_car', 'Road': 'draw_road', } def __init__(self, surface): self.surface = surface def draw(self, obj): object_class = obj.__class__.__name__ method_name = self.draw_methods.get(object_class, None) if method_name: method = getattr(self, method_name) method(obj) def draw_car(self, car): coord = car.coordinates acceleration_rate = car.acceleration_rate rect = pygame.Rect(coord.x, coord.y, self.car_width, self.car_width) # Change car color depending on acceleration if acceleration_rate > 0: color = (0, 0, 255) else: color = (255, 0, 0) pygame.draw.rect(self.surface, color, rect, 0) def draw_road(self, road): pointlist = road.pointlist() closed = False pygame.draw.lines(self.surface, self.road_color, closed, pointlist, self.road_width)
<commit_before>import pygame class Graphic: car_color = (255, 50, 50) car_width = 3 road_color = (255, 255, 255) road_width = 6 draw_methods = { 'Car': 'draw_car', 'Road': 'draw_road', } def __init__(self, surface): self.surface = surface def draw(self, obj): object_class = obj.__class__.__name__ method_name = self.draw_methods.get(object_class, None) if method_name: method = getattr(self, method_name) method(obj) def draw_car(self, car): coord = car.coordinates acceleration_rate = car.acceleration_rate rect = pygame.Rect(coord.x, coord.y, self.car_width, self.car_width) # Change car color depending on acceleration if acceleration_rate > 0: rate = min(1, acceleration_rate) color = (0, 0, int(rate * 255)) else: rate = max(-1, acceleration_rate) color = (int(-rate * 255), 0, 0) pygame.draw.rect(self.surface, color, rect, 0) def draw_road(self, road): pointlist = road.pointlist() closed = False pygame.draw.lines(self.surface, self.road_color, closed, pointlist, self.road_width) <commit_msg>Make color easier to read<commit_after>
import pygame class Graphic: car_color = (255, 50, 50) car_width = 3 road_color = (255, 255, 255) road_width = 6 draw_methods = { 'Car': 'draw_car', 'Road': 'draw_road', } def __init__(self, surface): self.surface = surface def draw(self, obj): object_class = obj.__class__.__name__ method_name = self.draw_methods.get(object_class, None) if method_name: method = getattr(self, method_name) method(obj) def draw_car(self, car): coord = car.coordinates acceleration_rate = car.acceleration_rate rect = pygame.Rect(coord.x, coord.y, self.car_width, self.car_width) # Change car color depending on acceleration if acceleration_rate > 0: color = (0, 0, 255) else: color = (255, 0, 0) pygame.draw.rect(self.surface, color, rect, 0) def draw_road(self, road): pointlist = road.pointlist() closed = False pygame.draw.lines(self.surface, self.road_color, closed, pointlist, self.road_width)
import pygame class Graphic: car_color = (255, 50, 50) car_width = 3 road_color = (255, 255, 255) road_width = 6 draw_methods = { 'Car': 'draw_car', 'Road': 'draw_road', } def __init__(self, surface): self.surface = surface def draw(self, obj): object_class = obj.__class__.__name__ method_name = self.draw_methods.get(object_class, None) if method_name: method = getattr(self, method_name) method(obj) def draw_car(self, car): coord = car.coordinates acceleration_rate = car.acceleration_rate rect = pygame.Rect(coord.x, coord.y, self.car_width, self.car_width) # Change car color depending on acceleration if acceleration_rate > 0: rate = min(1, acceleration_rate) color = (0, 0, int(rate * 255)) else: rate = max(-1, acceleration_rate) color = (int(-rate * 255), 0, 0) pygame.draw.rect(self.surface, color, rect, 0) def draw_road(self, road): pointlist = road.pointlist() closed = False pygame.draw.lines(self.surface, self.road_color, closed, pointlist, self.road_width) Make color easier to readimport pygame class Graphic: car_color = (255, 50, 50) car_width = 3 road_color = (255, 255, 255) road_width = 6 draw_methods = { 'Car': 'draw_car', 'Road': 'draw_road', } def __init__(self, surface): self.surface = surface def draw(self, obj): object_class = obj.__class__.__name__ method_name = self.draw_methods.get(object_class, None) if method_name: method = getattr(self, method_name) method(obj) def draw_car(self, car): coord = car.coordinates acceleration_rate = car.acceleration_rate rect = pygame.Rect(coord.x, coord.y, self.car_width, self.car_width) # Change car color depending on acceleration if acceleration_rate > 0: color = (0, 0, 255) else: color = (255, 0, 0) pygame.draw.rect(self.surface, color, rect, 0) def draw_road(self, road): pointlist = road.pointlist() closed = False pygame.draw.lines(self.surface, self.road_color, closed, pointlist, self.road_width)
<commit_before>import pygame class Graphic: car_color = (255, 50, 50) car_width = 3 road_color = (255, 255, 255) road_width = 6 draw_methods = { 'Car': 'draw_car', 'Road': 'draw_road', } def __init__(self, surface): self.surface = surface def draw(self, obj): object_class = obj.__class__.__name__ method_name = self.draw_methods.get(object_class, None) if method_name: method = getattr(self, method_name) method(obj) def draw_car(self, car): coord = car.coordinates acceleration_rate = car.acceleration_rate rect = pygame.Rect(coord.x, coord.y, self.car_width, self.car_width) # Change car color depending on acceleration if acceleration_rate > 0: rate = min(1, acceleration_rate) color = (0, 0, int(rate * 255)) else: rate = max(-1, acceleration_rate) color = (int(-rate * 255), 0, 0) pygame.draw.rect(self.surface, color, rect, 0) def draw_road(self, road): pointlist = road.pointlist() closed = False pygame.draw.lines(self.surface, self.road_color, closed, pointlist, self.road_width) <commit_msg>Make color easier to read<commit_after>import pygame class Graphic: car_color = (255, 50, 50) car_width = 3 road_color = (255, 255, 255) road_width = 6 draw_methods = { 'Car': 'draw_car', 'Road': 'draw_road', } def __init__(self, surface): self.surface = surface def draw(self, obj): object_class = obj.__class__.__name__ method_name = self.draw_methods.get(object_class, None) if method_name: method = getattr(self, method_name) method(obj) def draw_car(self, car): coord = car.coordinates acceleration_rate = car.acceleration_rate rect = pygame.Rect(coord.x, coord.y, self.car_width, self.car_width) # Change car color depending on acceleration if acceleration_rate > 0: color = (0, 0, 255) else: color = (255, 0, 0) pygame.draw.rect(self.surface, color, rect, 0) def draw_road(self, road): pointlist = road.pointlist() closed = False pygame.draw.lines(self.surface, self.road_color, closed, pointlist, self.road_width)
44ff13234dcc8452d525eb0c648b350243b81ddb
calendarBotModule/setup.py
calendarBotModule/setup.py
#!/usr/bin/env python3 from setuptools import setup, find_packages install_requires = ( 'html2text', 'matterhook', 'exchangelib', ) setup(name='calendarBot', version='0.1', description='Mattermost calendar Bot', long_description=open('README.md').read(), url='https://github.com/mharrend', author='Marco A. Harrendorf', author_email='marco.harrendorf@cern.ch', license='MIT', keywords='chat bot calendar mattermost', platforms=['Any'], packages = find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
#!/usr/bin/env python3 from setuptools import setup, find_packages install_requires = ( 'html2text', 'matterhook', 'exchangelib', ) setup(name='calendarBot', version='0.1.1', description='Mattermost calendar Bot', long_description=open('README.md').read(), url='https://github.com/mharrend', author='Marco A. Harrendorf', author_email='marco.harrendorf@cern.ch', license='MIT', keywords='chat bot calendar mattermost', platforms=['Any'], zip_safe = False, packages = find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Use zip_safe = false to make sure that python module is extracted and later the settingsFile can be changed
Setup.py: Use zip_safe = false to make sure that python module is extracted and later the settingsFile can be changed
Python
mit
mharrend/matterbot-calendarBot,mharrend/matterbot-calendarBot
#!/usr/bin/env python3 from setuptools import setup, find_packages install_requires = ( 'html2text', 'matterhook', 'exchangelib', ) setup(name='calendarBot', version='0.1', description='Mattermost calendar Bot', long_description=open('README.md').read(), url='https://github.com/mharrend', author='Marco A. Harrendorf', author_email='marco.harrendorf@cern.ch', license='MIT', keywords='chat bot calendar mattermost', platforms=['Any'], packages = find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) Setup.py: Use zip_safe = false to make sure that python module is extracted and later the settingsFile can be changed
#!/usr/bin/env python3 from setuptools import setup, find_packages install_requires = ( 'html2text', 'matterhook', 'exchangelib', ) setup(name='calendarBot', version='0.1.1', description='Mattermost calendar Bot', long_description=open('README.md').read(), url='https://github.com/mharrend', author='Marco A. Harrendorf', author_email='marco.harrendorf@cern.ch', license='MIT', keywords='chat bot calendar mattermost', platforms=['Any'], zip_safe = False, packages = find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
<commit_before>#!/usr/bin/env python3 from setuptools import setup, find_packages install_requires = ( 'html2text', 'matterhook', 'exchangelib', ) setup(name='calendarBot', version='0.1', description='Mattermost calendar Bot', long_description=open('README.md').read(), url='https://github.com/mharrend', author='Marco A. Harrendorf', author_email='marco.harrendorf@cern.ch', license='MIT', keywords='chat bot calendar mattermost', platforms=['Any'], packages = find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) <commit_msg>Setup.py: Use zip_safe = false to make sure that python module is extracted and later the settingsFile can be changed<commit_after>
#!/usr/bin/env python3 from setuptools import setup, find_packages install_requires = ( 'html2text', 'matterhook', 'exchangelib', ) setup(name='calendarBot', version='0.1.1', description='Mattermost calendar Bot', long_description=open('README.md').read(), url='https://github.com/mharrend', author='Marco A. Harrendorf', author_email='marco.harrendorf@cern.ch', license='MIT', keywords='chat bot calendar mattermost', platforms=['Any'], zip_safe = False, packages = find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
#!/usr/bin/env python3 from setuptools import setup, find_packages install_requires = ( 'html2text', 'matterhook', 'exchangelib', ) setup(name='calendarBot', version='0.1', description='Mattermost calendar Bot', long_description=open('README.md').read(), url='https://github.com/mharrend', author='Marco A. Harrendorf', author_email='marco.harrendorf@cern.ch', license='MIT', keywords='chat bot calendar mattermost', platforms=['Any'], packages = find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) Setup.py: Use zip_safe = false to make sure that python module is extracted and later the settingsFile can be changed#!/usr/bin/env python3 from setuptools import setup, find_packages install_requires = ( 'html2text', 'matterhook', 'exchangelib', ) setup(name='calendarBot', version='0.1.1', description='Mattermost calendar Bot', long_description=open('README.md').read(), url='https://github.com/mharrend', author='Marco A. Harrendorf', author_email='marco.harrendorf@cern.ch', license='MIT', keywords='chat bot calendar mattermost', platforms=['Any'], zip_safe = False, packages = find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
<commit_before>#!/usr/bin/env python3 from setuptools import setup, find_packages install_requires = ( 'html2text', 'matterhook', 'exchangelib', ) setup(name='calendarBot', version='0.1', description='Mattermost calendar Bot', long_description=open('README.md').read(), url='https://github.com/mharrend', author='Marco A. Harrendorf', author_email='marco.harrendorf@cern.ch', license='MIT', keywords='chat bot calendar mattermost', platforms=['Any'], packages = find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) <commit_msg>Setup.py: Use zip_safe = false to make sure that python module is extracted and later the settingsFile can be changed<commit_after>#!/usr/bin/env python3 from setuptools import setup, find_packages install_requires = ( 'html2text', 'matterhook', 'exchangelib', ) setup(name='calendarBot', version='0.1.1', description='Mattermost calendar Bot', long_description=open('README.md').read(), url='https://github.com/mharrend', author='Marco A. Harrendorf', author_email='marco.harrendorf@cern.ch', license='MIT', keywords='chat bot calendar mattermost', platforms=['Any'], zip_safe = False, packages = find_packages(), install_requires=install_requires, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
27e14d057aad81f4686ed3def25cfffc8156fd4c
scp-slots.py
scp-slots.py
#!/usr/bin/python import re import sys from bs4 import BeautifulSoup from urllib.request import urlopen SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}') def count_slots(url): with urlopen(url) as response: data = response.read() empty_slots = 0 total_slots = 0 scps = set() soup = BeautifulSoup(data, 'html.parser') for link in soup.select('.series a'): href = link.get('href') if href is None or SCP_SERIES_REGEX.match(href) is None: continue if href in scps: continue scps.add(href) total_slots += 1 if link.get('class') == ['newpage']: empty_slots += 1 return empty_slots, total_slots if __name__ == '__main__': if len(sys.argv) > 1: series = int(sys.argv[1]) else: series = 5 url = f'http://www.scp-wiki.net/scp-series-{series}' print(f'Counting slots in {url}...') empty, total = count_slots(url) print(f'{empty} / {total} slots empty ({empty/total*100:.2f}%)')
#!/usr/bin/python import re import sys from bs4 import BeautifulSoup from urllib.request import urlopen SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}') def count_slots(url): with urlopen(url) as response: data = response.read() empty_slots = 0 total_slots = 0 scps = set() soup = BeautifulSoup(data, 'html.parser') for link in soup.select('.series a'): href = link.get('href') if href is None or SCP_SERIES_REGEX.match(href) is None: continue if href in scps: continue scps.add(href) total_slots += 1 if link.get('class') == ['newpage']: empty_slots += 1 return empty_slots, total_slots def get_series_url(number): if number == 1: return 'http://www.scp-wiki.net/scp-series' return f'http://www.scp-wiki.net/scp-series-{series}' if __name__ == '__main__': if len(sys.argv) > 1: series = int(sys.argv[1]) else: series = 5 url = get_series_url(series) print(f'Counting slots in {url}...') empty, total = count_slots(url) print(f'{empty} / {total} slots empty ({empty/total*100:.2f}%)')
Add support for Series I.
Add support for Series I.
Python
mit
ammongit/scripts,ammongit/scripts,ammongit/scripts,ammongit/scripts
#!/usr/bin/python import re import sys from bs4 import BeautifulSoup from urllib.request import urlopen SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}') def count_slots(url): with urlopen(url) as response: data = response.read() empty_slots = 0 total_slots = 0 scps = set() soup = BeautifulSoup(data, 'html.parser') for link in soup.select('.series a'): href = link.get('href') if href is None or SCP_SERIES_REGEX.match(href) is None: continue if href in scps: continue scps.add(href) total_slots += 1 if link.get('class') == ['newpage']: empty_slots += 1 return empty_slots, total_slots if __name__ == '__main__': if len(sys.argv) > 1: series = int(sys.argv[1]) else: series = 5 url = f'http://www.scp-wiki.net/scp-series-{series}' print(f'Counting slots in {url}...') empty, total = count_slots(url) print(f'{empty} / {total} slots empty ({empty/total*100:.2f}%)') Add support for Series I.
#!/usr/bin/python import re import sys from bs4 import BeautifulSoup from urllib.request import urlopen SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}') def count_slots(url): with urlopen(url) as response: data = response.read() empty_slots = 0 total_slots = 0 scps = set() soup = BeautifulSoup(data, 'html.parser') for link in soup.select('.series a'): href = link.get('href') if href is None or SCP_SERIES_REGEX.match(href) is None: continue if href in scps: continue scps.add(href) total_slots += 1 if link.get('class') == ['newpage']: empty_slots += 1 return empty_slots, total_slots def get_series_url(number): if number == 1: return 'http://www.scp-wiki.net/scp-series' return f'http://www.scp-wiki.net/scp-series-{series}' if __name__ == '__main__': if len(sys.argv) > 1: series = int(sys.argv[1]) else: series = 5 url = get_series_url(series) print(f'Counting slots in {url}...') empty, total = count_slots(url) print(f'{empty} / {total} slots empty ({empty/total*100:.2f}%)')
<commit_before>#!/usr/bin/python import re import sys from bs4 import BeautifulSoup from urllib.request import urlopen SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}') def count_slots(url): with urlopen(url) as response: data = response.read() empty_slots = 0 total_slots = 0 scps = set() soup = BeautifulSoup(data, 'html.parser') for link in soup.select('.series a'): href = link.get('href') if href is None or SCP_SERIES_REGEX.match(href) is None: continue if href in scps: continue scps.add(href) total_slots += 1 if link.get('class') == ['newpage']: empty_slots += 1 return empty_slots, total_slots if __name__ == '__main__': if len(sys.argv) > 1: series = int(sys.argv[1]) else: series = 5 url = f'http://www.scp-wiki.net/scp-series-{series}' print(f'Counting slots in {url}...') empty, total = count_slots(url) print(f'{empty} / {total} slots empty ({empty/total*100:.2f}%)') <commit_msg>Add support for Series I.<commit_after>
#!/usr/bin/python import re import sys from bs4 import BeautifulSoup from urllib.request import urlopen SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}') def count_slots(url): with urlopen(url) as response: data = response.read() empty_slots = 0 total_slots = 0 scps = set() soup = BeautifulSoup(data, 'html.parser') for link in soup.select('.series a'): href = link.get('href') if href is None or SCP_SERIES_REGEX.match(href) is None: continue if href in scps: continue scps.add(href) total_slots += 1 if link.get('class') == ['newpage']: empty_slots += 1 return empty_slots, total_slots def get_series_url(number): if number == 1: return 'http://www.scp-wiki.net/scp-series' return f'http://www.scp-wiki.net/scp-series-{series}' if __name__ == '__main__': if len(sys.argv) > 1: series = int(sys.argv[1]) else: series = 5 url = get_series_url(series) print(f'Counting slots in {url}...') empty, total = count_slots(url) print(f'{empty} / {total} slots empty ({empty/total*100:.2f}%)')
#!/usr/bin/python import re import sys from bs4 import BeautifulSoup from urllib.request import urlopen SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}') def count_slots(url): with urlopen(url) as response: data = response.read() empty_slots = 0 total_slots = 0 scps = set() soup = BeautifulSoup(data, 'html.parser') for link in soup.select('.series a'): href = link.get('href') if href is None or SCP_SERIES_REGEX.match(href) is None: continue if href in scps: continue scps.add(href) total_slots += 1 if link.get('class') == ['newpage']: empty_slots += 1 return empty_slots, total_slots if __name__ == '__main__': if len(sys.argv) > 1: series = int(sys.argv[1]) else: series = 5 url = f'http://www.scp-wiki.net/scp-series-{series}' print(f'Counting slots in {url}...') empty, total = count_slots(url) print(f'{empty} / {total} slots empty ({empty/total*100:.2f}%)') Add support for Series I.#!/usr/bin/python import re import sys from bs4 import BeautifulSoup from urllib.request import urlopen SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}') def count_slots(url): with urlopen(url) as response: data = response.read() empty_slots = 0 total_slots = 0 scps = set() soup = BeautifulSoup(data, 'html.parser') for link in soup.select('.series a'): href = link.get('href') if href is None or SCP_SERIES_REGEX.match(href) is None: continue if href in scps: continue scps.add(href) total_slots += 1 if link.get('class') == ['newpage']: empty_slots += 1 return empty_slots, total_slots def get_series_url(number): if number == 1: return 'http://www.scp-wiki.net/scp-series' return f'http://www.scp-wiki.net/scp-series-{series}' if __name__ == '__main__': if len(sys.argv) > 1: series = int(sys.argv[1]) else: series = 5 url = get_series_url(series) print(f'Counting slots in {url}...') empty, total = count_slots(url) print(f'{empty} / {total} slots empty ({empty/total*100:.2f}%)')
<commit_before>#!/usr/bin/python import re import sys from bs4 import BeautifulSoup from urllib.request import urlopen SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}') def count_slots(url): with urlopen(url) as response: data = response.read() empty_slots = 0 total_slots = 0 scps = set() soup = BeautifulSoup(data, 'html.parser') for link in soup.select('.series a'): href = link.get('href') if href is None or SCP_SERIES_REGEX.match(href) is None: continue if href in scps: continue scps.add(href) total_slots += 1 if link.get('class') == ['newpage']: empty_slots += 1 return empty_slots, total_slots if __name__ == '__main__': if len(sys.argv) > 1: series = int(sys.argv[1]) else: series = 5 url = f'http://www.scp-wiki.net/scp-series-{series}' print(f'Counting slots in {url}...') empty, total = count_slots(url) print(f'{empty} / {total} slots empty ({empty/total*100:.2f}%)') <commit_msg>Add support for Series I.<commit_after>#!/usr/bin/python import re import sys from bs4 import BeautifulSoup from urllib.request import urlopen SCP_SERIES_REGEX = re.compile(r'/scp-[0-9]{3,4}') def count_slots(url): with urlopen(url) as response: data = response.read() empty_slots = 0 total_slots = 0 scps = set() soup = BeautifulSoup(data, 'html.parser') for link in soup.select('.series a'): href = link.get('href') if href is None or SCP_SERIES_REGEX.match(href) is None: continue if href in scps: continue scps.add(href) total_slots += 1 if link.get('class') == ['newpage']: empty_slots += 1 return empty_slots, total_slots def get_series_url(number): if number == 1: return 'http://www.scp-wiki.net/scp-series' return f'http://www.scp-wiki.net/scp-series-{series}' if __name__ == '__main__': if len(sys.argv) > 1: series = int(sys.argv[1]) else: series = 5 url = get_series_url(series) print(f'Counting slots in {url}...') empty, total = count_slots(url) print(f'{empty} / {total} slots empty ({empty/total*100:.2f}%)')
f53f8b7cb7c45bc9bb7db65ebeb8791fd2e62873
send_boto.py
send_boto.py
import sys import boto import boto.s3 # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10)
import sys import boto import boto.s3 # for debugging boto.set_stream_logger('boto') # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10)
Debug sending data w/ boto.
Debug sending data w/ boto.
Python
bsd-2-clause
LeMeteore/ballin-octo-ninja
import sys import boto import boto.s3 # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10) Debug sending data w/ boto.
import sys import boto import boto.s3 # for debugging boto.set_stream_logger('boto') # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10)
<commit_before>import sys import boto import boto.s3 # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10) <commit_msg>Debug sending data w/ boto.<commit_after>
import sys import boto import boto.s3 # for debugging boto.set_stream_logger('boto') # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10)
import sys import boto import boto.s3 # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10) Debug sending data w/ boto.import sys import boto import boto.s3 # for debugging boto.set_stream_logger('boto') # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10)
<commit_before>import sys import boto import boto.s3 # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10) <commit_msg>Debug sending data w/ boto.<commit_after>import sys import boto import boto.s3 # for debugging boto.set_stream_logger('boto') # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' # a bucket per author maybe bucket_name = 'boto-demo-1421108796' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s3.connection.Location.DEFAULT) uploadfile = sys.argv[1] print('Uploading %s to Amazon S3 bucket %s' % (uploadfile, bucket_name)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() from boto.s3.key import Key k = Key(bucket) # the key, should be the file name k.key = str(uploadfile) # the key value k.set_contents_from_filename(uploadfile, cb=percent_cb, num_cb=10)
76784dc06bc1d7fedb7e2e85f87fc4a2c2a489fc
chainer/functions/reshape.py
chainer/functions/reshape.py
from chainer import function class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x)
import numpy from chainer import function from chainer.utils import type_check class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def check_type_forward(self, in_type): type_check.expect(in_type.size() == 1) x_type, = in_type in_shape_size = type_check.Variable( numpy.prod(x_type.shape.eval()), 'in_shape_size') out_shape_size = type_check.Variable( numpy.prod(self.shape), 'out_shape_size') type_check.expect(in_shape_size == out_shape_size) def check_type_backward(self, in_types, out_types): type_check.expect(out_types.size() == 1) x_type, = in_types y_type, = out_types in_shape_size = type_check.Variable( numpy.prod(x_type.shape.eval()), 'in_shape_size') out_shape_size = type_check.Variable( numpy.prod(y_type.shape.eval()), 'out_shape_size') type_check.expect(in_shape_size == out_shape_size) def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x)
Add typecheck for Reshape function
Add typecheck for Reshape function
Python
mit
muupan/chainer,niboshi/chainer,AlpacaDB/chainer,ktnyt/chainer,keisuke-umezawa/chainer,ytoyama/yans_chainer_hackathon,elviswf/chainer,wkentaro/chainer,jfsantos/chainer,chainer/chainer,ikasumi/chainer,hvy/chainer,okuta/chainer,bayerj/chainer,tigerneil/chainer,okuta/chainer,cupy/cupy,muupan/chainer,sinhrks/chainer,anaruse/chainer,niboshi/chainer,truongdq/chainer,ronekko/chainer,delta2323/chainer,cemoody/chainer,cupy/cupy,1986ks/chainer,hvy/chainer,keisuke-umezawa/chainer,woodshop/chainer,tkerola/chainer,tscohen/chainer,jnishi/chainer,jnishi/chainer,wavelets/chainer,okuta/chainer,sinhrks/chainer,ktnyt/chainer,kashif/chainer,jnishi/chainer,minhpqn/chainer,chainer/chainer,wkentaro/chainer,keisuke-umezawa/chainer,truongdq/chainer,cupy/cupy,cupy/cupy,kikusu/chainer,wkentaro/chainer,laysakura/chainer,ktnyt/chainer,kuwa32/chainer,masia02/chainer,hidenori-t/chainer,pfnet/chainer,jnishi/chainer,wkentaro/chainer,niboshi/chainer,hvy/chainer,ktnyt/chainer,yanweifu/chainer,niboshi/chainer,okuta/chainer,benob/chainer,umitanuki/chainer,kikusu/chainer,keisuke-umezawa/chainer,woodshop/complex-chainer,aonotas/chainer,ysekky/chainer,sou81821/chainer,t-abe/chainer,chainer/chainer,hvy/chainer,rezoo/chainer,kiyukuta/chainer,chainer/chainer,t-abe/chainer,AlpacaDB/chainer,Kaisuke5/chainer,benob/chainer
from chainer import function class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x) Add typecheck for Reshape function
import numpy from chainer import function from chainer.utils import type_check class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def check_type_forward(self, in_type): type_check.expect(in_type.size() == 1) x_type, = in_type in_shape_size = type_check.Variable( numpy.prod(x_type.shape.eval()), 'in_shape_size') out_shape_size = type_check.Variable( numpy.prod(self.shape), 'out_shape_size') type_check.expect(in_shape_size == out_shape_size) def check_type_backward(self, in_types, out_types): type_check.expect(out_types.size() == 1) x_type, = in_types y_type, = out_types in_shape_size = type_check.Variable( numpy.prod(x_type.shape.eval()), 'in_shape_size') out_shape_size = type_check.Variable( numpy.prod(y_type.shape.eval()), 'out_shape_size') type_check.expect(in_shape_size == out_shape_size) def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x)
<commit_before>from chainer import function class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x) <commit_msg>Add typecheck for Reshape function<commit_after>
import numpy from chainer import function from chainer.utils import type_check class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def check_type_forward(self, in_type): type_check.expect(in_type.size() == 1) x_type, = in_type in_shape_size = type_check.Variable( numpy.prod(x_type.shape.eval()), 'in_shape_size') out_shape_size = type_check.Variable( numpy.prod(self.shape), 'out_shape_size') type_check.expect(in_shape_size == out_shape_size) def check_type_backward(self, in_types, out_types): type_check.expect(out_types.size() == 1) x_type, = in_types y_type, = out_types in_shape_size = type_check.Variable( numpy.prod(x_type.shape.eval()), 'in_shape_size') out_shape_size = type_check.Variable( numpy.prod(y_type.shape.eval()), 'out_shape_size') type_check.expect(in_shape_size == out_shape_size) def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x)
from chainer import function class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x) Add typecheck for Reshape functionimport numpy from chainer import function from chainer.utils import type_check class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def check_type_forward(self, in_type): type_check.expect(in_type.size() == 1) x_type, = in_type in_shape_size = type_check.Variable( numpy.prod(x_type.shape.eval()), 'in_shape_size') out_shape_size = type_check.Variable( numpy.prod(self.shape), 'out_shape_size') type_check.expect(in_shape_size == out_shape_size) def check_type_backward(self, in_types, out_types): type_check.expect(out_types.size() == 1) x_type, = in_types y_type, = out_types in_shape_size = type_check.Variable( numpy.prod(x_type.shape.eval()), 'in_shape_size') out_shape_size = type_check.Variable( numpy.prod(y_type.shape.eval()), 'out_shape_size') type_check.expect(in_shape_size == out_shape_size) def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x)
<commit_before>from chainer import function class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x) <commit_msg>Add typecheck for Reshape function<commit_after>import numpy from chainer import function from chainer.utils import type_check class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def check_type_forward(self, in_type): type_check.expect(in_type.size() == 1) x_type, = in_type in_shape_size = type_check.Variable( numpy.prod(x_type.shape.eval()), 'in_shape_size') out_shape_size = type_check.Variable( numpy.prod(self.shape), 'out_shape_size') type_check.expect(in_shape_size == out_shape_size) def check_type_backward(self, in_types, out_types): type_check.expect(out_types.size() == 1) x_type, = in_types y_type, = out_types in_shape_size = type_check.Variable( numpy.prod(x_type.shape.eval()), 'in_shape_size') out_shape_size = type_check.Variable( numpy.prod(y_type.shape.eval()), 'out_shape_size') type_check.expect(in_shape_size == out_shape_size) def forward(self, x): return x[0].reshape(self.shape), def backward(self, x, gy): return gy[0].reshape(x[0].shape), def reshape(x, shape): """Reshapes an input variable without copy. Args: x (~chainer.Variable): Input variable. shape (tuple of ints): Target shape. Returns: ~chainer.Variable: Variable that holds a reshaped version of the input variable. """ return Reshape(shape)(x)
df8c19fe4679aa0d4fff90a15efcf4183a8ec8c1
api/v2/serializers/details/image_version.py
api/v2/serializers/details/image_version.py
from core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import LicenseSerializer from api.v2.serializers.summaries import ImageVersionSummarySerializer from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() #name, change_log, allow_imaging licenses = LicenseSerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW machines = ProviderMachineRelatedField(many=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'machines', 'allow_imaging', 'licenses', 'membership', 'start_date', 'end_date')
from core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import ( LicenseSerializer, UserSummarySerializer, IdentitySummarySerializer, ImageVersionSummarySerializer) from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() #name, change_log, allow_imaging licenses = LicenseSerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW user = UserSummarySerializer(source='created_by') identity = IdentitySummarySerializer(source='created_by_identity') machines = ProviderMachineRelatedField(many=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'machines', 'allow_imaging', 'licenses', 'membership', 'start_date', 'end_date')
Add 'user' and 'identity' attributes to the ImageVersion Details Serializer
Add 'user' and 'identity' attributes to the ImageVersion Details Serializer
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
from core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import LicenseSerializer from api.v2.serializers.summaries import ImageVersionSummarySerializer from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() #name, change_log, allow_imaging licenses = LicenseSerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW machines = ProviderMachineRelatedField(many=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'machines', 'allow_imaging', 'licenses', 'membership', 'start_date', 'end_date') Add 'user' and 'identity' attributes to the ImageVersion Details Serializer
from core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import ( LicenseSerializer, UserSummarySerializer, IdentitySummarySerializer, ImageVersionSummarySerializer) from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() #name, change_log, allow_imaging licenses = LicenseSerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW user = UserSummarySerializer(source='created_by') identity = IdentitySummarySerializer(source='created_by_identity') machines = ProviderMachineRelatedField(many=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'machines', 'allow_imaging', 'licenses', 'membership', 'start_date', 'end_date')
<commit_before>from core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import LicenseSerializer from api.v2.serializers.summaries import ImageVersionSummarySerializer from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() #name, change_log, allow_imaging licenses = LicenseSerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW machines = ProviderMachineRelatedField(many=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'machines', 'allow_imaging', 'licenses', 'membership', 'start_date', 'end_date') <commit_msg>Add 'user' and 'identity' attributes to the ImageVersion Details Serializer<commit_after>
from core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import ( LicenseSerializer, UserSummarySerializer, IdentitySummarySerializer, ImageVersionSummarySerializer) from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() #name, change_log, allow_imaging licenses = LicenseSerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW user = UserSummarySerializer(source='created_by') identity = IdentitySummarySerializer(source='created_by_identity') machines = ProviderMachineRelatedField(many=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'machines', 'allow_imaging', 'licenses', 'membership', 'start_date', 'end_date')
from core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import LicenseSerializer from api.v2.serializers.summaries import ImageVersionSummarySerializer from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() #name, change_log, allow_imaging licenses = LicenseSerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW machines = ProviderMachineRelatedField(many=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'machines', 'allow_imaging', 'licenses', 'membership', 'start_date', 'end_date') Add 'user' and 'identity' attributes to the ImageVersion Details Serializerfrom core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import ( LicenseSerializer, UserSummarySerializer, IdentitySummarySerializer, ImageVersionSummarySerializer) from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() #name, change_log, allow_imaging licenses = LicenseSerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW user = UserSummarySerializer(source='created_by') identity = IdentitySummarySerializer(source='created_by_identity') machines = ProviderMachineRelatedField(many=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'machines', 'allow_imaging', 'licenses', 'membership', 'start_date', 'end_date')
<commit_before>from core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import LicenseSerializer from api.v2.serializers.summaries import ImageVersionSummarySerializer from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() #name, change_log, allow_imaging licenses = LicenseSerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW machines = ProviderMachineRelatedField(many=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'machines', 'allow_imaging', 'licenses', 'membership', 'start_date', 'end_date') <commit_msg>Add 'user' and 'identity' attributes to the ImageVersion Details Serializer<commit_after>from core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import ( LicenseSerializer, UserSummarySerializer, IdentitySummarySerializer, ImageVersionSummarySerializer) from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() #name, change_log, allow_imaging licenses = LicenseSerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW user = UserSummarySerializer(source='created_by') identity = IdentitySummarySerializer(source='created_by_identity') machines = ProviderMachineRelatedField(many=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'machines', 'allow_imaging', 'licenses', 'membership', 'start_date', 'end_date')
06dd856ce57193f34395f8ee6e7c7d3030356609
tests/test_single.py
tests/test_single.py
import json from fixtures import PostSerializer def test_single(post): data = PostSerializer().to_json(post) assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]} def test_meta(post): data = PostSerializer().to_json(post, meta={'key': 'value'}) assert json.loads(data)['meta']['key'] == 'value'
import json from fixtures import PostSerializer def test_single(post): data = PostSerializer().to_json(post) assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]} def test_multiple(post_factory): post = post_factory(id=1, title='A title') another_post = post_factory(id=2, title='Another title') data = PostSerializer().to_json([post, another_post]) assert json.loads(data) == { 'posts': [ {'id': 1, 'title': 'A title'}, {'id': 2, 'title': 'Another title'}, ] } def test_meta(post): data = PostSerializer().to_json(post, meta={'key': 'value'}) assert json.loads(data)['meta']['key'] == 'value'
Add test for multiple resources
Add test for multiple resources
Python
mit
kalasjocke/hyp
import json from fixtures import PostSerializer def test_single(post): data = PostSerializer().to_json(post) assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]} def test_meta(post): data = PostSerializer().to_json(post, meta={'key': 'value'}) assert json.loads(data)['meta']['key'] == 'value' Add test for multiple resources
import json from fixtures import PostSerializer def test_single(post): data = PostSerializer().to_json(post) assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]} def test_multiple(post_factory): post = post_factory(id=1, title='A title') another_post = post_factory(id=2, title='Another title') data = PostSerializer().to_json([post, another_post]) assert json.loads(data) == { 'posts': [ {'id': 1, 'title': 'A title'}, {'id': 2, 'title': 'Another title'}, ] } def test_meta(post): data = PostSerializer().to_json(post, meta={'key': 'value'}) assert json.loads(data)['meta']['key'] == 'value'
<commit_before>import json from fixtures import PostSerializer def test_single(post): data = PostSerializer().to_json(post) assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]} def test_meta(post): data = PostSerializer().to_json(post, meta={'key': 'value'}) assert json.loads(data)['meta']['key'] == 'value' <commit_msg>Add test for multiple resources<commit_after>
import json from fixtures import PostSerializer def test_single(post): data = PostSerializer().to_json(post) assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]} def test_multiple(post_factory): post = post_factory(id=1, title='A title') another_post = post_factory(id=2, title='Another title') data = PostSerializer().to_json([post, another_post]) assert json.loads(data) == { 'posts': [ {'id': 1, 'title': 'A title'}, {'id': 2, 'title': 'Another title'}, ] } def test_meta(post): data = PostSerializer().to_json(post, meta={'key': 'value'}) assert json.loads(data)['meta']['key'] == 'value'
import json from fixtures import PostSerializer def test_single(post): data = PostSerializer().to_json(post) assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]} def test_meta(post): data = PostSerializer().to_json(post, meta={'key': 'value'}) assert json.loads(data)['meta']['key'] == 'value' Add test for multiple resourcesimport json from fixtures import PostSerializer def test_single(post): data = PostSerializer().to_json(post) assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]} def test_multiple(post_factory): post = post_factory(id=1, title='A title') another_post = post_factory(id=2, title='Another title') data = PostSerializer().to_json([post, another_post]) assert json.loads(data) == { 'posts': [ {'id': 1, 'title': 'A title'}, {'id': 2, 'title': 'Another title'}, ] } def test_meta(post): data = PostSerializer().to_json(post, meta={'key': 'value'}) assert json.loads(data)['meta']['key'] == 'value'
<commit_before>import json from fixtures import PostSerializer def test_single(post): data = PostSerializer().to_json(post) assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]} def test_meta(post): data = PostSerializer().to_json(post, meta={'key': 'value'}) assert json.loads(data)['meta']['key'] == 'value' <commit_msg>Add test for multiple resources<commit_after>import json from fixtures import PostSerializer def test_single(post): data = PostSerializer().to_json(post) assert json.loads(data) == {'posts': [{'id': 1, 'title': 'My title'}]} def test_multiple(post_factory): post = post_factory(id=1, title='A title') another_post = post_factory(id=2, title='Another title') data = PostSerializer().to_json([post, another_post]) assert json.loads(data) == { 'posts': [ {'id': 1, 'title': 'A title'}, {'id': 2, 'title': 'Another title'}, ] } def test_meta(post): data = PostSerializer().to_json(post, meta={'key': 'value'}) assert json.loads(data)['meta']['key'] == 'value'
0a628ed81ca11fc4175b480aad9a136b8a4fe1c2
constantsgen/pythonwriter.py
constantsgen/pythonwriter.py
class PythonWriter: def __init__(self, constants): self.constants = constants def write(self, out): out.write("# This file was generated by generate_constants.\n\n") out.write("from enum import Enum, unique\n\n") for name, enum in self.constants.enum_values.items(): out.write(""" @unique class {}(Enum):\n""".format(name)) for base_name, value in enum.items(): # For the enum value names remove everything up through the # first underscore and convert the remainder to lowercase. For # example the value NV_BOOL is assigned to bool. If there is no # underscore, find() returns -1 and the entire string is used. first_underscore = base_name.find("_") name = base_name[first_underscore + 1:].lower() out.write(" {} = {}\n".format(name, value)) for name, value in self.constants.constant_values.items(): out.write("{} = {}\n".format(name, value))
class PythonWriter: def __init__(self, constants): self.constants = constants def write(self, out): out.write("# This file was generated by generate_constants.\n\n") out.write("from enum import Enum, unique\n\n") for name, enum in self.constants.enum_values.items(): out.write(""" @unique class {}(Enum):\n""".format(name)) for base_name, value in enum.items(): # For the enum value names remove everything up through the # first underscore and convert the remainder to lowercase. For # example the value NV_BOOL is assigned to bool. If there is no # underscore, find() returns -1 and the entire string is used. first_underscore = base_name.find("_") name = base_name[first_underscore + 1:].lower() out.write(" {} = {}\n".format(name, value)) out.write("\n\n") for name, value in self.constants.constant_values.items(): out.write("{} = {}\n".format(name, value))
Add PEP8 whitespace around Enums
Add PEP8 whitespace around Enums
Python
bsd-3-clause
barracudanetworks/constantsgen,barracudanetworks/constantsgen,barracudanetworks/constantsgen
class PythonWriter: def __init__(self, constants): self.constants = constants def write(self, out): out.write("# This file was generated by generate_constants.\n\n") out.write("from enum import Enum, unique\n\n") for name, enum in self.constants.enum_values.items(): out.write(""" @unique class {}(Enum):\n""".format(name)) for base_name, value in enum.items(): # For the enum value names remove everything up through the # first underscore and convert the remainder to lowercase. For # example the value NV_BOOL is assigned to bool. If there is no # underscore, find() returns -1 and the entire string is used. first_underscore = base_name.find("_") name = base_name[first_underscore + 1:].lower() out.write(" {} = {}\n".format(name, value)) for name, value in self.constants.constant_values.items(): out.write("{} = {}\n".format(name, value)) Add PEP8 whitespace around Enums
class PythonWriter: def __init__(self, constants): self.constants = constants def write(self, out): out.write("# This file was generated by generate_constants.\n\n") out.write("from enum import Enum, unique\n\n") for name, enum in self.constants.enum_values.items(): out.write(""" @unique class {}(Enum):\n""".format(name)) for base_name, value in enum.items(): # For the enum value names remove everything up through the # first underscore and convert the remainder to lowercase. For # example the value NV_BOOL is assigned to bool. If there is no # underscore, find() returns -1 and the entire string is used. first_underscore = base_name.find("_") name = base_name[first_underscore + 1:].lower() out.write(" {} = {}\n".format(name, value)) out.write("\n\n") for name, value in self.constants.constant_values.items(): out.write("{} = {}\n".format(name, value))
<commit_before>class PythonWriter: def __init__(self, constants): self.constants = constants def write(self, out): out.write("# This file was generated by generate_constants.\n\n") out.write("from enum import Enum, unique\n\n") for name, enum in self.constants.enum_values.items(): out.write(""" @unique class {}(Enum):\n""".format(name)) for base_name, value in enum.items(): # For the enum value names remove everything up through the # first underscore and convert the remainder to lowercase. For # example the value NV_BOOL is assigned to bool. If there is no # underscore, find() returns -1 and the entire string is used. first_underscore = base_name.find("_") name = base_name[first_underscore + 1:].lower() out.write(" {} = {}\n".format(name, value)) for name, value in self.constants.constant_values.items(): out.write("{} = {}\n".format(name, value)) <commit_msg>Add PEP8 whitespace around Enums<commit_after>
class PythonWriter: def __init__(self, constants): self.constants = constants def write(self, out): out.write("# This file was generated by generate_constants.\n\n") out.write("from enum import Enum, unique\n\n") for name, enum in self.constants.enum_values.items(): out.write(""" @unique class {}(Enum):\n""".format(name)) for base_name, value in enum.items(): # For the enum value names remove everything up through the # first underscore and convert the remainder to lowercase. For # example the value NV_BOOL is assigned to bool. If there is no # underscore, find() returns -1 and the entire string is used. first_underscore = base_name.find("_") name = base_name[first_underscore + 1:].lower() out.write(" {} = {}\n".format(name, value)) out.write("\n\n") for name, value in self.constants.constant_values.items(): out.write("{} = {}\n".format(name, value))
class PythonWriter: def __init__(self, constants): self.constants = constants def write(self, out): out.write("# This file was generated by generate_constants.\n\n") out.write("from enum import Enum, unique\n\n") for name, enum in self.constants.enum_values.items(): out.write(""" @unique class {}(Enum):\n""".format(name)) for base_name, value in enum.items(): # For the enum value names remove everything up through the # first underscore and convert the remainder to lowercase. For # example the value NV_BOOL is assigned to bool. If there is no # underscore, find() returns -1 and the entire string is used. first_underscore = base_name.find("_") name = base_name[first_underscore + 1:].lower() out.write(" {} = {}\n".format(name, value)) for name, value in self.constants.constant_values.items(): out.write("{} = {}\n".format(name, value)) Add PEP8 whitespace around Enumsclass PythonWriter: def __init__(self, constants): self.constants = constants def write(self, out): out.write("# This file was generated by generate_constants.\n\n") out.write("from enum import Enum, unique\n\n") for name, enum in self.constants.enum_values.items(): out.write(""" @unique class {}(Enum):\n""".format(name)) for base_name, value in enum.items(): # For the enum value names remove everything up through the # first underscore and convert the remainder to lowercase. For # example the value NV_BOOL is assigned to bool. If there is no # underscore, find() returns -1 and the entire string is used. first_underscore = base_name.find("_") name = base_name[first_underscore + 1:].lower() out.write(" {} = {}\n".format(name, value)) out.write("\n\n") for name, value in self.constants.constant_values.items(): out.write("{} = {}\n".format(name, value))
<commit_before>class PythonWriter: def __init__(self, constants): self.constants = constants def write(self, out): out.write("# This file was generated by generate_constants.\n\n") out.write("from enum import Enum, unique\n\n") for name, enum in self.constants.enum_values.items(): out.write(""" @unique class {}(Enum):\n""".format(name)) for base_name, value in enum.items(): # For the enum value names remove everything up through the # first underscore and convert the remainder to lowercase. For # example the value NV_BOOL is assigned to bool. If there is no # underscore, find() returns -1 and the entire string is used. first_underscore = base_name.find("_") name = base_name[first_underscore + 1:].lower() out.write(" {} = {}\n".format(name, value)) for name, value in self.constants.constant_values.items(): out.write("{} = {}\n".format(name, value)) <commit_msg>Add PEP8 whitespace around Enums<commit_after>class PythonWriter: def __init__(self, constants): self.constants = constants def write(self, out): out.write("# This file was generated by generate_constants.\n\n") out.write("from enum import Enum, unique\n\n") for name, enum in self.constants.enum_values.items(): out.write(""" @unique class {}(Enum):\n""".format(name)) for base_name, value in enum.items(): # For the enum value names remove everything up through the # first underscore and convert the remainder to lowercase. For # example the value NV_BOOL is assigned to bool. If there is no # underscore, find() returns -1 and the entire string is used. first_underscore = base_name.find("_") name = base_name[first_underscore + 1:].lower() out.write(" {} = {}\n".format(name, value)) out.write("\n\n") for name, value in self.constants.constant_values.items(): out.write("{} = {}\n".format(name, value))
640e0d0c9ec58c534f4d08962dd558e87401abb2
problem_4/solution.py
problem_4/solution.py
def is_palindrome_number(n): return n == n[::-1] largest_number = 0 for x in xrange(100, 999): for y in xrange(100, 999): v = x * y if v > largest_number: if is_palindrome_number(str(v)): largest_number = v print largest_number
import time def is_palindrome_number(n): return n == n[::-1] def largest_palindrome_from_the_product_of_three_digit_numbers(): largest_number = 0 for x in xrange(100, 999): for y in xrange(100, 999): v = x * y if v > largest_number: if is_palindrome_number(str(v)): largest_number = v return largest_number t1 = time.time() largest_palindrome_from_the_product_of_three_digit_numbers() t2 = time.time() print "largest_palindrome_from_the_product_of_three_digit_numbers: %fs" % (t2 - t1) print "Answer: {0}".format(largest_palindrome_from_the_product_of_three_digit_numbers())
Add timing for python implementation of problem 4
Add timing for python implementation of problem 4
Python
mit
mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler
def is_palindrome_number(n): return n == n[::-1] largest_number = 0 for x in xrange(100, 999): for y in xrange(100, 999): v = x * y if v > largest_number: if is_palindrome_number(str(v)): largest_number = v print largest_number Add timing for python implementation of problem 4
import time def is_palindrome_number(n): return n == n[::-1] def largest_palindrome_from_the_product_of_three_digit_numbers(): largest_number = 0 for x in xrange(100, 999): for y in xrange(100, 999): v = x * y if v > largest_number: if is_palindrome_number(str(v)): largest_number = v return largest_number t1 = time.time() largest_palindrome_from_the_product_of_three_digit_numbers() t2 = time.time() print "largest_palindrome_from_the_product_of_three_digit_numbers: %fs" % (t2 - t1) print "Answer: {0}".format(largest_palindrome_from_the_product_of_three_digit_numbers())
<commit_before>def is_palindrome_number(n): return n == n[::-1] largest_number = 0 for x in xrange(100, 999): for y in xrange(100, 999): v = x * y if v > largest_number: if is_palindrome_number(str(v)): largest_number = v print largest_number <commit_msg>Add timing for python implementation of problem 4<commit_after>
import time def is_palindrome_number(n): return n == n[::-1] def largest_palindrome_from_the_product_of_three_digit_numbers(): largest_number = 0 for x in xrange(100, 999): for y in xrange(100, 999): v = x * y if v > largest_number: if is_palindrome_number(str(v)): largest_number = v return largest_number t1 = time.time() largest_palindrome_from_the_product_of_three_digit_numbers() t2 = time.time() print "largest_palindrome_from_the_product_of_three_digit_numbers: %fs" % (t2 - t1) print "Answer: {0}".format(largest_palindrome_from_the_product_of_three_digit_numbers())
def is_palindrome_number(n): return n == n[::-1] largest_number = 0 for x in xrange(100, 999): for y in xrange(100, 999): v = x * y if v > largest_number: if is_palindrome_number(str(v)): largest_number = v print largest_number Add timing for python implementation of problem 4import time def is_palindrome_number(n): return n == n[::-1] def largest_palindrome_from_the_product_of_three_digit_numbers(): largest_number = 0 for x in xrange(100, 999): for y in xrange(100, 999): v = x * y if v > largest_number: if is_palindrome_number(str(v)): largest_number = v return largest_number t1 = time.time() largest_palindrome_from_the_product_of_three_digit_numbers() t2 = time.time() print "largest_palindrome_from_the_product_of_three_digit_numbers: %fs" % (t2 - t1) print "Answer: {0}".format(largest_palindrome_from_the_product_of_three_digit_numbers())
<commit_before>def is_palindrome_number(n): return n == n[::-1] largest_number = 0 for x in xrange(100, 999): for y in xrange(100, 999): v = x * y if v > largest_number: if is_palindrome_number(str(v)): largest_number = v print largest_number <commit_msg>Add timing for python implementation of problem 4<commit_after>import time def is_palindrome_number(n): return n == n[::-1] def largest_palindrome_from_the_product_of_three_digit_numbers(): largest_number = 0 for x in xrange(100, 999): for y in xrange(100, 999): v = x * y if v > largest_number: if is_palindrome_number(str(v)): largest_number = v return largest_number t1 = time.time() largest_palindrome_from_the_product_of_three_digit_numbers() t2 = time.time() print "largest_palindrome_from_the_product_of_three_digit_numbers: %fs" % (t2 - t1) print "Answer: {0}".format(largest_palindrome_from_the_product_of_three_digit_numbers())
619033bc8daf3b8f5faafa95b04c06d98c39969f
stack/vpc.py
stack/vpc.py
from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, Route, RouteTable, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) # Public route table public_route_table = RouteTable( "PublicRouteTable", template=template, VpcId=Ref(vpc), ) public_route = Route( "PublicRoute", template=template, GatewayId=Ref(internet_gateway), DestinationCidrBlock="0.0.0.0/0", RouteTableId=Ref(public_route_table), )
from troposphere import ( GetAtt, Ref, ) from troposphere.ec2 import ( EIP, InternetGateway, NatGateway, Route, RouteTable, Subnet, SubnetRouteTableAssociation, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) # Public route table public_route_table = RouteTable( "PublicRouteTable", template=template, VpcId=Ref(vpc), ) public_route = Route( "PublicRoute", template=template, GatewayId=Ref(internet_gateway), DestinationCidrBlock="0.0.0.0/0", RouteTableId=Ref(public_route_table), ) # Holds public instances public_subnet_cidr = "10.0.1.0/24" public_subnet = Subnet( "PublicSubnet", template=template, VpcId=Ref(vpc), CidrBlock=public_subnet_cidr, ) SubnetRouteTableAssociation( "PublicSubnetRouteTableAssociation", template=template, RouteTableId=Ref(public_route_table), SubnetId=Ref(public_subnet), ) # NAT nat_ip = EIP( "NatIp", template=template, Domain="vpc", ) nat_gateway = NatGateway( "NatGateway", template=template, AllocationId=GetAtt(nat_ip, "AllocationId"), SubnetId=Ref(public_subnet), )
Add a public subnet that holds a `NAT` gateway
Add a public subnet that holds a `NAT` gateway
Python
mit
caktus/aws-web-stacks,tobiasmcnulty/aws-container-basics
from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, Route, RouteTable, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) # Public route table public_route_table = RouteTable( "PublicRouteTable", template=template, VpcId=Ref(vpc), ) public_route = Route( "PublicRoute", template=template, GatewayId=Ref(internet_gateway), DestinationCidrBlock="0.0.0.0/0", RouteTableId=Ref(public_route_table), ) Add a public subnet that holds a `NAT` gateway
from troposphere import ( GetAtt, Ref, ) from troposphere.ec2 import ( EIP, InternetGateway, NatGateway, Route, RouteTable, Subnet, SubnetRouteTableAssociation, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) # Public route table public_route_table = RouteTable( "PublicRouteTable", template=template, VpcId=Ref(vpc), ) public_route = Route( "PublicRoute", template=template, GatewayId=Ref(internet_gateway), DestinationCidrBlock="0.0.0.0/0", RouteTableId=Ref(public_route_table), ) # Holds public instances public_subnet_cidr = "10.0.1.0/24" public_subnet = Subnet( "PublicSubnet", template=template, VpcId=Ref(vpc), CidrBlock=public_subnet_cidr, ) SubnetRouteTableAssociation( "PublicSubnetRouteTableAssociation", template=template, RouteTableId=Ref(public_route_table), SubnetId=Ref(public_subnet), ) # NAT nat_ip = EIP( "NatIp", template=template, Domain="vpc", ) nat_gateway = NatGateway( "NatGateway", template=template, AllocationId=GetAtt(nat_ip, "AllocationId"), SubnetId=Ref(public_subnet), )
<commit_before>from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, Route, RouteTable, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) # Public route table public_route_table = RouteTable( "PublicRouteTable", template=template, VpcId=Ref(vpc), ) public_route = Route( "PublicRoute", template=template, GatewayId=Ref(internet_gateway), DestinationCidrBlock="0.0.0.0/0", RouteTableId=Ref(public_route_table), ) <commit_msg>Add a public subnet that holds a `NAT` gateway<commit_after>
from troposphere import ( GetAtt, Ref, ) from troposphere.ec2 import ( EIP, InternetGateway, NatGateway, Route, RouteTable, Subnet, SubnetRouteTableAssociation, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) # Public route table public_route_table = RouteTable( "PublicRouteTable", template=template, VpcId=Ref(vpc), ) public_route = Route( "PublicRoute", template=template, GatewayId=Ref(internet_gateway), DestinationCidrBlock="0.0.0.0/0", RouteTableId=Ref(public_route_table), ) # Holds public instances public_subnet_cidr = "10.0.1.0/24" public_subnet = Subnet( "PublicSubnet", template=template, VpcId=Ref(vpc), CidrBlock=public_subnet_cidr, ) SubnetRouteTableAssociation( "PublicSubnetRouteTableAssociation", template=template, RouteTableId=Ref(public_route_table), SubnetId=Ref(public_subnet), ) # NAT nat_ip = EIP( "NatIp", template=template, Domain="vpc", ) nat_gateway = NatGateway( "NatGateway", template=template, AllocationId=GetAtt(nat_ip, "AllocationId"), SubnetId=Ref(public_subnet), )
from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, Route, RouteTable, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) # Public route table public_route_table = RouteTable( "PublicRouteTable", template=template, VpcId=Ref(vpc), ) public_route = Route( "PublicRoute", template=template, GatewayId=Ref(internet_gateway), DestinationCidrBlock="0.0.0.0/0", RouteTableId=Ref(public_route_table), ) Add a public subnet that holds a `NAT` gatewayfrom troposphere import ( GetAtt, Ref, ) from troposphere.ec2 import ( EIP, InternetGateway, NatGateway, Route, RouteTable, Subnet, SubnetRouteTableAssociation, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) # Public route table public_route_table = RouteTable( "PublicRouteTable", template=template, VpcId=Ref(vpc), ) public_route = Route( "PublicRoute", template=template, GatewayId=Ref(internet_gateway), DestinationCidrBlock="0.0.0.0/0", RouteTableId=Ref(public_route_table), ) # Holds public instances public_subnet_cidr = "10.0.1.0/24" public_subnet = Subnet( "PublicSubnet", template=template, VpcId=Ref(vpc), CidrBlock=public_subnet_cidr, ) SubnetRouteTableAssociation( "PublicSubnetRouteTableAssociation", template=template, RouteTableId=Ref(public_route_table), SubnetId=Ref(public_subnet), ) # NAT nat_ip = EIP( "NatIp", template=template, Domain="vpc", ) nat_gateway = NatGateway( "NatGateway", template=template, AllocationId=GetAtt(nat_ip, "AllocationId"), SubnetId=Ref(public_subnet), )
<commit_before>from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, Route, RouteTable, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) # Public route table public_route_table = RouteTable( "PublicRouteTable", template=template, VpcId=Ref(vpc), ) public_route = Route( "PublicRoute", template=template, GatewayId=Ref(internet_gateway), DestinationCidrBlock="0.0.0.0/0", RouteTableId=Ref(public_route_table), ) <commit_msg>Add a public subnet that holds a `NAT` gateway<commit_after>from troposphere import ( GetAtt, Ref, ) from troposphere.ec2 import ( EIP, InternetGateway, NatGateway, Route, RouteTable, Subnet, SubnetRouteTableAssociation, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) # Public route table public_route_table = RouteTable( "PublicRouteTable", template=template, VpcId=Ref(vpc), ) public_route = Route( "PublicRoute", template=template, GatewayId=Ref(internet_gateway), DestinationCidrBlock="0.0.0.0/0", RouteTableId=Ref(public_route_table), ) # Holds public instances public_subnet_cidr = "10.0.1.0/24" public_subnet = Subnet( "PublicSubnet", template=template, VpcId=Ref(vpc), CidrBlock=public_subnet_cidr, ) SubnetRouteTableAssociation( "PublicSubnetRouteTableAssociation", template=template, RouteTableId=Ref(public_route_table), SubnetId=Ref(public_subnet), ) # NAT nat_ip = EIP( "NatIp", template=template, Domain="vpc", ) nat_gateway = NatGateway( "NatGateway", template=template, AllocationId=GetAtt(nat_ip, "AllocationId"), SubnetId=Ref(public_subnet), )
26e16c6229f12ca75c4bbf224eb9d1cf3b250b9c
rock/utils.py
rock/utils.py
import StringIO import os from rock.exceptions import ConfigError ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split() class Shell(object): def __init__(self): self.stdin = StringIO.StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not os.path.isfile(ROCK_SHELL[0]) or not os.access(ROCK_SHELL[0], os.X_OK): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n')
import StringIO import os from rock.exceptions import ConfigError ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split() def isexecutable(path): return os.path.isfile(path) and os.access(path, os.X_OK) class Shell(object): def __init__(self): self.stdin = StringIO.StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not isexecutable(ROCK_SHELL[0]): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n')
Split isexecutable into its own function
Split isexecutable into its own function
Python
mit
silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock
import StringIO import os from rock.exceptions import ConfigError ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split() class Shell(object): def __init__(self): self.stdin = StringIO.StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not os.path.isfile(ROCK_SHELL[0]) or not os.access(ROCK_SHELL[0], os.X_OK): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n') Split isexecutable into its own function
import StringIO import os from rock.exceptions import ConfigError ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split() def isexecutable(path): return os.path.isfile(path) and os.access(path, os.X_OK) class Shell(object): def __init__(self): self.stdin = StringIO.StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not isexecutable(ROCK_SHELL[0]): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n')
<commit_before>import StringIO import os from rock.exceptions import ConfigError ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split() class Shell(object): def __init__(self): self.stdin = StringIO.StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not os.path.isfile(ROCK_SHELL[0]) or not os.access(ROCK_SHELL[0], os.X_OK): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n') <commit_msg>Split isexecutable into its own function<commit_after>
import StringIO import os from rock.exceptions import ConfigError ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split() def isexecutable(path): return os.path.isfile(path) and os.access(path, os.X_OK) class Shell(object): def __init__(self): self.stdin = StringIO.StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not isexecutable(ROCK_SHELL[0]): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n')
import StringIO import os from rock.exceptions import ConfigError ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split() class Shell(object): def __init__(self): self.stdin = StringIO.StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not os.path.isfile(ROCK_SHELL[0]) or not os.access(ROCK_SHELL[0], os.X_OK): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n') Split isexecutable into its own functionimport StringIO import os from rock.exceptions import ConfigError ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split() def isexecutable(path): return os.path.isfile(path) and os.access(path, os.X_OK) class Shell(object): def __init__(self): self.stdin = StringIO.StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not isexecutable(ROCK_SHELL[0]): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n')
<commit_before>import StringIO import os from rock.exceptions import ConfigError ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split() class Shell(object): def __init__(self): self.stdin = StringIO.StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not os.path.isfile(ROCK_SHELL[0]) or not os.access(ROCK_SHELL[0], os.X_OK): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n') <commit_msg>Split isexecutable into its own function<commit_after>import StringIO import os from rock.exceptions import ConfigError ROCK_SHELL = os.environ.get('ROCK_SHELL', '/bin/bash -l -c').split() def isexecutable(path): return os.path.isfile(path) and os.access(path, os.X_OK) class Shell(object): def __init__(self): self.stdin = StringIO.StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): self.run() def run(self): if not isexecutable(ROCK_SHELL[0]): raise ConfigError('invalid ROCK_SHELL: %s' % ROCK_SHELL) os.execl(*(ROCK_SHELL + [self.stdin.getvalue()])) def write(self, text): self.stdin.write(text + '\n')
6c564ebe538d2723cc5f9397e09e5945796a257e
pyelevator/message.py
pyelevator/message.py
import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], }
import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1) and not isinstance(self._datas[0], (tuple, list)): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], }
Fix : Range of len(1) have to be a tuple of tuples
Fix : Range of len(1) have to be a tuple of tuples
Python
mit
oleiade/py-elevator
import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], } Fix : Range of len(1) have to be a tuple of tuples
import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1) and not isinstance(self._datas[0], (tuple, list)): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], }
<commit_before>import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], } <commit_msg>Fix : Range of len(1) have to be a tuple of tuples<commit_after>
import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1) and not isinstance(self._datas[0], (tuple, list)): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], }
import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], } Fix : Range of len(1) have to be a tuple of tuplesimport msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1) and not isinstance(self._datas[0], (tuple, list)): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], }
<commit_before>import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], } <commit_msg>Fix : Range of len(1) have to be a tuple of tuples<commit_after>import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1) and not isinstance(self._datas[0], (tuple, list)): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], }
3c30166378d37c812cecb505a3d9023b079d24be
app/__init__.py
app/__init__.py
# Gevent needed for sockets from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk try: nltk.data.find('tokenizers/punkt') except LookupError: nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404
# Gevent needed for sockets from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404
Fix stupid nltk data download thing
Fix stupid nltk data download thing
Python
mit
PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews,PapaCharlie/SteamyReviews
# Gevent needed for sockets from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk try: nltk.data.find('tokenizers/punkt') except LookupError: nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404 Fix stupid nltk data download thing
# Gevent needed for sockets from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404
<commit_before># Gevent needed for sockets from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk try: nltk.data.find('tokenizers/punkt') except LookupError: nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404 <commit_msg>Fix stupid nltk data download thing<commit_after>
# Gevent needed for sockets from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404
# Gevent needed for sockets from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk try: nltk.data.find('tokenizers/punkt') except LookupError: nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404 Fix stupid nltk data download thing# Gevent needed for sockets from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404
<commit_before># Gevent needed for sockets from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk try: nltk.data.find('tokenizers/punkt') except LookupError: nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404 <commit_msg>Fix stupid nltk data download thing<commit_after># Gevent needed for sockets from gevent import monkey monkey.patch_all() # Imports import os from flask import Flask, render_template from flask_socketio import SocketIO import boto3 # Configure app socketio = SocketIO() app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) import nltk nltk.download("punkt") # DB db = boto3.resource("dynamodb", region_name=app.config["DYNAMO_REGION"], endpoint_url=app.config["DYNAMO_DATABASE_URI"]) s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"]) from app import models models.initialize() # Initialize the controllers from app import controllers # Initialize app w/SocketIO socketio.init_app(app) # HTTP error handling @app.errorhandler(404) def not_found(error): return render_template("404.html"), 404
1599bc03b0a1cd202836479fba2406457a17f118
user_map/tests/urls.py
user_map/tests/urls.py
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^user-map/', include('user_map.urls', namespace='user_map')) )
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^user-map/', include('user_map.urls', namespace='user_map')), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}, name='my_login', ), )
Add login url for testing.
Add login url for testing.
Python
lgpl-2.1
akbargumbira/django-user-map,akbargumbira/django-user-map,akbargumbira/django-user-map,akbargumbira/django-user-map
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^user-map/', include('user_map.urls', namespace='user_map')) ) Add login url for testing.
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^user-map/', include('user_map.urls', namespace='user_map')), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}, name='my_login', ), )
<commit_before>from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^user-map/', include('user_map.urls', namespace='user_map')) ) <commit_msg>Add login url for testing.<commit_after>
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^user-map/', include('user_map.urls', namespace='user_map')), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}, name='my_login', ), )
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^user-map/', include('user_map.urls', namespace='user_map')) ) Add login url for testing.from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^user-map/', include('user_map.urls', namespace='user_map')), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}, name='my_login', ), )
<commit_before>from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^user-map/', include('user_map.urls', namespace='user_map')) ) <commit_msg>Add login url for testing.<commit_after>from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^user-map/', include('user_map.urls', namespace='user_map')), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}, name='my_login', ), )
2a9c213c02abbabeddbf2a699fd6caf5e18bf6dd
utils/word_checking.py
utils/word_checking.py
from __future__ import unicode_literals import re from collections import Counter def check_for_flag_words(message, words_array): cnt = Counter() delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r ' pattern = r"[{}]".format(delims) message_array = re.split(pattern, message.lower()) for word in message_array: formatted_word = word.replace(u"\u2019s", "").replace(u"s\u2019", "s").replace("'s", "").replace("s'", "s") if formatted_word in words_array: cnt[formatted_word] += 1 return dict(cnt)
from __future__ import unicode_literals import re from collections import Counter def check_for_flag_words(message, words_array): cnt = Counter() delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r ' pattern = r"[{}]".format(delims) message_array = re.split(pattern, message.lower()) for word in message_array: # remove numbers from the word text_word = re.sub("\d", "", word) # handle apostrophes including unicode, ie. apple's -> apple and apples' -> apples formatted_word = text_word.replace(u"\u2019s", "").replace(u"s\u2019", "s").replace("'s", "").replace("s'", "s") if formatted_word in words_array: cnt[formatted_word] += 1 return dict(cnt)
Remove numbers from the word to check for.
Remove numbers from the word to check for.
Python
apache-2.0
jkvoorhis/cheeseburger_backpack_bot
from __future__ import unicode_literals import re from collections import Counter def check_for_flag_words(message, words_array): cnt = Counter() delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r ' pattern = r"[{}]".format(delims) message_array = re.split(pattern, message.lower()) for word in message_array: formatted_word = word.replace(u"\u2019s", "").replace(u"s\u2019", "s").replace("'s", "").replace("s'", "s") if formatted_word in words_array: cnt[formatted_word] += 1 return dict(cnt) Remove numbers from the word to check for.
from __future__ import unicode_literals import re from collections import Counter def check_for_flag_words(message, words_array): cnt = Counter() delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r ' pattern = r"[{}]".format(delims) message_array = re.split(pattern, message.lower()) for word in message_array: # remove numbers from the word text_word = re.sub("\d", "", word) # handle apostrophes including unicode, ie. apple's -> apple and apples' -> apples formatted_word = text_word.replace(u"\u2019s", "").replace(u"s\u2019", "s").replace("'s", "").replace("s'", "s") if formatted_word in words_array: cnt[formatted_word] += 1 return dict(cnt)
<commit_before>from __future__ import unicode_literals import re from collections import Counter def check_for_flag_words(message, words_array): cnt = Counter() delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r ' pattern = r"[{}]".format(delims) message_array = re.split(pattern, message.lower()) for word in message_array: formatted_word = word.replace(u"\u2019s", "").replace(u"s\u2019", "s").replace("'s", "").replace("s'", "s") if formatted_word in words_array: cnt[formatted_word] += 1 return dict(cnt) <commit_msg>Remove numbers from the word to check for.<commit_after>
from __future__ import unicode_literals import re from collections import Counter def check_for_flag_words(message, words_array): cnt = Counter() delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r ' pattern = r"[{}]".format(delims) message_array = re.split(pattern, message.lower()) for word in message_array: # remove numbers from the word text_word = re.sub("\d", "", word) # handle apostrophes including unicode, ie. apple's -> apple and apples' -> apples formatted_word = text_word.replace(u"\u2019s", "").replace(u"s\u2019", "s").replace("'s", "").replace("s'", "s") if formatted_word in words_array: cnt[formatted_word] += 1 return dict(cnt)
from __future__ import unicode_literals import re from collections import Counter def check_for_flag_words(message, words_array): cnt = Counter() delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r ' pattern = r"[{}]".format(delims) message_array = re.split(pattern, message.lower()) for word in message_array: formatted_word = word.replace(u"\u2019s", "").replace(u"s\u2019", "s").replace("'s", "").replace("s'", "s") if formatted_word in words_array: cnt[formatted_word] += 1 return dict(cnt) Remove numbers from the word to check for.from __future__ import unicode_literals import re from collections import Counter def check_for_flag_words(message, words_array): cnt = Counter() delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r ' pattern = r"[{}]".format(delims) message_array = re.split(pattern, message.lower()) for word in message_array: # remove numbers from the word text_word = re.sub("\d", "", word) # handle apostrophes including unicode, ie. apple's -> apple and apples' -> apples formatted_word = text_word.replace(u"\u2019s", "").replace(u"s\u2019", "s").replace("'s", "").replace("s'", "s") if formatted_word in words_array: cnt[formatted_word] += 1 return dict(cnt)
<commit_before>from __future__ import unicode_literals import re from collections import Counter def check_for_flag_words(message, words_array): cnt = Counter() delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r ' pattern = r"[{}]".format(delims) message_array = re.split(pattern, message.lower()) for word in message_array: formatted_word = word.replace(u"\u2019s", "").replace(u"s\u2019", "s").replace("'s", "").replace("s'", "s") if formatted_word in words_array: cnt[formatted_word] += 1 return dict(cnt) <commit_msg>Remove numbers from the word to check for.<commit_after>from __future__ import unicode_literals import re from collections import Counter def check_for_flag_words(message, words_array): cnt = Counter() delims = '!"#$%&()*+,./:;<=>?@[\\]^_`{|}~\t\n\x0b\x0c\r ' pattern = r"[{}]".format(delims) message_array = re.split(pattern, message.lower()) for word in message_array: # remove numbers from the word text_word = re.sub("\d", "", word) # handle apostrophes including unicode, ie. apple's -> apple and apples' -> apples formatted_word = text_word.replace(u"\u2019s", "").replace(u"s\u2019", "s").replace("'s", "").replace("s'", "s") if formatted_word in words_array: cnt[formatted_word] += 1 return dict(cnt)
186cd6148bba29baebad0dfcdbe57cd393bf1777
report/report_util.py
report/report_util.py
def compare_ledger_types(account, data, orm): # TODO alternate_ledger return True account_ledgers = [ledger.id for ledger in account.ledger_types] selected_ledger = int(data['form']['ledger_type']) # Store in data to avoid recomputing. if 'ledger_type_all' not in data: data['ledger_type_all'] = ( orm.pool.get('alternate_ledger.ledger_type').browse( orm.cursor, orm.uid, selected_ledger).name == 'A') catch_all = data['ledger_type_all'] return (selected_ledger in account_ledgers or (catch_all and account_ledgers == [])) def should_show_account(account, data): if 'account_from' not in data['form'] or 'account_to' not in data['form']: return True low = data['form']['account_from'] high = data['form']['account_to'] return low <= account.code <= high
def compare_ledger_types(account, data, orm): account_ledgers = [ledger.id for ledger in account.ledger_types] selected_ledgers = data['form']['ledger_types'] # Store in data to avoid recomputing. if 'ledger_type_all' not in data: ledger_A = orm.pool.get('alternate_ledger.ledger_type').search( orm.cursor, orm.uid, [('name', '=', 'A')] ) data['ledger_type_all'] = ( ledger_A and ledger_A[0] in selected_ledgers ) catch_all = data['ledger_type_all'] if catch_all and account_ledgers == []: return True for selected_ledger in selected_ledgers: if selected_ledger in account_ledgers: return True return False def should_show_account(account, data): if 'account_from' not in data['form'] or 'account_to' not in data['form']: return True low = data['form']['account_from'] high = data['form']['account_to'] return low <= account.code <= high
Make the ledger type selector work
Make the ledger type selector work
Python
agpl-3.0
xcgd/account_report_webkit,xcgd/account_report_webkit,lithint/account_report_webkit,lithint/account_report_webkit
def compare_ledger_types(account, data, orm): # TODO alternate_ledger return True account_ledgers = [ledger.id for ledger in account.ledger_types] selected_ledger = int(data['form']['ledger_type']) # Store in data to avoid recomputing. if 'ledger_type_all' not in data: data['ledger_type_all'] = ( orm.pool.get('alternate_ledger.ledger_type').browse( orm.cursor, orm.uid, selected_ledger).name == 'A') catch_all = data['ledger_type_all'] return (selected_ledger in account_ledgers or (catch_all and account_ledgers == [])) def should_show_account(account, data): if 'account_from' not in data['form'] or 'account_to' not in data['form']: return True low = data['form']['account_from'] high = data['form']['account_to'] return low <= account.code <= high Make the ledger type selector work
def compare_ledger_types(account, data, orm): account_ledgers = [ledger.id for ledger in account.ledger_types] selected_ledgers = data['form']['ledger_types'] # Store in data to avoid recomputing. if 'ledger_type_all' not in data: ledger_A = orm.pool.get('alternate_ledger.ledger_type').search( orm.cursor, orm.uid, [('name', '=', 'A')] ) data['ledger_type_all'] = ( ledger_A and ledger_A[0] in selected_ledgers ) catch_all = data['ledger_type_all'] if catch_all and account_ledgers == []: return True for selected_ledger in selected_ledgers: if selected_ledger in account_ledgers: return True return False def should_show_account(account, data): if 'account_from' not in data['form'] or 'account_to' not in data['form']: return True low = data['form']['account_from'] high = data['form']['account_to'] return low <= account.code <= high
<commit_before>def compare_ledger_types(account, data, orm): # TODO alternate_ledger return True account_ledgers = [ledger.id for ledger in account.ledger_types] selected_ledger = int(data['form']['ledger_type']) # Store in data to avoid recomputing. if 'ledger_type_all' not in data: data['ledger_type_all'] = ( orm.pool.get('alternate_ledger.ledger_type').browse( orm.cursor, orm.uid, selected_ledger).name == 'A') catch_all = data['ledger_type_all'] return (selected_ledger in account_ledgers or (catch_all and account_ledgers == [])) def should_show_account(account, data): if 'account_from' not in data['form'] or 'account_to' not in data['form']: return True low = data['form']['account_from'] high = data['form']['account_to'] return low <= account.code <= high <commit_msg>Make the ledger type selector work<commit_after>
def compare_ledger_types(account, data, orm): account_ledgers = [ledger.id for ledger in account.ledger_types] selected_ledgers = data['form']['ledger_types'] # Store in data to avoid recomputing. if 'ledger_type_all' not in data: ledger_A = orm.pool.get('alternate_ledger.ledger_type').search( orm.cursor, orm.uid, [('name', '=', 'A')] ) data['ledger_type_all'] = ( ledger_A and ledger_A[0] in selected_ledgers ) catch_all = data['ledger_type_all'] if catch_all and account_ledgers == []: return True for selected_ledger in selected_ledgers: if selected_ledger in account_ledgers: return True return False def should_show_account(account, data): if 'account_from' not in data['form'] or 'account_to' not in data['form']: return True low = data['form']['account_from'] high = data['form']['account_to'] return low <= account.code <= high
def compare_ledger_types(account, data, orm): # TODO alternate_ledger return True account_ledgers = [ledger.id for ledger in account.ledger_types] selected_ledger = int(data['form']['ledger_type']) # Store in data to avoid recomputing. if 'ledger_type_all' not in data: data['ledger_type_all'] = ( orm.pool.get('alternate_ledger.ledger_type').browse( orm.cursor, orm.uid, selected_ledger).name == 'A') catch_all = data['ledger_type_all'] return (selected_ledger in account_ledgers or (catch_all and account_ledgers == [])) def should_show_account(account, data): if 'account_from' not in data['form'] or 'account_to' not in data['form']: return True low = data['form']['account_from'] high = data['form']['account_to'] return low <= account.code <= high Make the ledger type selector workdef compare_ledger_types(account, data, orm): account_ledgers = [ledger.id for ledger in account.ledger_types] selected_ledgers = data['form']['ledger_types'] # Store in data to avoid recomputing. if 'ledger_type_all' not in data: ledger_A = orm.pool.get('alternate_ledger.ledger_type').search( orm.cursor, orm.uid, [('name', '=', 'A')] ) data['ledger_type_all'] = ( ledger_A and ledger_A[0] in selected_ledgers ) catch_all = data['ledger_type_all'] if catch_all and account_ledgers == []: return True for selected_ledger in selected_ledgers: if selected_ledger in account_ledgers: return True return False def should_show_account(account, data): if 'account_from' not in data['form'] or 'account_to' not in data['form']: return True low = data['form']['account_from'] high = data['form']['account_to'] return low <= account.code <= high
<commit_before>def compare_ledger_types(account, data, orm): # TODO alternate_ledger return True account_ledgers = [ledger.id for ledger in account.ledger_types] selected_ledger = int(data['form']['ledger_type']) # Store in data to avoid recomputing. if 'ledger_type_all' not in data: data['ledger_type_all'] = ( orm.pool.get('alternate_ledger.ledger_type').browse( orm.cursor, orm.uid, selected_ledger).name == 'A') catch_all = data['ledger_type_all'] return (selected_ledger in account_ledgers or (catch_all and account_ledgers == [])) def should_show_account(account, data): if 'account_from' not in data['form'] or 'account_to' not in data['form']: return True low = data['form']['account_from'] high = data['form']['account_to'] return low <= account.code <= high <commit_msg>Make the ledger type selector work<commit_after>def compare_ledger_types(account, data, orm): account_ledgers = [ledger.id for ledger in account.ledger_types] selected_ledgers = data['form']['ledger_types'] # Store in data to avoid recomputing. if 'ledger_type_all' not in data: ledger_A = orm.pool.get('alternate_ledger.ledger_type').search( orm.cursor, orm.uid, [('name', '=', 'A')] ) data['ledger_type_all'] = ( ledger_A and ledger_A[0] in selected_ledgers ) catch_all = data['ledger_type_all'] if catch_all and account_ledgers == []: return True for selected_ledger in selected_ledgers: if selected_ledger in account_ledgers: return True return False def should_show_account(account, data): if 'account_from' not in data['form'] or 'account_to' not in data['form']: return True low = data['form']['account_from'] high = data['form']['account_to'] return low <= account.code <= high
a7b1bc006c23f534820fe06dea2da3b6553b64df
shcol/config.py
shcol/config.py
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = sys.platform.startswith('win') PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = 'windows' in os.getenv('os', '').lower() PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout
Use environment variable to detect Windows systems.
Use environment variable to detect Windows systems.
Python
bsd-2-clause
seblin/shcol
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = sys.platform.startswith('win') PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout Use environment variable to detect Windows systems.
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = 'windows' in os.getenv('os', '').lower() PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout
<commit_before># -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = sys.platform.startswith('win') PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout <commit_msg>Use environment variable to detect Windows systems.<commit_after>
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = 'windows' in os.getenv('os', '').lower() PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = sys.platform.startswith('win') PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout Use environment variable to detect Windows systems.# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = 'windows' in os.getenv('os', '').lower() PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout
<commit_before># -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = sys.platform.startswith('win') PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout <commit_msg>Use environment variable to detect Windows systems.<commit_after># -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import os import sys ENCODING = sys.stdout.encoding or 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' MAKE_UNIQUE = False NEEDS_DECODING = (sys.version_info < (3, 0)) ON_WINDOWS = 'windows' in os.getenv('os', '').lower() PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout
19c46fd57e04a026c6e52e1be9ba265a82d651f1
walletname/__init__.py
walletname/__init__.py
__author__ = 'mdavid' import json import re import requests from blockexplorer.settings import WNS_URL_BASE WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$') TIMEOUT_IN_SECONDS = 20 def is_valid_wallet_name(string): return WALLET_NAME_RE.match(string) def lookup_wallet_name(wallet_name, currency='btc', wns_base=WNS_URL_BASE): assert is_valid_wallet_name(wallet_name) r = requests.get('%s/%s/%s' % (wns_base, wallet_name, currency), verify=True, timeout=TIMEOUT_IN_SECONDS) rdict = json.loads(r.text) if rdict.get('success', False) and rdict.get('wallet_name','') == wallet_name and rdict.get('currency','') == currency: return rdict.get('wallet_address') return None
__author__ = 'mdavid' import json import re import requests from blockexplorer.settings import WNS_URL_BASE WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$') TIMEOUT_IN_SECONDS = 20 def is_valid_wallet_name(string): return WALLET_NAME_RE.match(string) def lookup_wallet_name(wallet_name, currency='btc', wns_base=WNS_URL_BASE): assert is_valid_wallet_name(wallet_name) try: r = requests.get('%s/%s/%s' % (wns_base, wallet_name, currency), verify=True, timeout=TIMEOUT_IN_SECONDS) rdict = json.loads(r.text) if rdict.get('success', False) and rdict.get('wallet_name','') == wallet_name and rdict.get('currency','') == currency: return rdict.get('wallet_address') except: pass return None
Add try/except block around lookup in lookup_wallet_name function
Add try/except block around lookup in lookup_wallet_name function
Python
apache-2.0
ychaim/explorer,blockcypher/explorer,blockcypher/explorer,ychaim/explorer,ychaim/explorer,blockcypher/explorer
__author__ = 'mdavid' import json import re import requests from blockexplorer.settings import WNS_URL_BASE WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$') TIMEOUT_IN_SECONDS = 20 def is_valid_wallet_name(string): return WALLET_NAME_RE.match(string) def lookup_wallet_name(wallet_name, currency='btc', wns_base=WNS_URL_BASE): assert is_valid_wallet_name(wallet_name) r = requests.get('%s/%s/%s' % (wns_base, wallet_name, currency), verify=True, timeout=TIMEOUT_IN_SECONDS) rdict = json.loads(r.text) if rdict.get('success', False) and rdict.get('wallet_name','') == wallet_name and rdict.get('currency','') == currency: return rdict.get('wallet_address') return NoneAdd try/except block around lookup in lookup_wallet_name function
__author__ = 'mdavid' import json import re import requests from blockexplorer.settings import WNS_URL_BASE WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$') TIMEOUT_IN_SECONDS = 20 def is_valid_wallet_name(string): return WALLET_NAME_RE.match(string) def lookup_wallet_name(wallet_name, currency='btc', wns_base=WNS_URL_BASE): assert is_valid_wallet_name(wallet_name) try: r = requests.get('%s/%s/%s' % (wns_base, wallet_name, currency), verify=True, timeout=TIMEOUT_IN_SECONDS) rdict = json.loads(r.text) if rdict.get('success', False) and rdict.get('wallet_name','') == wallet_name and rdict.get('currency','') == currency: return rdict.get('wallet_address') except: pass return None
<commit_before>__author__ = 'mdavid' import json import re import requests from blockexplorer.settings import WNS_URL_BASE WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$') TIMEOUT_IN_SECONDS = 20 def is_valid_wallet_name(string): return WALLET_NAME_RE.match(string) def lookup_wallet_name(wallet_name, currency='btc', wns_base=WNS_URL_BASE): assert is_valid_wallet_name(wallet_name) r = requests.get('%s/%s/%s' % (wns_base, wallet_name, currency), verify=True, timeout=TIMEOUT_IN_SECONDS) rdict = json.loads(r.text) if rdict.get('success', False) and rdict.get('wallet_name','') == wallet_name and rdict.get('currency','') == currency: return rdict.get('wallet_address') return None<commit_msg>Add try/except block around lookup in lookup_wallet_name function<commit_after>
__author__ = 'mdavid' import json import re import requests from blockexplorer.settings import WNS_URL_BASE WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$') TIMEOUT_IN_SECONDS = 20 def is_valid_wallet_name(string): return WALLET_NAME_RE.match(string) def lookup_wallet_name(wallet_name, currency='btc', wns_base=WNS_URL_BASE): assert is_valid_wallet_name(wallet_name) try: r = requests.get('%s/%s/%s' % (wns_base, wallet_name, currency), verify=True, timeout=TIMEOUT_IN_SECONDS) rdict = json.loads(r.text) if rdict.get('success', False) and rdict.get('wallet_name','') == wallet_name and rdict.get('currency','') == currency: return rdict.get('wallet_address') except: pass return None
__author__ = 'mdavid' import json import re import requests from blockexplorer.settings import WNS_URL_BASE WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$') TIMEOUT_IN_SECONDS = 20 def is_valid_wallet_name(string): return WALLET_NAME_RE.match(string) def lookup_wallet_name(wallet_name, currency='btc', wns_base=WNS_URL_BASE): assert is_valid_wallet_name(wallet_name) r = requests.get('%s/%s/%s' % (wns_base, wallet_name, currency), verify=True, timeout=TIMEOUT_IN_SECONDS) rdict = json.loads(r.text) if rdict.get('success', False) and rdict.get('wallet_name','') == wallet_name and rdict.get('currency','') == currency: return rdict.get('wallet_address') return NoneAdd try/except block around lookup in lookup_wallet_name function__author__ = 'mdavid' import json import re import requests from blockexplorer.settings import WNS_URL_BASE WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$') TIMEOUT_IN_SECONDS = 20 def is_valid_wallet_name(string): return WALLET_NAME_RE.match(string) def lookup_wallet_name(wallet_name, currency='btc', wns_base=WNS_URL_BASE): assert is_valid_wallet_name(wallet_name) try: r = requests.get('%s/%s/%s' % (wns_base, wallet_name, currency), verify=True, timeout=TIMEOUT_IN_SECONDS) rdict = json.loads(r.text) if rdict.get('success', False) and rdict.get('wallet_name','') == wallet_name and rdict.get('currency','') == currency: return rdict.get('wallet_address') except: pass return None
<commit_before>__author__ = 'mdavid' import json import re import requests from blockexplorer.settings import WNS_URL_BASE WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$') TIMEOUT_IN_SECONDS = 20 def is_valid_wallet_name(string): return WALLET_NAME_RE.match(string) def lookup_wallet_name(wallet_name, currency='btc', wns_base=WNS_URL_BASE): assert is_valid_wallet_name(wallet_name) r = requests.get('%s/%s/%s' % (wns_base, wallet_name, currency), verify=True, timeout=TIMEOUT_IN_SECONDS) rdict = json.loads(r.text) if rdict.get('success', False) and rdict.get('wallet_name','') == wallet_name and rdict.get('currency','') == currency: return rdict.get('wallet_address') return None<commit_msg>Add try/except block around lookup in lookup_wallet_name function<commit_after>__author__ = 'mdavid' import json import re import requests from blockexplorer.settings import WNS_URL_BASE WALLET_NAME_RE = re.compile('^([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$') TIMEOUT_IN_SECONDS = 20 def is_valid_wallet_name(string): return WALLET_NAME_RE.match(string) def lookup_wallet_name(wallet_name, currency='btc', wns_base=WNS_URL_BASE): assert is_valid_wallet_name(wallet_name) try: r = requests.get('%s/%s/%s' % (wns_base, wallet_name, currency), verify=True, timeout=TIMEOUT_IN_SECONDS) rdict = json.loads(r.text) if rdict.get('success', False) and rdict.get('wallet_name','') == wallet_name and rdict.get('currency','') == currency: return rdict.get('wallet_address') except: pass return None
74faea73440c4ff8b94493d5864e23e3fae7a53f
core/observables/file.py
core/observables/file.py
from __future__ import unicode_literals from mongoengine import * from core.observables import Observable from core.observables import Hash class File(Observable): value = StringField(verbose_name="SHA256 hash") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
from __future__ import unicode_literals from flask import url_for from flask_mongoengine.wtf import model_form from mongoengine import * from core.observables import Observable from core.database import StringListField class File(Observable): value = StringField(verbose_name="Value") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] exclude_fields = Observable.exclude_fields + ['hashes', 'body'] @classmethod def get_form(klass): form = model_form(klass, exclude=klass.exclude_fields) form.filenames = StringListField("Filenames") return form @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
Clean up File edit view
Clean up File edit view
Python
apache-2.0
yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti
from __future__ import unicode_literals from mongoengine import * from core.observables import Observable from core.observables import Hash class File(Observable): value = StringField(verbose_name="SHA256 hash") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i Clean up File edit view
from __future__ import unicode_literals from flask import url_for from flask_mongoengine.wtf import model_form from mongoengine import * from core.observables import Observable from core.database import StringListField class File(Observable): value = StringField(verbose_name="Value") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] exclude_fields = Observable.exclude_fields + ['hashes', 'body'] @classmethod def get_form(klass): form = model_form(klass, exclude=klass.exclude_fields) form.filenames = StringListField("Filenames") return form @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
<commit_before>from __future__ import unicode_literals from mongoengine import * from core.observables import Observable from core.observables import Hash class File(Observable): value = StringField(verbose_name="SHA256 hash") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i <commit_msg>Clean up File edit view<commit_after>
from __future__ import unicode_literals from flask import url_for from flask_mongoengine.wtf import model_form from mongoengine import * from core.observables import Observable from core.database import StringListField class File(Observable): value = StringField(verbose_name="Value") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] exclude_fields = Observable.exclude_fields + ['hashes', 'body'] @classmethod def get_form(klass): form = model_form(klass, exclude=klass.exclude_fields) form.filenames = StringListField("Filenames") return form @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
from __future__ import unicode_literals from mongoengine import * from core.observables import Observable from core.observables import Hash class File(Observable): value = StringField(verbose_name="SHA256 hash") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i Clean up File edit viewfrom __future__ import unicode_literals from flask import url_for from flask_mongoengine.wtf import model_form from mongoengine import * from core.observables import Observable from core.database import StringListField class File(Observable): value = StringField(verbose_name="Value") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] exclude_fields = Observable.exclude_fields + ['hashes', 'body'] @classmethod def get_form(klass): form = model_form(klass, exclude=klass.exclude_fields) form.filenames = StringListField("Filenames") return form @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
<commit_before>from __future__ import unicode_literals from mongoengine import * from core.observables import Observable from core.observables import Hash class File(Observable): value = StringField(verbose_name="SHA256 hash") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i <commit_msg>Clean up File edit view<commit_after>from __future__ import unicode_literals from flask import url_for from flask_mongoengine.wtf import model_form from mongoengine import * from core.observables import Observable from core.database import StringListField class File(Observable): value = StringField(verbose_name="Value") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] exclude_fields = Observable.exclude_fields + ['hashes', 'body'] @classmethod def get_form(klass): form = model_form(klass, exclude=klass.exclude_fields) form.filenames = StringListField("Filenames") return form @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
b0362233c278ed37c8d10ccdd60388e0fa749b4a
etools/apps/pcs/constants.py
etools/apps/pcs/constants.py
# допустимое отклонение от начала часа для фиксации замера PERMISSIBLE_PREC = 3
# допустимое отклонение от начала часа для фиксации замера PERMISSIBLE_PREC = 5
Increase permessable interval to +- 5 min
Increase permessable interval to +- 5 min
Python
bsd-3-clause
Igelinmist/etools,Igelinmist/etools
# допустимое отклонение от начала часа для фиксации замера PERMISSIBLE_PREC = 3 Increase permessable interval to +- 5 min
# допустимое отклонение от начала часа для фиксации замера PERMISSIBLE_PREC = 5
<commit_before># допустимое отклонение от начала часа для фиксации замера PERMISSIBLE_PREC = 3 <commit_msg>Increase permessable interval to +- 5 min<commit_after>
# допустимое отклонение от начала часа для фиксации замера PERMISSIBLE_PREC = 5
# допустимое отклонение от начала часа для фиксации замера PERMISSIBLE_PREC = 3 Increase permessable interval to +- 5 min# допустимое отклонение от начала часа для фиксации замера PERMISSIBLE_PREC = 5
<commit_before># допустимое отклонение от начала часа для фиксации замера PERMISSIBLE_PREC = 3 <commit_msg>Increase permessable interval to +- 5 min<commit_after># допустимое отклонение от начала часа для фиксации замера PERMISSIBLE_PREC = 5
724d7235e546fb79009800700fd74328f8171b8c
src/etc/tidy.py
src/etc/tidy.py
#!/usr/bin/python import sys, fileinput, subprocess err=0 cols=78 try: result=subprocess.check_output([ "git", "config", "core.autocrlf" ]) autocrlf=result.strip() == b"true" except CalledProcessError: autocrlf=False def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if not autocrlf and line.find('\r') != -1: report_err("CR character") line_len = len(line)-2 if autocrlf else len(line)-1 if line_len > cols: report_err("line longer than %d chars" % cols) sys.exit(err)
#!/usr/bin/python import sys, fileinput err=0 cols=78 def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if line.find('\r') != -1: report_err("CR character") if len(line)-1 > cols: report_err("line longer than %d chars" % cols) sys.exit(err)
Revert "Don't complain about \r when core.autocrlf is on in Git"
Revert "Don't complain about \r when core.autocrlf is on in Git" This reverts commit 828afaa2fa4cc9e3e53bda0ae3073abfcfa151ca.
Python
apache-2.0
SiegeLord/rust,gifnksm/rust,kwantam/rust,defuz/rust,aidancully/rust,avdi/rust,sae-bom/rust,erickt/rust,pelmers/rust,avdi/rust,pythonesque/rust,Ryman/rust,carols10cents/rust,robertg/rust,aepsil0n/rust,kwantam/rust,jbclements/rust,aepsil0n/rust,kmcallister/rust,mihneadb/rust,andars/rust,pczarn/rust,pczarn/rust,krzysz00/rust,barosl/rust,richo/rust,omasanori/rust,LeoTestard/rust,rprichard/rust,0x73/rust,michaelballantyne/rust-gpu,sarojaba/rust-doc-korean,aneeshusa/rust,pelmers/rust,j16r/rust,P1start/rust,jroesch/rust,victorvde/rust,AerialX/rust,pshc/rust,SiegeLord/rust,kimroen/rust,mihneadb/rust,dinfuehr/rust,miniupnp/rust,gifnksm/rust,ktossell/rust,mdinger/rust,bombless/rust-docs-chinese,robertg/rust,michaelballantyne/rust-gpu,omasanori/rust,jashank/rust,KokaKiwi/rust,vhbit/rust,victorvde/rust,pythonesque/rust,seanrivera/rust,gifnksm/rust,servo/rust,j16r/rust,barosl/rust,P1start/rust,sae-bom/rust,TheNeikos/rust,AerialX/rust,michaelballantyne/rust-gpu,rohitjoshi/rust,robertg/rust,seanrivera/rust,l0kod/rust,michaelballantyne/rust-gpu,pshc/rust,vhbit/rust,hauleth/rust,aepsil0n/rust,pshc/rust,l0kod/rust,mdinger/rust,untitaker/rust,graydon/rust,aneeshusa/rust,ktossell/rust,defuz/rust,defuz/rust,aepsil0n/rust,pythonesque/rust,andars/rust,ebfull/rand,GBGamer/rust,KokaKiwi/rust,ktossell/rust,SiegeLord/rust,mihneadb/rust,barosl/rust,vhbit/rust,miniupnp/rust,reem/rust,aturon/rust,aturon/rust,Ryman/rust,carols10cents/rust,dwillmer/rust,GBGamer/rust,erickt/rust,quornian/rust,erickt/rust,P1start/rust,ebfull/rust,quornian/rust,ruud-v-a/rust,krzysz00/rust,omasanori/rust,aneeshusa/rust,vhbit/rust,cllns/rust,Ryman/rust,philyoon/rust,zaeleus/rust,mvdnes/rust,zaeleus/rust,jashank/rust,aneeshusa/rust,andars/rust,nwin/rust,kimroen/rust,jbclements/rust,miniupnp/rust,ejjeong/rust,XMPPwocky/rust,aturon/rust,nwin/rust,dwillmer/rust,kimroen/rust,kimroen/rust,nwin/rust,P1start/rust,quornian/rust,bombless/rust,aturon/rust,defuz/rust,barosl/rust,cllns/rust,jbclements/rust,ktossell/rust,j16r/rust,reem/rust,krzysz00/rust,richo/rust,ruud-v-a/rust,Ryman/rust,jroesch/rust,pczarn/rust,aturon/rust,XMPPwocky/rust,bombless/rust,TheNeikos/rust,pythonesque/rust,zachwick/rust,aneeshusa/rust,gifnksm/rust,sarojaba/rust-doc-korean,seanrivera/rust,AerialX/rust-rt-minimal,P1start/rust,KokaKiwi/rust,XMPPwocky/rust,dwillmer/rust,TheNeikos/rust,GBGamer/rust,waynenilsen/rand,servo/rust,aturon/rust,ruud-v-a/rust,kimroen/rust,aidancully/rust,emk/rust,AerialX/rust-rt-minimal,zachwick/rust,zubron/rust,mitsuhiko/rust,servo/rust,krzysz00/rust,miniupnp/rust,zubron/rust,robertg/rust,LeoTestard/rust,pczarn/rust,reem/rust,erickt/rust,zaeleus/rust,rprichard/rust,seanrivera/rust,omasanori/rust,AerialX/rust,fabricedesre/rust,jroesch/rust,philyoon/rust,mvdnes/rust,stepancheg/rust-ide-rust,AerialX/rust,LeoTestard/rust,stepancheg/rust-ide-rust,omasanori/rust,stepancheg/rust-ide-rust,GrahamDennis/rand,victorvde/rust,krzysz00/rust,hauleth/rust,nham/rust,jashank/rust,graydon/rust,jbclements/rust,servo/rust,jbclements/rust,ebfull/rust,servo/rust,pelmers/rust,krzysz00/rust,LeoTestard/rust,GBGamer/rust,sarojaba/rust-doc-korean,dwillmer/rust,stepancheg/rust-ide-rust,hauleth/rust,fabricedesre/rust,0x73/rust,jroesch/rust,mvdnes/rust,ruud-v-a/rust,michaelballantyne/rust-gpu,cllns/rust,miniupnp/rust,kwantam/rust,miniupnp/rust,untitaker/rust,richo/rust,hauleth/rust,mahkoh/rust,kimroen/rust,mahkoh/rust,jashank/rust,graydon/rust,mdinger/rust,defuz/rust,AerialX/rust-rt-minimal,aidancully/rust,LeoTestard/rust,kwantam/rust,quornian/rust,pelmers/rust,erickt/rust,avdi/rust,bhickey/rand,stepancheg/rust-ide-rust,carols10cents/rust,huonw/rand,cllns/rust,graydon/rust,andars/rust,kmcallister/rust,zubron/rust,dwillmer/rust,cllns/rust,vhbit/rust,zaeleus/rust,XMPPwocky/rust,cllns/rust,mahkoh/rust,aidancully/rust,mahkoh/rust,stepancheg/rust-ide-rust,jashank/rust,P1start/rust,GBGamer/rust,untitaker/rust,emk/rust,mihneadb/rust,SiegeLord/rust,bombless/rust,pczarn/rust,bombless/rust,carols10cents/rust,stepancheg/rust-ide-rust,jroesch/rust,jbclements/rust,emk/rust,kwantam/rust,j16r/rust,robertg/rust,seanrivera/rust,SiegeLord/rust,Ryman/rust,jroesch/rust,mvdnes/rust,aidancully/rust,richo/rust,untitaker/rust,hauleth/rust,0x73/rust,aepsil0n/rust,kmcallister/rust,AerialX/rust,emk/rust,pelmers/rust,emk/rust,zubron/rust,jbclements/rust,0x73/rust,LeoTestard/rust,dwillmer/rust,fabricedesre/rust,emk/rust,retep998/rand,jbclements/rust,GBGamer/rust,untitaker/rust,kmcallister/rust,jbclements/rust,jashank/rust,pythonesque/rust,AerialX/rust-rt-minimal,l0kod/rust,reem/rust,mitsuhiko/rust,nwin/rust,mitsuhiko/rust,kimroen/rust,rohitjoshi/rust,kmcallister/rust,AerialX/rust,erickt/rust,bombless/rust,bombless/rust,rprichard/rust,omasanori/rust,sarojaba/rust-doc-korean,achanda/rand,sae-bom/rust,andars/rust,nham/rust,kmcallister/rust,mitsuhiko/rust,ejjeong/rust,graydon/rust,philyoon/rust,zachwick/rust,ktossell/rust,victorvde/rust,dinfuehr/rust,AerialX/rust-rt-minimal,zachwick/rust,pelmers/rust,avdi/rust,pythonesque/rust,dinfuehr/rust,GBGamer/rust,mvdnes/rust,rohitjoshi/rust,quornian/rust,TheNeikos/rust,barosl/rust,pshc/rust,l0kod/rust,carols10cents/rust,mitsuhiko/rust,aturon/rust,P1start/rust,GBGamer/rust,defuz/rust,zaeleus/rust,nham/rust,ejjeong/rust,pythonesque/rust,reem/rust,jashank/rust,Ryman/rust,hauleth/rust,zaeleus/rust,SiegeLord/rust,barosl/rust,jashank/rust,servo/rust,sarojaba/rust-doc-korean,kmcallister/rust,aidancully/rust,mdinger/rust,nham/rust,philyoon/rust,servo/rust,SiegeLord/rust,jroesch/rust,KokaKiwi/rust,ktossell/rust,mdinger/rust,nwin/rust,untitaker/rust,avdi/rust,andars/rust,robertg/rust,sarojaba/rust-doc-korean,nham/rust,mitsuhiko/rust,dinfuehr/rust,j16r/rust,sae-bom/rust,mdinger/rust,philyoon/rust,pshc/rust,sae-bom/rust,nham/rust,Ryman/rust,zubron/rust,rprichard/rust,ejjeong/rust,mahkoh/rust,erickt/rust,ruud-v-a/rust,emk/rust,dwillmer/rust,mihneadb/rust,rohitjoshi/rust,pczarn/rust,sarojaba/rust-doc-korean,j16r/rust,TheNeikos/rust,AerialX/rust-rt-minimal,XMPPwocky/rust,dinfuehr/rust,nwin/rust,seanrivera/rust,0x73/rust,rprichard/rust,zubron/rust,shepmaster/rand,miniupnp/rust,l0kod/rust,KokaKiwi/rust,l0kod/rust,arthurprs/rand,0x73/rust,gifnksm/rust,mahkoh/rust,l0kod/rust,quornian/rust,KokaKiwi/rust,sae-bom/rust,nham/rust,fabricedesre/rust,richo/rust,pshc/rust,richo/rust,zachwick/rust,pshc/rust,fabricedesre/rust,ebfull/rust,barosl/rust,kwantam/rust,XMPPwocky/rust,nwin/rust,j16r/rust,reem/rust,victorvde/rust,ebfull/rust,rohitjoshi/rust,ejjeong/rust,gifnksm/rust,nwin/rust,miniupnp/rust,ebfull/rust,mitsuhiko/rust,philyoon/rust,l0kod/rust,vhbit/rust,jroesch/rust,rohitjoshi/rust,michaelballantyne/rust-gpu,zachwick/rust,pshc/rust,zubron/rust,bluss/rand,pczarn/rust,vhbit/rust,mihneadb/rust,ktossell/rust,michaelballantyne/rust-gpu,zubron/rust,dwillmer/rust,dinfuehr/rust,fabricedesre/rust,aneeshusa/rust,TheNeikos/rust,rprichard/rust,LeoTestard/rust,ejjeong/rust,carols10cents/rust,mvdnes/rust,graydon/rust,aepsil0n/rust,avdi/rust,fabricedesre/rust,ebfull/rust,victorvde/rust,0x73/rust,quornian/rust,ruud-v-a/rust,vhbit/rust
#!/usr/bin/python import sys, fileinput, subprocess err=0 cols=78 try: result=subprocess.check_output([ "git", "config", "core.autocrlf" ]) autocrlf=result.strip() == b"true" except CalledProcessError: autocrlf=False def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if not autocrlf and line.find('\r') != -1: report_err("CR character") line_len = len(line)-2 if autocrlf else len(line)-1 if line_len > cols: report_err("line longer than %d chars" % cols) sys.exit(err) Revert "Don't complain about \r when core.autocrlf is on in Git" This reverts commit 828afaa2fa4cc9e3e53bda0ae3073abfcfa151ca.
#!/usr/bin/python import sys, fileinput err=0 cols=78 def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if line.find('\r') != -1: report_err("CR character") if len(line)-1 > cols: report_err("line longer than %d chars" % cols) sys.exit(err)
<commit_before>#!/usr/bin/python import sys, fileinput, subprocess err=0 cols=78 try: result=subprocess.check_output([ "git", "config", "core.autocrlf" ]) autocrlf=result.strip() == b"true" except CalledProcessError: autocrlf=False def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if not autocrlf and line.find('\r') != -1: report_err("CR character") line_len = len(line)-2 if autocrlf else len(line)-1 if line_len > cols: report_err("line longer than %d chars" % cols) sys.exit(err) <commit_msg>Revert "Don't complain about \r when core.autocrlf is on in Git" This reverts commit 828afaa2fa4cc9e3e53bda0ae3073abfcfa151ca.<commit_after>
#!/usr/bin/python import sys, fileinput err=0 cols=78 def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if line.find('\r') != -1: report_err("CR character") if len(line)-1 > cols: report_err("line longer than %d chars" % cols) sys.exit(err)
#!/usr/bin/python import sys, fileinput, subprocess err=0 cols=78 try: result=subprocess.check_output([ "git", "config", "core.autocrlf" ]) autocrlf=result.strip() == b"true" except CalledProcessError: autocrlf=False def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if not autocrlf and line.find('\r') != -1: report_err("CR character") line_len = len(line)-2 if autocrlf else len(line)-1 if line_len > cols: report_err("line longer than %d chars" % cols) sys.exit(err) Revert "Don't complain about \r when core.autocrlf is on in Git" This reverts commit 828afaa2fa4cc9e3e53bda0ae3073abfcfa151ca.#!/usr/bin/python import sys, fileinput err=0 cols=78 def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if line.find('\r') != -1: report_err("CR character") if len(line)-1 > cols: report_err("line longer than %d chars" % cols) sys.exit(err)
<commit_before>#!/usr/bin/python import sys, fileinput, subprocess err=0 cols=78 try: result=subprocess.check_output([ "git", "config", "core.autocrlf" ]) autocrlf=result.strip() == b"true" except CalledProcessError: autocrlf=False def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if not autocrlf and line.find('\r') != -1: report_err("CR character") line_len = len(line)-2 if autocrlf else len(line)-1 if line_len > cols: report_err("line longer than %d chars" % cols) sys.exit(err) <commit_msg>Revert "Don't complain about \r when core.autocrlf is on in Git" This reverts commit 828afaa2fa4cc9e3e53bda0ae3073abfcfa151ca.<commit_after>#!/usr/bin/python import sys, fileinput err=0 cols=78 def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if line.find('\r') != -1: report_err("CR character") if len(line)-1 > cols: report_err("line longer than %d chars" % cols) sys.exit(err)
2805eb26865d7a12cbc0e6f7a71dbd99ba49224e
gem/templatetags/gem_tags.py
gem/templatetags/gem_tags.py
from django.template import Library from django.conf import settings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter('fieldtype') def fieldtype(field): return field.field.widget.__class__.__name__ @register.filter(name='smarttruncatechars') def smart_truncate_chars(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != ' ': truncd_val = truncd_val[:truncd_val.rfind(' ')] return truncd_val + '...' return value
from django.template import Library from django.conf import settings from gem.models import GemSettings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter() def get_bbm_app_id(request): return GemSettings.for_site(request.site).bbm_app_id @register.filter('fieldtype') def fieldtype(field): return field.field.widget.__class__.__name__ @register.filter(name='smarttruncatechars') def smart_truncate_chars(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != ' ': truncd_val = truncd_val[:truncd_val.rfind(' ')] return truncd_val + '...' return value
Create GEM filter to get BBM App ID
Create GEM filter to get BBM App ID
Python
bsd-2-clause
praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem
from django.template import Library from django.conf import settings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter('fieldtype') def fieldtype(field): return field.field.widget.__class__.__name__ @register.filter(name='smarttruncatechars') def smart_truncate_chars(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != ' ': truncd_val = truncd_val[:truncd_val.rfind(' ')] return truncd_val + '...' return value Create GEM filter to get BBM App ID
from django.template import Library from django.conf import settings from gem.models import GemSettings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter() def get_bbm_app_id(request): return GemSettings.for_site(request.site).bbm_app_id @register.filter('fieldtype') def fieldtype(field): return field.field.widget.__class__.__name__ @register.filter(name='smarttruncatechars') def smart_truncate_chars(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != ' ': truncd_val = truncd_val[:truncd_val.rfind(' ')] return truncd_val + '...' return value
<commit_before>from django.template import Library from django.conf import settings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter('fieldtype') def fieldtype(field): return field.field.widget.__class__.__name__ @register.filter(name='smarttruncatechars') def smart_truncate_chars(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != ' ': truncd_val = truncd_val[:truncd_val.rfind(' ')] return truncd_val + '...' return value <commit_msg>Create GEM filter to get BBM App ID<commit_after>
from django.template import Library from django.conf import settings from gem.models import GemSettings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter() def get_bbm_app_id(request): return GemSettings.for_site(request.site).bbm_app_id @register.filter('fieldtype') def fieldtype(field): return field.field.widget.__class__.__name__ @register.filter(name='smarttruncatechars') def smart_truncate_chars(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != ' ': truncd_val = truncd_val[:truncd_val.rfind(' ')] return truncd_val + '...' return value
from django.template import Library from django.conf import settings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter('fieldtype') def fieldtype(field): return field.field.widget.__class__.__name__ @register.filter(name='smarttruncatechars') def smart_truncate_chars(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != ' ': truncd_val = truncd_val[:truncd_val.rfind(' ')] return truncd_val + '...' return value Create GEM filter to get BBM App IDfrom django.template import Library from django.conf import settings from gem.models import GemSettings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter() def get_bbm_app_id(request): return GemSettings.for_site(request.site).bbm_app_id @register.filter('fieldtype') def fieldtype(field): return field.field.widget.__class__.__name__ @register.filter(name='smarttruncatechars') def smart_truncate_chars(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != ' ': truncd_val = truncd_val[:truncd_val.rfind(' ')] return truncd_val + '...' return value
<commit_before>from django.template import Library from django.conf import settings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter('fieldtype') def fieldtype(field): return field.field.widget.__class__.__name__ @register.filter(name='smarttruncatechars') def smart_truncate_chars(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != ' ': truncd_val = truncd_val[:truncd_val.rfind(' ')] return truncd_val + '...' return value <commit_msg>Create GEM filter to get BBM App ID<commit_after>from django.template import Library from django.conf import settings from gem.models import GemSettings register = Library() @register.simple_tag() def get_site_static_prefix(): return settings.SITE_STATIC_PREFIX @register.filter() def get_bbm_app_id(request): return GemSettings.for_site(request.site).bbm_app_id @register.filter('fieldtype') def fieldtype(field): return field.field.widget.__class__.__name__ @register.filter(name='smarttruncatechars') def smart_truncate_chars(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != ' ': truncd_val = truncd_val[:truncd_val.rfind(' ')] return truncd_val + '...' return value
062a2e41e6e605dad4d8a8dc23abaa50f8348595
start_server.py
start_server.py
#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from server.tsuserver import TsuServer3 # Idiotproof setup def check_pyyaml(): try: import yaml except ImportError: print("Couldn't import PyYAML. Installing it for you...") import pip pip.main(["install", "--user", "pyyaml"]) def main(): server = TsuServer3() server.start() if __name__ == '__main__': check_pyyaml() main()
#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from server.tsuserver import TsuServer3 # Idiotproof setup def check_pyyaml(): try: import yaml except ModuleNotFoundError: print("Couldn't import PyYAML. Installing it for you...") import pip pip.main(["install", "--user", "pyyaml"]) def main(): server = TsuServer3() server.start() if __name__ == '__main__': check_pyyaml() main()
Use ModuleNotFoundError instead of ImportError
Use ModuleNotFoundError instead of ImportError
Python
agpl-3.0
Attorney-Online-Engineering-Task-Force/tsuserver3,Mariomagistr/tsuserver3
#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from server.tsuserver import TsuServer3 # Idiotproof setup def check_pyyaml(): try: import yaml except ImportError: print("Couldn't import PyYAML. Installing it for you...") import pip pip.main(["install", "--user", "pyyaml"]) def main(): server = TsuServer3() server.start() if __name__ == '__main__': check_pyyaml() main() Use ModuleNotFoundError instead of ImportError
#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from server.tsuserver import TsuServer3 # Idiotproof setup def check_pyyaml(): try: import yaml except ModuleNotFoundError: print("Couldn't import PyYAML. Installing it for you...") import pip pip.main(["install", "--user", "pyyaml"]) def main(): server = TsuServer3() server.start() if __name__ == '__main__': check_pyyaml() main()
<commit_before>#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from server.tsuserver import TsuServer3 # Idiotproof setup def check_pyyaml(): try: import yaml except ImportError: print("Couldn't import PyYAML. Installing it for you...") import pip pip.main(["install", "--user", "pyyaml"]) def main(): server = TsuServer3() server.start() if __name__ == '__main__': check_pyyaml() main() <commit_msg>Use ModuleNotFoundError instead of ImportError<commit_after>
#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from server.tsuserver import TsuServer3 # Idiotproof setup def check_pyyaml(): try: import yaml except ModuleNotFoundError: print("Couldn't import PyYAML. Installing it for you...") import pip pip.main(["install", "--user", "pyyaml"]) def main(): server = TsuServer3() server.start() if __name__ == '__main__': check_pyyaml() main()
#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from server.tsuserver import TsuServer3 # Idiotproof setup def check_pyyaml(): try: import yaml except ImportError: print("Couldn't import PyYAML. Installing it for you...") import pip pip.main(["install", "--user", "pyyaml"]) def main(): server = TsuServer3() server.start() if __name__ == '__main__': check_pyyaml() main() Use ModuleNotFoundError instead of ImportError#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from server.tsuserver import TsuServer3 # Idiotproof setup def check_pyyaml(): try: import yaml except ModuleNotFoundError: print("Couldn't import PyYAML. Installing it for you...") import pip pip.main(["install", "--user", "pyyaml"]) def main(): server = TsuServer3() server.start() if __name__ == '__main__': check_pyyaml() main()
<commit_before>#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from server.tsuserver import TsuServer3 # Idiotproof setup def check_pyyaml(): try: import yaml except ImportError: print("Couldn't import PyYAML. Installing it for you...") import pip pip.main(["install", "--user", "pyyaml"]) def main(): server = TsuServer3() server.start() if __name__ == '__main__': check_pyyaml() main() <commit_msg>Use ModuleNotFoundError instead of ImportError<commit_after>#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from server.tsuserver import TsuServer3 # Idiotproof setup def check_pyyaml(): try: import yaml except ModuleNotFoundError: print("Couldn't import PyYAML. Installing it for you...") import pip pip.main(["install", "--user", "pyyaml"]) def main(): server = TsuServer3() server.start() if __name__ == '__main__': check_pyyaml() main()
eb98db3ceedca1a7dd043eb3579c35dd2257c2ee
test_seasurf.py
test_seasurf.py
import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) if __name__ == '__main__': unittest.main()
import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) # Methods for backwards compatibility with python 2.5 & 2.6 def assertIn(self, value, container): self.assertTrue(value in container) def assertIsNotNone(self, value): self.assertNotEqual(value, None) if __name__ == '__main__': unittest.main()
Make tests compatible with python 2.5 and 2.6.
Make tests compatible with python 2.5 and 2.6.
Python
bsd-3-clause
heamon7/flask-seasurf,killpanda/flask-seasurf
import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) if __name__ == '__main__': unittest.main() Make tests compatible with python 2.5 and 2.6.
import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) # Methods for backwards compatibility with python 2.5 & 2.6 def assertIn(self, value, container): self.assertTrue(value in container) def assertIsNotNone(self, value): self.assertNotEqual(value, None) if __name__ == '__main__': unittest.main()
<commit_before>import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) if __name__ == '__main__': unittest.main() <commit_msg>Make tests compatible with python 2.5 and 2.6.<commit_after>
import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) # Methods for backwards compatibility with python 2.5 & 2.6 def assertIn(self, value, container): self.assertTrue(value in container) def assertIsNotNone(self, value): self.assertNotEqual(value, None) if __name__ == '__main__': unittest.main()
import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) if __name__ == '__main__': unittest.main() Make tests compatible with python 2.5 and 2.6.import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) # Methods for backwards compatibility with python 2.5 & 2.6 def assertIn(self, value, container): self.assertTrue(value in container) def assertIsNotNone(self, value): self.assertNotEqual(value, None) if __name__ == '__main__': unittest.main()
<commit_before>import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) if __name__ == '__main__': unittest.main() <commit_msg>Make tests compatible with python 2.5 and 2.6.<commit_after>import unittest from flask import Flask from flaskext.seasurf import SeaSurf class SeaSurfTestCase(unittest.TestCase): def setUp(self): app = Flask(__name__) app.debug = True app.secret_key = 'hunter2' self.app = app csrf = SeaSurf(app) csrf._csrf_disable = False self.csrf = csrf @csrf.exempt @app.route('/foo', methods=['POST']) def foo(): return 'bar' @app.route('/bar', methods=['POST']) def bar(): return 'foo' def test_generate_token(self): self.assertIsNotNone(self.csrf._generate_token()) def test_unique_generation(self): token_a = self.csrf._generate_token() token_b = self.csrf._generate_token() self.assertNotEqual(token_a, token_b) def test_token_is_string(self): token = self.csrf._generate_token() self.assertEqual(type(token), str) def test_exempt_view(self): rv = self.app.test_client().post('/foo') self.assertIn('bar', rv.data) def test_token_validation(self): # should produce a logger warning rv = self.app.test_client().post('/bar') self.assertIn('403 Forbidden', rv.data) # Methods for backwards compatibility with python 2.5 & 2.6 def assertIn(self, value, container): self.assertTrue(value in container) def assertIsNotNone(self, value): self.assertNotEqual(value, None) if __name__ == '__main__': unittest.main()
5cf839df99a03299215db7c2f6d9a78ac724c155
src/rinoh/language/__init__.py
src/rinoh/language/__init__.py
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = [] for string_collection in language.strings.values(): lines.append("\n.. rubric:: {}\n" .format(type(string_collection).__name__)) for string in string_collection._strings: lines.append(":{}: {}".format(string.name, string_collection[string.name])) language.__doc__ = '\n'.join(lines)
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = ['Localized strings for {}'.format(language.name)] for string_collection in language.strings.values(): lines.append("\n.. rubric:: {}\n" .format(type(string_collection).__name__)) for string in string_collection._strings: lines.append(":{}: {}".format(string.name, string_collection[string.name])) language.__doc__ = '\n'.join(lines)
Fix the rendering of language instance docstrings
Fix the rendering of language instance docstrings
Python
agpl-3.0
brechtm/rinohtype,brechtm/rinohtype,brechtm/rinohtype
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = [] for string_collection in language.strings.values(): lines.append("\n.. rubric:: {}\n" .format(type(string_collection).__name__)) for string in string_collection._strings: lines.append(":{}: {}".format(string.name, string_collection[string.name])) language.__doc__ = '\n'.join(lines) Fix the rendering of language instance docstrings
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = ['Localized strings for {}'.format(language.name)] for string_collection in language.strings.values(): lines.append("\n.. rubric:: {}\n" .format(type(string_collection).__name__)) for string in string_collection._strings: lines.append(":{}: {}".format(string.name, string_collection[string.name])) language.__doc__ = '\n'.join(lines)
<commit_before># This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = [] for string_collection in language.strings.values(): lines.append("\n.. rubric:: {}\n" .format(type(string_collection).__name__)) for string in string_collection._strings: lines.append(":{}: {}".format(string.name, string_collection[string.name])) language.__doc__ = '\n'.join(lines) <commit_msg>Fix the rendering of language instance docstrings<commit_after>
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = ['Localized strings for {}'.format(language.name)] for string_collection in language.strings.values(): lines.append("\n.. rubric:: {}\n" .format(type(string_collection).__name__)) for string in string_collection._strings: lines.append(":{}: {}".format(string.name, string_collection[string.name])) language.__doc__ = '\n'.join(lines)
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = [] for string_collection in language.strings.values(): lines.append("\n.. rubric:: {}\n" .format(type(string_collection).__name__)) for string in string_collection._strings: lines.append(":{}: {}".format(string.name, string_collection[string.name])) language.__doc__ = '\n'.join(lines) Fix the rendering of language instance docstrings# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = ['Localized strings for {}'.format(language.name)] for string_collection in language.strings.values(): lines.append("\n.. rubric:: {}\n" .format(type(string_collection).__name__)) for string in string_collection._strings: lines.append(":{}: {}".format(string.name, string_collection[string.name])) language.__doc__ = '\n'.join(lines)
<commit_before># This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = [] for string_collection in language.strings.values(): lines.append("\n.. rubric:: {}\n" .format(type(string_collection).__name__)) for string in string_collection._strings: lines.append(":{}: {}".format(string.name, string_collection[string.name])) language.__doc__ = '\n'.join(lines) <commit_msg>Fix the rendering of language instance docstrings<commit_after># This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = ['Localized strings for {}'.format(language.name)] for string_collection in language.strings.values(): lines.append("\n.. rubric:: {}\n" .format(type(string_collection).__name__)) for string in string_collection._strings: lines.append(":{}: {}".format(string.name, string_collection[string.name])) language.__doc__ = '\n'.join(lines)
502ef2c155aeaed7a2b9a2e4ad0471f34ef3790f
app/utils/utilities.py
app/utils/utilities.py
from re import search from flask import g from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User from instance.config import Config auth = HTTPBasicAuth()
from re import search from flask import g from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User from instance.config import Config auth = HTTPBasicAuth() def validate_email(email): ''' Method to check that a valid email is provided ''' email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" return True if search(email_re, email) else False @auth.verify_token def verify_token(token=None): ''' Method to verify token ''' token = request.headers.get('x-access-token') user_id = User.verify_authentication_token(token) if user_id: g.current_user = User.query.filter_by(id=user.id).first() return True return False
Add validate_email and verify_token methods Methods to be used to: - check that a valid email is provided - check the token authenticity
Add validate_email and verify_token methods Methods to be used to: - check that a valid email is provided - check the token authenticity
Python
mit
Elbertbiggs360/buckelist-api
from re import search from flask import g from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User from instance.config import Config auth = HTTPBasicAuth()Add validate_email and verify_token methods Methods to be used to: - check that a valid email is provided - check the token authenticity
from re import search from flask import g from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User from instance.config import Config auth = HTTPBasicAuth() def validate_email(email): ''' Method to check that a valid email is provided ''' email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" return True if search(email_re, email) else False @auth.verify_token def verify_token(token=None): ''' Method to verify token ''' token = request.headers.get('x-access-token') user_id = User.verify_authentication_token(token) if user_id: g.current_user = User.query.filter_by(id=user.id).first() return True return False
<commit_before>from re import search from flask import g from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User from instance.config import Config auth = HTTPBasicAuth()<commit_msg>Add validate_email and verify_token methods Methods to be used to: - check that a valid email is provided - check the token authenticity<commit_after>
from re import search from flask import g from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User from instance.config import Config auth = HTTPBasicAuth() def validate_email(email): ''' Method to check that a valid email is provided ''' email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" return True if search(email_re, email) else False @auth.verify_token def verify_token(token=None): ''' Method to verify token ''' token = request.headers.get('x-access-token') user_id = User.verify_authentication_token(token) if user_id: g.current_user = User.query.filter_by(id=user.id).first() return True return False
from re import search from flask import g from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User from instance.config import Config auth = HTTPBasicAuth()Add validate_email and verify_token methods Methods to be used to: - check that a valid email is provided - check the token authenticityfrom re import search from flask import g from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User from instance.config import Config auth = HTTPBasicAuth() def validate_email(email): ''' Method to check that a valid email is provided ''' email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" return True if search(email_re, email) else False @auth.verify_token def verify_token(token=None): ''' Method to verify token ''' token = request.headers.get('x-access-token') user_id = User.verify_authentication_token(token) if user_id: g.current_user = User.query.filter_by(id=user.id).first() return True return False
<commit_before>from re import search from flask import g from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User from instance.config import Config auth = HTTPBasicAuth()<commit_msg>Add validate_email and verify_token methods Methods to be used to: - check that a valid email is provided - check the token authenticity<commit_after>from re import search from flask import g from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User from instance.config import Config auth = HTTPBasicAuth() def validate_email(email): ''' Method to check that a valid email is provided ''' email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" return True if search(email_re, email) else False @auth.verify_token def verify_token(token=None): ''' Method to verify token ''' token = request.headers.get('x-access-token') user_id = User.verify_authentication_token(token) if user_id: g.current_user = User.query.filter_by(id=user.id).first() return True return False
099545e7a68ef82af8e8db15dc21746553143310
statictemplate/management/commands/statictemplate.py
statictemplate/management/commands/statictemplate.py
# -*- coding: utf-8 -*- from contextlib import contextmanager from django.conf import settings try: from django.conf.urls.defaults import patterns, url, include except ImportError: from django.conf.urls import patterns, url, include # pragma: no cover from django.core.management.base import BaseCommand from django.shortcuts import render_to_response from django.template.context import RequestContext from django.test.client import Client @contextmanager def override_urlconf(): has_old = hasattr(settings, 'ROOT_URLCONF') old = getattr(settings, 'ROOT_URLCONF', None) settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate' yield if has_old: setattr(settings, 'ROOT_URLCONF', old) else: # pragma: no cover delattr(settings, 'ROOT_URLCONF') def make_static(template): with override_urlconf(): client = Client() response = client.get('/', {'template': template}) return response.content class Command(BaseCommand): def handle(self, template, **options): output = make_static(template) self.stdout.write(output) def render(request): template_name = request.GET['template'] return render_to_response(template_name, RequestContext(request)) urlpatterns = patterns('', url('^$', render), url('^others', include(settings.ROOT_URLCONF)) )
# -*- coding: utf-8 -*- from contextlib import contextmanager from django.conf import settings try: from django.conf.urls.defaults import patterns, url, include except ImportError: from django.conf.urls import patterns, url, include # pragma: no cover from django.core.management.base import BaseCommand from django.shortcuts import render_to_response from django.template.context import RequestContext from django.test.client import Client class InvalidResponseError(Exception): pass @contextmanager def override_urlconf(): has_old = hasattr(settings, 'ROOT_URLCONF') old = getattr(settings, 'ROOT_URLCONF', None) settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate' yield if has_old: setattr(settings, 'ROOT_URLCONF', old) else: # pragma: no cover delattr(settings, 'ROOT_URLCONF') def make_static(template): with override_urlconf(): client = Client() response = client.get('/', {'template': template}) if response.status_code != 200: raise InvalidResponseError( 'Response code was %d' % response.status_code ) return response.content class Command(BaseCommand): def handle(self, template, **options): output = make_static(template) self.stdout.write(output) def render(request): template_name = request.GET['template'] return render_to_response(template_name, RequestContext(request)) urlpatterns = patterns('', url('^$', render), url('^others', include(settings.ROOT_URLCONF)) )
Add verbose error for a meddling middleware
Add verbose error for a meddling middleware
Python
bsd-3-clause
ojii/django-statictemplate,bdon/django-statictemplate,yakky/django-statictemplate
# -*- coding: utf-8 -*- from contextlib import contextmanager from django.conf import settings try: from django.conf.urls.defaults import patterns, url, include except ImportError: from django.conf.urls import patterns, url, include # pragma: no cover from django.core.management.base import BaseCommand from django.shortcuts import render_to_response from django.template.context import RequestContext from django.test.client import Client @contextmanager def override_urlconf(): has_old = hasattr(settings, 'ROOT_URLCONF') old = getattr(settings, 'ROOT_URLCONF', None) settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate' yield if has_old: setattr(settings, 'ROOT_URLCONF', old) else: # pragma: no cover delattr(settings, 'ROOT_URLCONF') def make_static(template): with override_urlconf(): client = Client() response = client.get('/', {'template': template}) return response.content class Command(BaseCommand): def handle(self, template, **options): output = make_static(template) self.stdout.write(output) def render(request): template_name = request.GET['template'] return render_to_response(template_name, RequestContext(request)) urlpatterns = patterns('', url('^$', render), url('^others', include(settings.ROOT_URLCONF)) ) Add verbose error for a meddling middleware
# -*- coding: utf-8 -*- from contextlib import contextmanager from django.conf import settings try: from django.conf.urls.defaults import patterns, url, include except ImportError: from django.conf.urls import patterns, url, include # pragma: no cover from django.core.management.base import BaseCommand from django.shortcuts import render_to_response from django.template.context import RequestContext from django.test.client import Client class InvalidResponseError(Exception): pass @contextmanager def override_urlconf(): has_old = hasattr(settings, 'ROOT_URLCONF') old = getattr(settings, 'ROOT_URLCONF', None) settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate' yield if has_old: setattr(settings, 'ROOT_URLCONF', old) else: # pragma: no cover delattr(settings, 'ROOT_URLCONF') def make_static(template): with override_urlconf(): client = Client() response = client.get('/', {'template': template}) if response.status_code != 200: raise InvalidResponseError( 'Response code was %d' % response.status_code ) return response.content class Command(BaseCommand): def handle(self, template, **options): output = make_static(template) self.stdout.write(output) def render(request): template_name = request.GET['template'] return render_to_response(template_name, RequestContext(request)) urlpatterns = patterns('', url('^$', render), url('^others', include(settings.ROOT_URLCONF)) )
<commit_before># -*- coding: utf-8 -*- from contextlib import contextmanager from django.conf import settings try: from django.conf.urls.defaults import patterns, url, include except ImportError: from django.conf.urls import patterns, url, include # pragma: no cover from django.core.management.base import BaseCommand from django.shortcuts import render_to_response from django.template.context import RequestContext from django.test.client import Client @contextmanager def override_urlconf(): has_old = hasattr(settings, 'ROOT_URLCONF') old = getattr(settings, 'ROOT_URLCONF', None) settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate' yield if has_old: setattr(settings, 'ROOT_URLCONF', old) else: # pragma: no cover delattr(settings, 'ROOT_URLCONF') def make_static(template): with override_urlconf(): client = Client() response = client.get('/', {'template': template}) return response.content class Command(BaseCommand): def handle(self, template, **options): output = make_static(template) self.stdout.write(output) def render(request): template_name = request.GET['template'] return render_to_response(template_name, RequestContext(request)) urlpatterns = patterns('', url('^$', render), url('^others', include(settings.ROOT_URLCONF)) ) <commit_msg>Add verbose error for a meddling middleware<commit_after>
# -*- coding: utf-8 -*- from contextlib import contextmanager from django.conf import settings try: from django.conf.urls.defaults import patterns, url, include except ImportError: from django.conf.urls import patterns, url, include # pragma: no cover from django.core.management.base import BaseCommand from django.shortcuts import render_to_response from django.template.context import RequestContext from django.test.client import Client class InvalidResponseError(Exception): pass @contextmanager def override_urlconf(): has_old = hasattr(settings, 'ROOT_URLCONF') old = getattr(settings, 'ROOT_URLCONF', None) settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate' yield if has_old: setattr(settings, 'ROOT_URLCONF', old) else: # pragma: no cover delattr(settings, 'ROOT_URLCONF') def make_static(template): with override_urlconf(): client = Client() response = client.get('/', {'template': template}) if response.status_code != 200: raise InvalidResponseError( 'Response code was %d' % response.status_code ) return response.content class Command(BaseCommand): def handle(self, template, **options): output = make_static(template) self.stdout.write(output) def render(request): template_name = request.GET['template'] return render_to_response(template_name, RequestContext(request)) urlpatterns = patterns('', url('^$', render), url('^others', include(settings.ROOT_URLCONF)) )
# -*- coding: utf-8 -*- from contextlib import contextmanager from django.conf import settings try: from django.conf.urls.defaults import patterns, url, include except ImportError: from django.conf.urls import patterns, url, include # pragma: no cover from django.core.management.base import BaseCommand from django.shortcuts import render_to_response from django.template.context import RequestContext from django.test.client import Client @contextmanager def override_urlconf(): has_old = hasattr(settings, 'ROOT_URLCONF') old = getattr(settings, 'ROOT_URLCONF', None) settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate' yield if has_old: setattr(settings, 'ROOT_URLCONF', old) else: # pragma: no cover delattr(settings, 'ROOT_URLCONF') def make_static(template): with override_urlconf(): client = Client() response = client.get('/', {'template': template}) return response.content class Command(BaseCommand): def handle(self, template, **options): output = make_static(template) self.stdout.write(output) def render(request): template_name = request.GET['template'] return render_to_response(template_name, RequestContext(request)) urlpatterns = patterns('', url('^$', render), url('^others', include(settings.ROOT_URLCONF)) ) Add verbose error for a meddling middleware# -*- coding: utf-8 -*- from contextlib import contextmanager from django.conf import settings try: from django.conf.urls.defaults import patterns, url, include except ImportError: from django.conf.urls import patterns, url, include # pragma: no cover from django.core.management.base import BaseCommand from django.shortcuts import render_to_response from django.template.context import RequestContext from django.test.client import Client class InvalidResponseError(Exception): pass @contextmanager def override_urlconf(): has_old = hasattr(settings, 'ROOT_URLCONF') old = getattr(settings, 'ROOT_URLCONF', None) settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate' yield if has_old: setattr(settings, 'ROOT_URLCONF', old) else: # pragma: no cover delattr(settings, 'ROOT_URLCONF') def make_static(template): with override_urlconf(): client = Client() response = client.get('/', {'template': template}) if response.status_code != 200: raise InvalidResponseError( 'Response code was %d' % response.status_code ) return response.content class Command(BaseCommand): def handle(self, template, **options): output = make_static(template) self.stdout.write(output) def render(request): template_name = request.GET['template'] return render_to_response(template_name, RequestContext(request)) urlpatterns = patterns('', url('^$', render), url('^others', include(settings.ROOT_URLCONF)) )
<commit_before># -*- coding: utf-8 -*- from contextlib import contextmanager from django.conf import settings try: from django.conf.urls.defaults import patterns, url, include except ImportError: from django.conf.urls import patterns, url, include # pragma: no cover from django.core.management.base import BaseCommand from django.shortcuts import render_to_response from django.template.context import RequestContext from django.test.client import Client @contextmanager def override_urlconf(): has_old = hasattr(settings, 'ROOT_URLCONF') old = getattr(settings, 'ROOT_URLCONF', None) settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate' yield if has_old: setattr(settings, 'ROOT_URLCONF', old) else: # pragma: no cover delattr(settings, 'ROOT_URLCONF') def make_static(template): with override_urlconf(): client = Client() response = client.get('/', {'template': template}) return response.content class Command(BaseCommand): def handle(self, template, **options): output = make_static(template) self.stdout.write(output) def render(request): template_name = request.GET['template'] return render_to_response(template_name, RequestContext(request)) urlpatterns = patterns('', url('^$', render), url('^others', include(settings.ROOT_URLCONF)) ) <commit_msg>Add verbose error for a meddling middleware<commit_after># -*- coding: utf-8 -*- from contextlib import contextmanager from django.conf import settings try: from django.conf.urls.defaults import patterns, url, include except ImportError: from django.conf.urls import patterns, url, include # pragma: no cover from django.core.management.base import BaseCommand from django.shortcuts import render_to_response from django.template.context import RequestContext from django.test.client import Client class InvalidResponseError(Exception): pass @contextmanager def override_urlconf(): has_old = hasattr(settings, 'ROOT_URLCONF') old = getattr(settings, 'ROOT_URLCONF', None) settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate' yield if has_old: setattr(settings, 'ROOT_URLCONF', old) else: # pragma: no cover delattr(settings, 'ROOT_URLCONF') def make_static(template): with override_urlconf(): client = Client() response = client.get('/', {'template': template}) if response.status_code != 200: raise InvalidResponseError( 'Response code was %d' % response.status_code ) return response.content class Command(BaseCommand): def handle(self, template, **options): output = make_static(template) self.stdout.write(output) def render(request): template_name = request.GET['template'] return render_to_response(template_name, RequestContext(request)) urlpatterns = patterns('', url('^$', render), url('^others', include(settings.ROOT_URLCONF)) )
b528b2cf4379369da8277a0a1c904267b5c7cf6f
Lib/test/test_atexit.py
Lib/test/test_atexit.py
# Test the atexit module. from test_support import TESTFN, vereq import atexit import os input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
# Test the atexit module. from test_support import TESTFN, vereq import atexit import os import sys input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
Use sys.executable to run Python, as suggested by Neal Norwitz.
Use sys.executable to run Python, as suggested by Neal Norwitz.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
# Test the atexit module. from test_support import TESTFN, vereq import atexit import os input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname) Use sys.executable to run Python, as suggested by Neal Norwitz.
# Test the atexit module. from test_support import TESTFN, vereq import atexit import os import sys input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
<commit_before># Test the atexit module. from test_support import TESTFN, vereq import atexit import os input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname) <commit_msg>Use sys.executable to run Python, as suggested by Neal Norwitz.<commit_after>
# Test the atexit module. from test_support import TESTFN, vereq import atexit import os import sys input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
# Test the atexit module. from test_support import TESTFN, vereq import atexit import os input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname) Use sys.executable to run Python, as suggested by Neal Norwitz.# Test the atexit module. from test_support import TESTFN, vereq import atexit import os import sys input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
<commit_before># Test the atexit module. from test_support import TESTFN, vereq import atexit import os input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname) <commit_msg>Use sys.executable to run Python, as suggested by Neal Norwitz.<commit_after># Test the atexit module. from test_support import TESTFN, vereq import atexit import os import sys input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
4381c4cabbeb870f3fe18da4e7bbdee9a39c55fd
dotbot/config.py
dotbot/config.py
import yaml from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: with open(config_file_path) as fin: data = yaml.load(fin) return data except Exception as e: msg = string.indent_lines(str(e)) raise ReadingError('Could not read config file:\n%s' % msg) def get_config(self): return self._config class ReadingError(Exception): pass
import yaml from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: with open(config_file_path) as fin: data = yaml.safe_load(fin) return data except Exception as e: msg = string.indent_lines(str(e)) raise ReadingError('Could not read config file:\n%s' % msg) def get_config(self): return self._config class ReadingError(Exception): pass
Use `safe_load` function to load YAML
Use `safe_load` function to load YAML In our use case, we are *not* reading arbitrary input that could be malicious. Still, because we know that what we're reading is made up of only dictionaries and lists and not arbitrary Python objects, we might as well use the more restrictive `safe_load` function rather than the `load` function.
Python
mit
anishathalye/dotbot,pulgalipe/dotbot,pulgalipe/dotbot,imattman/dotbot,imattman/dotbot,pulgalipe/dotbot,bchretien/dotbot,imattman/dotbot,anishathalye/dotbot,bchretien/dotbot,bchretien/dotbot
import yaml from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: with open(config_file_path) as fin: data = yaml.load(fin) return data except Exception as e: msg = string.indent_lines(str(e)) raise ReadingError('Could not read config file:\n%s' % msg) def get_config(self): return self._config class ReadingError(Exception): pass Use `safe_load` function to load YAML In our use case, we are *not* reading arbitrary input that could be malicious. Still, because we know that what we're reading is made up of only dictionaries and lists and not arbitrary Python objects, we might as well use the more restrictive `safe_load` function rather than the `load` function.
import yaml from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: with open(config_file_path) as fin: data = yaml.safe_load(fin) return data except Exception as e: msg = string.indent_lines(str(e)) raise ReadingError('Could not read config file:\n%s' % msg) def get_config(self): return self._config class ReadingError(Exception): pass
<commit_before>import yaml from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: with open(config_file_path) as fin: data = yaml.load(fin) return data except Exception as e: msg = string.indent_lines(str(e)) raise ReadingError('Could not read config file:\n%s' % msg) def get_config(self): return self._config class ReadingError(Exception): pass <commit_msg>Use `safe_load` function to load YAML In our use case, we are *not* reading arbitrary input that could be malicious. Still, because we know that what we're reading is made up of only dictionaries and lists and not arbitrary Python objects, we might as well use the more restrictive `safe_load` function rather than the `load` function.<commit_after>
import yaml from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: with open(config_file_path) as fin: data = yaml.safe_load(fin) return data except Exception as e: msg = string.indent_lines(str(e)) raise ReadingError('Could not read config file:\n%s' % msg) def get_config(self): return self._config class ReadingError(Exception): pass
import yaml from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: with open(config_file_path) as fin: data = yaml.load(fin) return data except Exception as e: msg = string.indent_lines(str(e)) raise ReadingError('Could not read config file:\n%s' % msg) def get_config(self): return self._config class ReadingError(Exception): pass Use `safe_load` function to load YAML In our use case, we are *not* reading arbitrary input that could be malicious. Still, because we know that what we're reading is made up of only dictionaries and lists and not arbitrary Python objects, we might as well use the more restrictive `safe_load` function rather than the `load` function.import yaml from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: with open(config_file_path) as fin: data = yaml.safe_load(fin) return data except Exception as e: msg = string.indent_lines(str(e)) raise ReadingError('Could not read config file:\n%s' % msg) def get_config(self): return self._config class ReadingError(Exception): pass
<commit_before>import yaml from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: with open(config_file_path) as fin: data = yaml.load(fin) return data except Exception as e: msg = string.indent_lines(str(e)) raise ReadingError('Could not read config file:\n%s' % msg) def get_config(self): return self._config class ReadingError(Exception): pass <commit_msg>Use `safe_load` function to load YAML In our use case, we are *not* reading arbitrary input that could be malicious. Still, because we know that what we're reading is made up of only dictionaries and lists and not arbitrary Python objects, we might as well use the more restrictive `safe_load` function rather than the `load` function.<commit_after>import yaml from .util import string class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: with open(config_file_path) as fin: data = yaml.safe_load(fin) return data except Exception as e: msg = string.indent_lines(str(e)) raise ReadingError('Could not read config file:\n%s' % msg) def get_config(self): return self._config class ReadingError(Exception): pass
4409823a5611d0f426ca09541d7e9dc982bc8c9f
asyncqlio/utils.py
asyncqlio/utils.py
""" Miscellaneous utilities used throughout the library. """ import collections.abc class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator): """ Transforms an `__iter__` method into an `__aiter__` method. """ def __init__(self, iterator: collections.abc.Iterator): self._it = iterator # magic methods def __iter__(self): return self def __next__(self): return self._it.__next__() def __aiter__(self): return self async def __anext__(self): return self.__next__() def iter_to_aiter(type_): """ Transforms a normal iterable type into an async iterable type. """ def __aiter__(self): return IterToAiter(iter(self)) type_.__aiter__ = __aiter__ return type_
""" Miscellaneous utilities used throughout the library. """ import collections.abc class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator): """ Transforms an `__iter__` method into an `__aiter__` method. """ def __init__(self, iterator: collections.abc.Iterator): self._it = iterator # magic methods def __iter__(self): return self def __next__(self): return self._it.__next__() def __aiter__(self): return self async def __anext__(self): try: return self.__next__() except StopIteration: raise StopAsyncIteration def iter_to_aiter(type_): """ Transforms a normal iterable type into an async iterable type. """ def __aiter__(self): return IterToAiter(iter(self)) type_.__aiter__ = __aiter__ return type_
Raise StopAsyncIteration instead of StopAsyncIteration in aiter wrapper.
Raise StopAsyncIteration instead of StopAsyncIteration in aiter wrapper.
Python
mit
SunDwarf/asyncqlio
""" Miscellaneous utilities used throughout the library. """ import collections.abc class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator): """ Transforms an `__iter__` method into an `__aiter__` method. """ def __init__(self, iterator: collections.abc.Iterator): self._it = iterator # magic methods def __iter__(self): return self def __next__(self): return self._it.__next__() def __aiter__(self): return self async def __anext__(self): return self.__next__() def iter_to_aiter(type_): """ Transforms a normal iterable type into an async iterable type. """ def __aiter__(self): return IterToAiter(iter(self)) type_.__aiter__ = __aiter__ return type_ Raise StopAsyncIteration instead of StopAsyncIteration in aiter wrapper.
""" Miscellaneous utilities used throughout the library. """ import collections.abc class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator): """ Transforms an `__iter__` method into an `__aiter__` method. """ def __init__(self, iterator: collections.abc.Iterator): self._it = iterator # magic methods def __iter__(self): return self def __next__(self): return self._it.__next__() def __aiter__(self): return self async def __anext__(self): try: return self.__next__() except StopIteration: raise StopAsyncIteration def iter_to_aiter(type_): """ Transforms a normal iterable type into an async iterable type. """ def __aiter__(self): return IterToAiter(iter(self)) type_.__aiter__ = __aiter__ return type_
<commit_before>""" Miscellaneous utilities used throughout the library. """ import collections.abc class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator): """ Transforms an `__iter__` method into an `__aiter__` method. """ def __init__(self, iterator: collections.abc.Iterator): self._it = iterator # magic methods def __iter__(self): return self def __next__(self): return self._it.__next__() def __aiter__(self): return self async def __anext__(self): return self.__next__() def iter_to_aiter(type_): """ Transforms a normal iterable type into an async iterable type. """ def __aiter__(self): return IterToAiter(iter(self)) type_.__aiter__ = __aiter__ return type_ <commit_msg>Raise StopAsyncIteration instead of StopAsyncIteration in aiter wrapper.<commit_after>
""" Miscellaneous utilities used throughout the library. """ import collections.abc class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator): """ Transforms an `__iter__` method into an `__aiter__` method. """ def __init__(self, iterator: collections.abc.Iterator): self._it = iterator # magic methods def __iter__(self): return self def __next__(self): return self._it.__next__() def __aiter__(self): return self async def __anext__(self): try: return self.__next__() except StopIteration: raise StopAsyncIteration def iter_to_aiter(type_): """ Transforms a normal iterable type into an async iterable type. """ def __aiter__(self): return IterToAiter(iter(self)) type_.__aiter__ = __aiter__ return type_
""" Miscellaneous utilities used throughout the library. """ import collections.abc class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator): """ Transforms an `__iter__` method into an `__aiter__` method. """ def __init__(self, iterator: collections.abc.Iterator): self._it = iterator # magic methods def __iter__(self): return self def __next__(self): return self._it.__next__() def __aiter__(self): return self async def __anext__(self): return self.__next__() def iter_to_aiter(type_): """ Transforms a normal iterable type into an async iterable type. """ def __aiter__(self): return IterToAiter(iter(self)) type_.__aiter__ = __aiter__ return type_ Raise StopAsyncIteration instead of StopAsyncIteration in aiter wrapper.""" Miscellaneous utilities used throughout the library. """ import collections.abc class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator): """ Transforms an `__iter__` method into an `__aiter__` method. """ def __init__(self, iterator: collections.abc.Iterator): self._it = iterator # magic methods def __iter__(self): return self def __next__(self): return self._it.__next__() def __aiter__(self): return self async def __anext__(self): try: return self.__next__() except StopIteration: raise StopAsyncIteration def iter_to_aiter(type_): """ Transforms a normal iterable type into an async iterable type. """ def __aiter__(self): return IterToAiter(iter(self)) type_.__aiter__ = __aiter__ return type_
<commit_before>""" Miscellaneous utilities used throughout the library. """ import collections.abc class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator): """ Transforms an `__iter__` method into an `__aiter__` method. """ def __init__(self, iterator: collections.abc.Iterator): self._it = iterator # magic methods def __iter__(self): return self def __next__(self): return self._it.__next__() def __aiter__(self): return self async def __anext__(self): return self.__next__() def iter_to_aiter(type_): """ Transforms a normal iterable type into an async iterable type. """ def __aiter__(self): return IterToAiter(iter(self)) type_.__aiter__ = __aiter__ return type_ <commit_msg>Raise StopAsyncIteration instead of StopAsyncIteration in aiter wrapper.<commit_after>""" Miscellaneous utilities used throughout the library. """ import collections.abc class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator): """ Transforms an `__iter__` method into an `__aiter__` method. """ def __init__(self, iterator: collections.abc.Iterator): self._it = iterator # magic methods def __iter__(self): return self def __next__(self): return self._it.__next__() def __aiter__(self): return self async def __anext__(self): try: return self.__next__() except StopIteration: raise StopAsyncIteration def iter_to_aiter(type_): """ Transforms a normal iterable type into an async iterable type. """ def __aiter__(self): return IterToAiter(iter(self)) type_.__aiter__ = __aiter__ return type_
f1cf2d2e9cbdd4182a5a755b5958e499fc9d9585
gcloud_expenses/views.py
gcloud_expenses/views.py
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': list_reports(employee_id), } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': get_report_info(employee_id, report_id)} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, )
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} def fixup_report(report): if report['status'] == 'paid': report['status'] = 'paid, check #%s' % report.pop('memo') elif report['status'] == 'rejected': report['status'] = 'rejected, #%s' % report.pop('memo') return report @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': [fixup_report(report) for report in list_reports(employee_id)], } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': fixup_report(get_report_info(employee_id, report_id))} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, )
Improve status display for reports.
Improve status display for reports.
Python
apache-2.0
GoogleCloudPlatform/google-cloud-python-expenses-demo,GoogleCloudPlatform/google-cloud-python-expenses-demo
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': list_reports(employee_id), } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': get_report_info(employee_id, report_id)} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, ) Improve status display for reports.
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} def fixup_report(report): if report['status'] == 'paid': report['status'] = 'paid, check #%s' % report.pop('memo') elif report['status'] == 'rejected': report['status'] = 'rejected, #%s' % report.pop('memo') return report @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': [fixup_report(report) for report in list_reports(employee_id)], } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': fixup_report(get_report_info(employee_id, report_id))} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, )
<commit_before>from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': list_reports(employee_id), } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': get_report_info(employee_id, report_id)} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, ) <commit_msg>Improve status display for reports.<commit_after>
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} def fixup_report(report): if report['status'] == 'paid': report['status'] = 'paid, check #%s' % report.pop('memo') elif report['status'] == 'rejected': report['status'] = 'rejected, #%s' % report.pop('memo') return report @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': [fixup_report(report) for report in list_reports(employee_id)], } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': fixup_report(get_report_info(employee_id, report_id))} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, )
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': list_reports(employee_id), } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': get_report_info(employee_id, report_id)} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, ) Improve status display for reports.from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} def fixup_report(report): if report['status'] == 'paid': report['status'] = 'paid, check #%s' % report.pop('memo') elif report['status'] == 'rejected': report['status'] = 'rejected, #%s' % report.pop('memo') return report @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': [fixup_report(report) for report in list_reports(employee_id)], } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': fixup_report(get_report_info(employee_id, report_id))} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, )
<commit_before>from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': list_reports(employee_id), } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': get_report_info(employee_id, report_id)} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, ) <commit_msg>Improve status display for reports.<commit_after>from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} def fixup_report(report): if report['status'] == 'paid': report['status'] = 'paid, check #%s' % report.pop('memo') elif report['status'] == 'rejected': report['status'] = 'rejected, #%s' % report.pop('memo') return report @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': [fixup_report(report) for report in list_reports(employee_id)], } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': fixup_report(get_report_info(employee_id, report_id))} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, )
737e2877cfad9ea801641b72094633a7c0178a44
UM/Settings/__init__.py
UM/Settings/__init__.py
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from .SettingDefinition import SettingDefinition from .SettingInstance import SettingInstance from .DefinitionContainer import DefinitionContainer from .InstanceContainer import InstanceContainer from .ContainerStack import ContainerStack from .Validator import Validator
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from .ContainerRegistry import ContainerRegistry from .SettingDefinition import SettingDefinition from .SettingInstance import SettingInstance from .DefinitionContainer import DefinitionContainer from .InstanceContainer import InstanceContainer from .ContainerStack import ContainerStack from .Validator import Validator
Add ContainerRegistry to the exposed classes of UM.Settings
Add ContainerRegistry to the exposed classes of UM.Settings
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from .SettingDefinition import SettingDefinition from .SettingInstance import SettingInstance from .DefinitionContainer import DefinitionContainer from .InstanceContainer import InstanceContainer from .ContainerStack import ContainerStack from .Validator import Validator Add ContainerRegistry to the exposed classes of UM.Settings
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from .ContainerRegistry import ContainerRegistry from .SettingDefinition import SettingDefinition from .SettingInstance import SettingInstance from .DefinitionContainer import DefinitionContainer from .InstanceContainer import InstanceContainer from .ContainerStack import ContainerStack from .Validator import Validator
<commit_before># Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from .SettingDefinition import SettingDefinition from .SettingInstance import SettingInstance from .DefinitionContainer import DefinitionContainer from .InstanceContainer import InstanceContainer from .ContainerStack import ContainerStack from .Validator import Validator <commit_msg>Add ContainerRegistry to the exposed classes of UM.Settings<commit_after>
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from .ContainerRegistry import ContainerRegistry from .SettingDefinition import SettingDefinition from .SettingInstance import SettingInstance from .DefinitionContainer import DefinitionContainer from .InstanceContainer import InstanceContainer from .ContainerStack import ContainerStack from .Validator import Validator
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from .SettingDefinition import SettingDefinition from .SettingInstance import SettingInstance from .DefinitionContainer import DefinitionContainer from .InstanceContainer import InstanceContainer from .ContainerStack import ContainerStack from .Validator import Validator Add ContainerRegistry to the exposed classes of UM.Settings# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from .ContainerRegistry import ContainerRegistry from .SettingDefinition import SettingDefinition from .SettingInstance import SettingInstance from .DefinitionContainer import DefinitionContainer from .InstanceContainer import InstanceContainer from .ContainerStack import ContainerStack from .Validator import Validator
<commit_before># Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from .SettingDefinition import SettingDefinition from .SettingInstance import SettingInstance from .DefinitionContainer import DefinitionContainer from .InstanceContainer import InstanceContainer from .ContainerStack import ContainerStack from .Validator import Validator <commit_msg>Add ContainerRegistry to the exposed classes of UM.Settings<commit_after># Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from .ContainerRegistry import ContainerRegistry from .SettingDefinition import SettingDefinition from .SettingInstance import SettingInstance from .DefinitionContainer import DefinitionContainer from .InstanceContainer import InstanceContainer from .ContainerStack import ContainerStack from .Validator import Validator
d8965e937a0f5b649c80c9ac14a3d5652d5a1859
getContentFromURL.py
getContentFromURL.py
# Team nameSpace@HINT2017 # # This script contains a function which takes a URL as input # and returns the content of the content in the webpage # 'newspaper' library is used here to extract only the main # content in a webpage from flask import Flask,render_template import urllib from newspaper import Article app = Flask(__name__) @app.route('/<name>') def failurl(name): return "Please enter a valid url" @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def getContentFromURL(path): article = Article(path) article.download() article.parse() article.nlp() article.summary return article.summary if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
# Team nameSpace@HINT2017 # # This script contains a function which takes a URL as input # and returns the content of the content in the webpage # 'newspaper' library is used here to extract only the main # content in a webpage from flask import Flask,render_template import urllib from newspaper import Article app = Flask(__name__) @app.route('/<name>') def failurl(name): return "Please enter a valid url" @app.route('/', defaults={'path': ''}) @app.route('/<path:url>') def getContentFromURL(url): article = Article(url) article.download() article.parse() article.nlp() article.summary strKeyword = "" for item in article.keywords: strKeyword += item + " " return strKeyword if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
Return keywords instead of summary
Return keywords instead of summary
Python
mit
urdarinda/LISTS,urdarinda/LISTS,urdarinda/LISTS
# Team nameSpace@HINT2017 # # This script contains a function which takes a URL as input # and returns the content of the content in the webpage # 'newspaper' library is used here to extract only the main # content in a webpage from flask import Flask,render_template import urllib from newspaper import Article app = Flask(__name__) @app.route('/<name>') def failurl(name): return "Please enter a valid url" @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def getContentFromURL(path): article = Article(path) article.download() article.parse() article.nlp() article.summary return article.summary if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') Return keywords instead of summary
# Team nameSpace@HINT2017 # # This script contains a function which takes a URL as input # and returns the content of the content in the webpage # 'newspaper' library is used here to extract only the main # content in a webpage from flask import Flask,render_template import urllib from newspaper import Article app = Flask(__name__) @app.route('/<name>') def failurl(name): return "Please enter a valid url" @app.route('/', defaults={'path': ''}) @app.route('/<path:url>') def getContentFromURL(url): article = Article(url) article.download() article.parse() article.nlp() article.summary strKeyword = "" for item in article.keywords: strKeyword += item + " " return strKeyword if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
<commit_before># Team nameSpace@HINT2017 # # This script contains a function which takes a URL as input # and returns the content of the content in the webpage # 'newspaper' library is used here to extract only the main # content in a webpage from flask import Flask,render_template import urllib from newspaper import Article app = Flask(__name__) @app.route('/<name>') def failurl(name): return "Please enter a valid url" @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def getContentFromURL(path): article = Article(path) article.download() article.parse() article.nlp() article.summary return article.summary if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') <commit_msg>Return keywords instead of summary<commit_after>
# Team nameSpace@HINT2017 # # This script contains a function which takes a URL as input # and returns the content of the content in the webpage # 'newspaper' library is used here to extract only the main # content in a webpage from flask import Flask,render_template import urllib from newspaper import Article app = Flask(__name__) @app.route('/<name>') def failurl(name): return "Please enter a valid url" @app.route('/', defaults={'path': ''}) @app.route('/<path:url>') def getContentFromURL(url): article = Article(url) article.download() article.parse() article.nlp() article.summary strKeyword = "" for item in article.keywords: strKeyword += item + " " return strKeyword if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
# Team nameSpace@HINT2017 # # This script contains a function which takes a URL as input # and returns the content of the content in the webpage # 'newspaper' library is used here to extract only the main # content in a webpage from flask import Flask,render_template import urllib from newspaper import Article app = Flask(__name__) @app.route('/<name>') def failurl(name): return "Please enter a valid url" @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def getContentFromURL(path): article = Article(path) article.download() article.parse() article.nlp() article.summary return article.summary if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') Return keywords instead of summary# Team nameSpace@HINT2017 # # This script contains a function which takes a URL as input # and returns the content of the content in the webpage # 'newspaper' library is used here to extract only the main # content in a webpage from flask import Flask,render_template import urllib from newspaper import Article app = Flask(__name__) @app.route('/<name>') def failurl(name): return "Please enter a valid url" @app.route('/', defaults={'path': ''}) @app.route('/<path:url>') def getContentFromURL(url): article = Article(url) article.download() article.parse() article.nlp() article.summary strKeyword = "" for item in article.keywords: strKeyword += item + " " return strKeyword if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
<commit_before># Team nameSpace@HINT2017 # # This script contains a function which takes a URL as input # and returns the content of the content in the webpage # 'newspaper' library is used here to extract only the main # content in a webpage from flask import Flask,render_template import urllib from newspaper import Article app = Flask(__name__) @app.route('/<name>') def failurl(name): return "Please enter a valid url" @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def getContentFromURL(path): article = Article(path) article.download() article.parse() article.nlp() article.summary return article.summary if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') <commit_msg>Return keywords instead of summary<commit_after># Team nameSpace@HINT2017 # # This script contains a function which takes a URL as input # and returns the content of the content in the webpage # 'newspaper' library is used here to extract only the main # content in a webpage from flask import Flask,render_template import urllib from newspaper import Article app = Flask(__name__) @app.route('/<name>') def failurl(name): return "Please enter a valid url" @app.route('/', defaults={'path': ''}) @app.route('/<path:url>') def getContentFromURL(url): article = Article(url) article.download() article.parse() article.nlp() article.summary strKeyword = "" for item in article.keywords: strKeyword += item + " " return strKeyword if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
243bb615c579c0598a2f2be5791d3d5092dcd556
invoice/tasks.py
invoice/tasks.py
# -*- encoding: utf-8 -*- import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '<table border="0">' for d, summary in report.items(): message = message + '<tr colspan="3">' message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A')) message = message + '</tr>' for ticket in summary['tickets']: message = message + '<tr>' message = message + '<td>{}</td>'.format(ticket['pk']) message = message + '<td>{}, {}</td>'.format( ticket['contact'], ticket['description'], ) message = message + '<td>{}</td>'.format( ticket['format_minutes'], ) message = message + '</tr>' message = message + '<tr>' message = message + '<td></td><td></td>' message = message + '<td><b>{}</b></td>'.format( summary['format_total'] ) message = message + '</tr>' message = message + '</table>' queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay()
# -*- encoding: utf-8 -*- import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '' for d, summary in report.items(): message = message + '\n\n{}, total time {}'.format( d.strftime('%d/%m/%Y %A'), summary['format_total'], ) for ticket in summary['tickets']: message = message + '\n{}: {}, {} ({})'.format( ticket['pk'], ticket['contact'], ticket['description'], ticket['format_minutes'], ) queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay()
Remove HTML table (our mail cannot send HTML)
Remove HTML table (our mail cannot send HTML)
Python
apache-2.0
pkimber/invoice,pkimber/invoice,pkimber/invoice
# -*- encoding: utf-8 -*- import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '<table border="0">' for d, summary in report.items(): message = message + '<tr colspan="3">' message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A')) message = message + '</tr>' for ticket in summary['tickets']: message = message + '<tr>' message = message + '<td>{}</td>'.format(ticket['pk']) message = message + '<td>{}, {}</td>'.format( ticket['contact'], ticket['description'], ) message = message + '<td>{}</td>'.format( ticket['format_minutes'], ) message = message + '</tr>' message = message + '<tr>' message = message + '<td></td><td></td>' message = message + '<td><b>{}</b></td>'.format( summary['format_total'] ) message = message + '</tr>' message = message + '</table>' queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay() Remove HTML table (our mail cannot send HTML)
# -*- encoding: utf-8 -*- import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '' for d, summary in report.items(): message = message + '\n\n{}, total time {}'.format( d.strftime('%d/%m/%Y %A'), summary['format_total'], ) for ticket in summary['tickets']: message = message + '\n{}: {}, {} ({})'.format( ticket['pk'], ticket['contact'], ticket['description'], ticket['format_minutes'], ) queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay()
<commit_before># -*- encoding: utf-8 -*- import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '<table border="0">' for d, summary in report.items(): message = message + '<tr colspan="3">' message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A')) message = message + '</tr>' for ticket in summary['tickets']: message = message + '<tr>' message = message + '<td>{}</td>'.format(ticket['pk']) message = message + '<td>{}, {}</td>'.format( ticket['contact'], ticket['description'], ) message = message + '<td>{}</td>'.format( ticket['format_minutes'], ) message = message + '</tr>' message = message + '<tr>' message = message + '<td></td><td></td>' message = message + '<td><b>{}</b></td>'.format( summary['format_total'] ) message = message + '</tr>' message = message + '</table>' queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay() <commit_msg>Remove HTML table (our mail cannot send HTML)<commit_after>
# -*- encoding: utf-8 -*- import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '' for d, summary in report.items(): message = message + '\n\n{}, total time {}'.format( d.strftime('%d/%m/%Y %A'), summary['format_total'], ) for ticket in summary['tickets']: message = message + '\n{}: {}, {} ({})'.format( ticket['pk'], ticket['contact'], ticket['description'], ticket['format_minutes'], ) queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay()
# -*- encoding: utf-8 -*- import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '<table border="0">' for d, summary in report.items(): message = message + '<tr colspan="3">' message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A')) message = message + '</tr>' for ticket in summary['tickets']: message = message + '<tr>' message = message + '<td>{}</td>'.format(ticket['pk']) message = message + '<td>{}, {}</td>'.format( ticket['contact'], ticket['description'], ) message = message + '<td>{}</td>'.format( ticket['format_minutes'], ) message = message + '</tr>' message = message + '<tr>' message = message + '<td></td><td></td>' message = message + '<td><b>{}</b></td>'.format( summary['format_total'] ) message = message + '</tr>' message = message + '</table>' queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay() Remove HTML table (our mail cannot send HTML)# -*- encoding: utf-8 -*- import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '' for d, summary in report.items(): message = message + '\n\n{}, total time {}'.format( d.strftime('%d/%m/%Y %A'), summary['format_total'], ) for ticket in summary['tickets']: message = message + '\n{}: {}, {} ({})'.format( ticket['pk'], ticket['contact'], ticket['description'], ticket['format_minutes'], ) queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay()
<commit_before># -*- encoding: utf-8 -*- import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '<table border="0">' for d, summary in report.items(): message = message + '<tr colspan="3">' message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A')) message = message + '</tr>' for ticket in summary['tickets']: message = message + '<tr>' message = message + '<td>{}</td>'.format(ticket['pk']) message = message + '<td>{}, {}</td>'.format( ticket['contact'], ticket['description'], ) message = message + '<td>{}</td>'.format( ticket['format_minutes'], ) message = message + '</tr>' message = message + '<tr>' message = message + '<td></td><td></td>' message = message + '<td><b>{}</b></td>'.format( summary['format_total'] ) message = message + '</tr>' message = message + '</table>' queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay() <commit_msg>Remove HTML table (our mail cannot send HTML)<commit_after># -*- encoding: utf-8 -*- import logging from celery import shared_task from django.utils import timezone from invoice.models import InvoiceUser from mail.service import queue_mail_message from mail.tasks import process_mail from .report import time_summary logger = logging.getLogger(__name__) @shared_task def mail_time_summary(): users = [] for item in InvoiceUser.objects.all(): if item.mail_time_summary and item.user.email: users.append(item.user) for user in users: logger.info('mail_time_summary: {}'.format(user.username)) report = time_summary(user, days=1) message = '' for d, summary in report.items(): message = message + '\n\n{}, total time {}'.format( d.strftime('%d/%m/%Y %A'), summary['format_total'], ) for ticket in summary['tickets']: message = message + '\n{}: {}, {} ({})'.format( ticket['pk'], ticket['contact'], ticket['description'], ticket['format_minutes'], ) queue_mail_message( user, [user.email], 'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')), message, ) if users: process_mail.delay()
5e5f5c8bfb5b61bd87ff4e55004e80c0e7edf408
ikea-ota-download.py
ikea-ota-download.py
#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname)
#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data.decode('utf-8')) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname)
Update json.loads line for python 3.5
Update json.loads line for python 3.5 Running the script inside a docker container with python 3.5 throws an "TypeError: the JSON object must be str, not 'bytes'". Fixed it by decoding downloaded json to utf-8
Python
bsd-3-clause
dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin
#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname) Update json.loads line for python 3.5 Running the script inside a docker container with python 3.5 throws an "TypeError: the JSON object must be str, not 'bytes'". Fixed it by decoding downloaded json to utf-8
#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data.decode('utf-8')) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname)
<commit_before>#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname) <commit_msg>Update json.loads line for python 3.5 Running the script inside a docker container with python 3.5 throws an "TypeError: the JSON object must be str, not 'bytes'". Fixed it by decoding downloaded json to utf-8<commit_after>
#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data.decode('utf-8')) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname)
#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname) Update json.loads line for python 3.5 Running the script inside a docker container with python 3.5 throws an "TypeError: the JSON object must be str, not 'bytes'". Fixed it by decoding downloaded json to utf-8#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data.decode('utf-8')) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname)
<commit_before>#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname) <commit_msg>Update json.loads line for python 3.5 Running the script inside a docker container with python 3.5 throws an "TypeError: the JSON object must be str, not 'bytes'". Fixed it by decoding downloaded json to utf-8<commit_after>#!/usr/bin/env python """ Snipped to download current IKEA ZLL OTA files into ~/otau compatible with python 3. """ import os import json try: from urllib.request import urlopen, urlretrieve except ImportError: from urllib2 import urlopen from urllib import urlretrieve f = urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json") data = f.read() arr = json.loads(data.decode('utf-8')) otapath = '%s/otau' % os.path.expanduser('~') if not os.path.exists(otapath): os.makedirs(otapath) for i in arr: if 'fw_binary_url' in i: url = i['fw_binary_url'] ls = url.split('/') fname = ls[len(ls) - 1] path = '%s/%s' % (otapath, fname) if not os.path.isfile(path): urlretrieve(url, path) print(path) else: print('%s already exists' % fname)
208081800ab7e6217ec0f88e76c2dffd32187db1
whyp/shell.py
whyp/shell.py
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): if not path_dir.isdir(): continue for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands
Allow for missing directories in $PATH
Allow for missing directories in $PATH
Python
mit
jalanb/what,jalanb/what
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands Allow for missing directories in $PATH
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): if not path_dir.isdir(): continue for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands
<commit_before>import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands <commit_msg>Allow for missing directories in $PATH<commit_after>
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): if not path_dir.isdir(): continue for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands Allow for missing directories in $PATHimport os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): if not path_dir.isdir(): continue for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands
<commit_before>import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands <commit_msg>Allow for missing directories in $PATH<commit_after>import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): if not path_dir.isdir(): continue for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands
c727f8382237c177d508d5113a7e3b8ca8ea7066
fasta/graphs.py
fasta/graphs.py
# Internal modules # from plumbing.graphs import Graph from plumbing.autopaths import FilePath # Third party modules # from matplotlib import pyplot # Constants # __all__ = ['LengthDist'] ################################################################################ class LengthDist(Graph): """The length distribution of the sequences""" short_name = 'length_dist' def __init__(self, parent): self.parent = parent self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf') def plot(self, x_log=False, y_log=False): # Data # counts = self.parent.lengths_counter # Plot # fig = pyplot.figure() pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center') axes = pyplot.gca() # Information # title = 'Distribution of sequence lengths' axes.set_title(title) axes.set_xlabel('Length of sequence in nucleotides') axes.set_ylabel('Number of sequences with this length') axes.xaxis.grid(False) # Add logarithm to axes # if x_log: axes.set_xscale('symlog') if y_log: axes.set_yscale('symlog') # Save it # self.save_plot(fig, axes, sep=('x'))
# Internal modules # from plumbing.graphs import Graph from plumbing.autopaths import FilePath # Third party modules # from matplotlib import pyplot # Constants # __all__ = ['LengthDist'] ################################################################################ class LengthDist(Graph): """The length distribution of the sequences""" short_name = 'length_dist' def __init__(self, parent): self.parent = parent self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf') def plot(self, x_log=False, y_log=False): # Data # counts = self.parent.lengths_counter # Plot # fig = pyplot.figure() pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center') axes = pyplot.gca() # Information # title = 'Distribution of sequence lengths' axes.set_title(title) axes.set_xlabel('Length of sequence in nucleotides') axes.set_ylabel('Number of sequences with this length') axes.xaxis.grid(False) # Add logarithm to axes # if x_log: axes.set_xscale('symlog') if y_log: axes.set_yscale('symlog') # Save it # self.save_plot(fig, axes, sep=('x')) # For convenience # return self
Return graph object after ploting
Return graph object after ploting
Python
mit
xapple/fasta
# Internal modules # from plumbing.graphs import Graph from plumbing.autopaths import FilePath # Third party modules # from matplotlib import pyplot # Constants # __all__ = ['LengthDist'] ################################################################################ class LengthDist(Graph): """The length distribution of the sequences""" short_name = 'length_dist' def __init__(self, parent): self.parent = parent self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf') def plot(self, x_log=False, y_log=False): # Data # counts = self.parent.lengths_counter # Plot # fig = pyplot.figure() pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center') axes = pyplot.gca() # Information # title = 'Distribution of sequence lengths' axes.set_title(title) axes.set_xlabel('Length of sequence in nucleotides') axes.set_ylabel('Number of sequences with this length') axes.xaxis.grid(False) # Add logarithm to axes # if x_log: axes.set_xscale('symlog') if y_log: axes.set_yscale('symlog') # Save it # self.save_plot(fig, axes, sep=('x'))Return graph object after ploting
# Internal modules # from plumbing.graphs import Graph from plumbing.autopaths import FilePath # Third party modules # from matplotlib import pyplot # Constants # __all__ = ['LengthDist'] ################################################################################ class LengthDist(Graph): """The length distribution of the sequences""" short_name = 'length_dist' def __init__(self, parent): self.parent = parent self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf') def plot(self, x_log=False, y_log=False): # Data # counts = self.parent.lengths_counter # Plot # fig = pyplot.figure() pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center') axes = pyplot.gca() # Information # title = 'Distribution of sequence lengths' axes.set_title(title) axes.set_xlabel('Length of sequence in nucleotides') axes.set_ylabel('Number of sequences with this length') axes.xaxis.grid(False) # Add logarithm to axes # if x_log: axes.set_xscale('symlog') if y_log: axes.set_yscale('symlog') # Save it # self.save_plot(fig, axes, sep=('x')) # For convenience # return self
<commit_before># Internal modules # from plumbing.graphs import Graph from plumbing.autopaths import FilePath # Third party modules # from matplotlib import pyplot # Constants # __all__ = ['LengthDist'] ################################################################################ class LengthDist(Graph): """The length distribution of the sequences""" short_name = 'length_dist' def __init__(self, parent): self.parent = parent self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf') def plot(self, x_log=False, y_log=False): # Data # counts = self.parent.lengths_counter # Plot # fig = pyplot.figure() pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center') axes = pyplot.gca() # Information # title = 'Distribution of sequence lengths' axes.set_title(title) axes.set_xlabel('Length of sequence in nucleotides') axes.set_ylabel('Number of sequences with this length') axes.xaxis.grid(False) # Add logarithm to axes # if x_log: axes.set_xscale('symlog') if y_log: axes.set_yscale('symlog') # Save it # self.save_plot(fig, axes, sep=('x'))<commit_msg>Return graph object after ploting<commit_after>
# Internal modules # from plumbing.graphs import Graph from plumbing.autopaths import FilePath # Third party modules # from matplotlib import pyplot # Constants # __all__ = ['LengthDist'] ################################################################################ class LengthDist(Graph): """The length distribution of the sequences""" short_name = 'length_dist' def __init__(self, parent): self.parent = parent self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf') def plot(self, x_log=False, y_log=False): # Data # counts = self.parent.lengths_counter # Plot # fig = pyplot.figure() pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center') axes = pyplot.gca() # Information # title = 'Distribution of sequence lengths' axes.set_title(title) axes.set_xlabel('Length of sequence in nucleotides') axes.set_ylabel('Number of sequences with this length') axes.xaxis.grid(False) # Add logarithm to axes # if x_log: axes.set_xscale('symlog') if y_log: axes.set_yscale('symlog') # Save it # self.save_plot(fig, axes, sep=('x')) # For convenience # return self
# Internal modules # from plumbing.graphs import Graph from plumbing.autopaths import FilePath # Third party modules # from matplotlib import pyplot # Constants # __all__ = ['LengthDist'] ################################################################################ class LengthDist(Graph): """The length distribution of the sequences""" short_name = 'length_dist' def __init__(self, parent): self.parent = parent self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf') def plot(self, x_log=False, y_log=False): # Data # counts = self.parent.lengths_counter # Plot # fig = pyplot.figure() pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center') axes = pyplot.gca() # Information # title = 'Distribution of sequence lengths' axes.set_title(title) axes.set_xlabel('Length of sequence in nucleotides') axes.set_ylabel('Number of sequences with this length') axes.xaxis.grid(False) # Add logarithm to axes # if x_log: axes.set_xscale('symlog') if y_log: axes.set_yscale('symlog') # Save it # self.save_plot(fig, axes, sep=('x'))Return graph object after ploting# Internal modules # from plumbing.graphs import Graph from plumbing.autopaths import FilePath # Third party modules # from matplotlib import pyplot # Constants # __all__ = ['LengthDist'] ################################################################################ class LengthDist(Graph): """The length distribution of the sequences""" short_name = 'length_dist' def __init__(self, parent): self.parent = parent self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf') def plot(self, x_log=False, y_log=False): # Data # counts = self.parent.lengths_counter # Plot # fig = pyplot.figure() pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center') axes = pyplot.gca() # Information # title = 'Distribution of sequence lengths' axes.set_title(title) axes.set_xlabel('Length of sequence in nucleotides') axes.set_ylabel('Number of sequences with this length') axes.xaxis.grid(False) # Add logarithm to axes # if x_log: axes.set_xscale('symlog') if y_log: axes.set_yscale('symlog') # Save it # self.save_plot(fig, axes, sep=('x')) # For convenience # return self
<commit_before># Internal modules # from plumbing.graphs import Graph from plumbing.autopaths import FilePath # Third party modules # from matplotlib import pyplot # Constants # __all__ = ['LengthDist'] ################################################################################ class LengthDist(Graph): """The length distribution of the sequences""" short_name = 'length_dist' def __init__(self, parent): self.parent = parent self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf') def plot(self, x_log=False, y_log=False): # Data # counts = self.parent.lengths_counter # Plot # fig = pyplot.figure() pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center') axes = pyplot.gca() # Information # title = 'Distribution of sequence lengths' axes.set_title(title) axes.set_xlabel('Length of sequence in nucleotides') axes.set_ylabel('Number of sequences with this length') axes.xaxis.grid(False) # Add logarithm to axes # if x_log: axes.set_xscale('symlog') if y_log: axes.set_yscale('symlog') # Save it # self.save_plot(fig, axes, sep=('x'))<commit_msg>Return graph object after ploting<commit_after># Internal modules # from plumbing.graphs import Graph from plumbing.autopaths import FilePath # Third party modules # from matplotlib import pyplot # Constants # __all__ = ['LengthDist'] ################################################################################ class LengthDist(Graph): """The length distribution of the sequences""" short_name = 'length_dist' def __init__(self, parent): self.parent = parent self.path = FilePath(self.parent.prefix_path + '_len_dist.pdf') def plot(self, x_log=False, y_log=False): # Data # counts = self.parent.lengths_counter # Plot # fig = pyplot.figure() pyplot.bar(counts.keys(), counts.values(), 1.0, color='gray', align='center') axes = pyplot.gca() # Information # title = 'Distribution of sequence lengths' axes.set_title(title) axes.set_xlabel('Length of sequence in nucleotides') axes.set_ylabel('Number of sequences with this length') axes.xaxis.grid(False) # Add logarithm to axes # if x_log: axes.set_xscale('symlog') if y_log: axes.set_yscale('symlog') # Save it # self.save_plot(fig, axes, sep=('x')) # For convenience # return self
1851190543d24d6f4c26a5d7a3a04f56aeba511d
sheldon/exceptions.py
sheldon/exceptions.py
# -*- coding: utf-8 -*- """ @author: Lises team @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """
# -*- coding: utf-8 -*- """ @author: Lises team @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ from sheldon.utils import logger def catch_plugin_errors(plugin_call_function): """ Catch all plugin exceptions and log it :param plugin_call_function: function with calling user plugin :return: """ def wrapper(*args, **kwargs): try: plugin_call_function(*args, **kwargs) except Exception as error: error_message = str(error.__traceback__) logger.error_log_message('Plugin error: \n' + error_message) return wrapper
Create decorator for catching plugin errors
Create decorator for catching plugin errors
Python
mit
lises/sheldon
# -*- coding: utf-8 -*- """ @author: Lises team @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """Create decorator for catching plugin errors
# -*- coding: utf-8 -*- """ @author: Lises team @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ from sheldon.utils import logger def catch_plugin_errors(plugin_call_function): """ Catch all plugin exceptions and log it :param plugin_call_function: function with calling user plugin :return: """ def wrapper(*args, **kwargs): try: plugin_call_function(*args, **kwargs) except Exception as error: error_message = str(error.__traceback__) logger.error_log_message('Plugin error: \n' + error_message) return wrapper
<commit_before># -*- coding: utf-8 -*- """ @author: Lises team @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """<commit_msg>Create decorator for catching plugin errors<commit_after>
# -*- coding: utf-8 -*- """ @author: Lises team @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ from sheldon.utils import logger def catch_plugin_errors(plugin_call_function): """ Catch all plugin exceptions and log it :param plugin_call_function: function with calling user plugin :return: """ def wrapper(*args, **kwargs): try: plugin_call_function(*args, **kwargs) except Exception as error: error_message = str(error.__traceback__) logger.error_log_message('Plugin error: \n' + error_message) return wrapper
# -*- coding: utf-8 -*- """ @author: Lises team @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """Create decorator for catching plugin errors# -*- coding: utf-8 -*- """ @author: Lises team @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ from sheldon.utils import logger def catch_plugin_errors(plugin_call_function): """ Catch all plugin exceptions and log it :param plugin_call_function: function with calling user plugin :return: """ def wrapper(*args, **kwargs): try: plugin_call_function(*args, **kwargs) except Exception as error: error_message = str(error.__traceback__) logger.error_log_message('Plugin error: \n' + error_message) return wrapper
<commit_before># -*- coding: utf-8 -*- """ @author: Lises team @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """<commit_msg>Create decorator for catching plugin errors<commit_after># -*- coding: utf-8 -*- """ @author: Lises team @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ from sheldon.utils import logger def catch_plugin_errors(plugin_call_function): """ Catch all plugin exceptions and log it :param plugin_call_function: function with calling user plugin :return: """ def wrapper(*args, **kwargs): try: plugin_call_function(*args, **kwargs) except Exception as error: error_message = str(error.__traceback__) logger.error_log_message('Plugin error: \n' + error_message) return wrapper
301fd00ea31346126d78696c50ac9daf1b76a428
classifier.py
classifier.py
import training_data import re import math class Classifier: def classify(self,text,prior=0.5,c=10e-6): """ Remove a pontuacao do texto """ words = re.findall(r"[\w']+",text) """words = text.split()""" data = training_data.TrainingData() spamLikehood = math.log(1) hamLikehood = math.log(1) for word in words: """ Calculo de spam""" if word in data.spam: spamLikehood += math.log(data.spam[word]) else: spamLikehood += math.log(c) """ Calculo de ham""" if word in data.ham: hamLikehood += math.log(data.ham[word]) else: hamLikehood += math.log(c) isSpam = spamLikehood + math.log(prior) isHam = hamLikehood + math.log(prior) print "HAM:", isHam, "SPAM:", isSpam
import re import math class Classifier: def classify(self,text,trainingData,prior=0.5,c=10e-6): """ Remove a pontuacao do texto """ words = re.findall(r"[\w']+",text) """words = text.split()""" likehood = math.log(1) for word in words: """ Calculo do likehood """ if word in trainingData: likehood += math.log(trainingData[word]) else: likehood += math.log(c) return likehood + math.log(prior)
Change so that we can use with any data
Change so that we can use with any data
Python
mit
anishihara/SpamFilter
import training_data import re import math class Classifier: def classify(self,text,prior=0.5,c=10e-6): """ Remove a pontuacao do texto """ words = re.findall(r"[\w']+",text) """words = text.split()""" data = training_data.TrainingData() spamLikehood = math.log(1) hamLikehood = math.log(1) for word in words: """ Calculo de spam""" if word in data.spam: spamLikehood += math.log(data.spam[word]) else: spamLikehood += math.log(c) """ Calculo de ham""" if word in data.ham: hamLikehood += math.log(data.ham[word]) else: hamLikehood += math.log(c) isSpam = spamLikehood + math.log(prior) isHam = hamLikehood + math.log(prior) print "HAM:", isHam, "SPAM:", isSpamChange so that we can use with any data
import re import math class Classifier: def classify(self,text,trainingData,prior=0.5,c=10e-6): """ Remove a pontuacao do texto """ words = re.findall(r"[\w']+",text) """words = text.split()""" likehood = math.log(1) for word in words: """ Calculo do likehood """ if word in trainingData: likehood += math.log(trainingData[word]) else: likehood += math.log(c) return likehood + math.log(prior)
<commit_before>import training_data import re import math class Classifier: def classify(self,text,prior=0.5,c=10e-6): """ Remove a pontuacao do texto """ words = re.findall(r"[\w']+",text) """words = text.split()""" data = training_data.TrainingData() spamLikehood = math.log(1) hamLikehood = math.log(1) for word in words: """ Calculo de spam""" if word in data.spam: spamLikehood += math.log(data.spam[word]) else: spamLikehood += math.log(c) """ Calculo de ham""" if word in data.ham: hamLikehood += math.log(data.ham[word]) else: hamLikehood += math.log(c) isSpam = spamLikehood + math.log(prior) isHam = hamLikehood + math.log(prior) print "HAM:", isHam, "SPAM:", isSpam<commit_msg>Change so that we can use with any data<commit_after>
import re import math class Classifier: def classify(self,text,trainingData,prior=0.5,c=10e-6): """ Remove a pontuacao do texto """ words = re.findall(r"[\w']+",text) """words = text.split()""" likehood = math.log(1) for word in words: """ Calculo do likehood """ if word in trainingData: likehood += math.log(trainingData[word]) else: likehood += math.log(c) return likehood + math.log(prior)
import training_data import re import math class Classifier: def classify(self,text,prior=0.5,c=10e-6): """ Remove a pontuacao do texto """ words = re.findall(r"[\w']+",text) """words = text.split()""" data = training_data.TrainingData() spamLikehood = math.log(1) hamLikehood = math.log(1) for word in words: """ Calculo de spam""" if word in data.spam: spamLikehood += math.log(data.spam[word]) else: spamLikehood += math.log(c) """ Calculo de ham""" if word in data.ham: hamLikehood += math.log(data.ham[word]) else: hamLikehood += math.log(c) isSpam = spamLikehood + math.log(prior) isHam = hamLikehood + math.log(prior) print "HAM:", isHam, "SPAM:", isSpamChange so that we can use with any dataimport re import math class Classifier: def classify(self,text,trainingData,prior=0.5,c=10e-6): """ Remove a pontuacao do texto """ words = re.findall(r"[\w']+",text) """words = text.split()""" likehood = math.log(1) for word in words: """ Calculo do likehood """ if word in trainingData: likehood += math.log(trainingData[word]) else: likehood += math.log(c) return likehood + math.log(prior)
<commit_before>import training_data import re import math class Classifier: def classify(self,text,prior=0.5,c=10e-6): """ Remove a pontuacao do texto """ words = re.findall(r"[\w']+",text) """words = text.split()""" data = training_data.TrainingData() spamLikehood = math.log(1) hamLikehood = math.log(1) for word in words: """ Calculo de spam""" if word in data.spam: spamLikehood += math.log(data.spam[word]) else: spamLikehood += math.log(c) """ Calculo de ham""" if word in data.ham: hamLikehood += math.log(data.ham[word]) else: hamLikehood += math.log(c) isSpam = spamLikehood + math.log(prior) isHam = hamLikehood + math.log(prior) print "HAM:", isHam, "SPAM:", isSpam<commit_msg>Change so that we can use with any data<commit_after>import re import math class Classifier: def classify(self,text,trainingData,prior=0.5,c=10e-6): """ Remove a pontuacao do texto """ words = re.findall(r"[\w']+",text) """words = text.split()""" likehood = math.log(1) for word in words: """ Calculo do likehood """ if word in trainingData: likehood += math.log(trainingData[word]) else: likehood += math.log(c) return likehood + math.log(prior)
bc083087cd7aadbf11fba9a8d1312bde3b7a2a27
osgtest/library/mysql.py
osgtest/library/mysql.py
import os from osgtest.library import core from osgtest.library import service def name(): if core.el_release() < 7: return 'mysql' else: return 'mariadb' def daemon_name(): if core.el_release() < 7: return 'mysqld' else: return 'mariadb' def init_script(): return daemon_name() def pidfile(): return os.path.join('/var/run', daemon_name(), daemon_name() + '.pid') def server_rpm(): return name() + '-server' def client_rpm(): return name() def start(): service.start('mysql', init_script=init_script(), sentinel_file=pidfile()) def stop(): service.stop('mysql') def is_running(): service.is_running('mysql', init_script=init_script())
import os import re from osgtest.library import core from osgtest.library import service def name(): if core.el_release() < 7: return 'mysql' else: return 'mariadb' def daemon_name(): if core.el_release() < 7: return 'mysqld' else: return 'mariadb' def init_script(): return daemon_name() def pidfile(): return os.path.join('/var/run', daemon_name(), daemon_name() + '.pid') def server_rpm(): return name() + '-server' def client_rpm(): return name() def start(): service.start('mysql', init_script=init_script(), sentinel_file=pidfile()) def stop(): service.stop('mysql') def is_running(): service.is_running('mysql', init_script=init_script()) def _get_command(user='root', database=None): command = ['mysql', '-N', '-B', '--user=' + str(user)] if database: command.append('--database=' + str(database)) return command def execute(statements, database=None): return core.system(_get_command(database=database), stdin=statements) def check_execute(statements, message, database=None, exit=0): return core.check_system(_get_command(database=database), message, stdin=statements, exit=exit) def dbdump(destfile, database=None): command = "mysqldump --skip-comments --skip-extended-insert -u root " if database: command += re.escape(database) else: command += "--all-databases" command += ">" + re.escape(destfile) core.system(command, user=None, stdin=None, log_output=False, shell=True)
Add several useful MySQL functions
Add several useful MySQL functions Functions useful for examining and manipulating MySQL databases: - execute() -- execute one or more MySQL statements (as a single string), optionally on a specific database. Returns the same thing as core.system() - check_execute() -- same as execute(), but checks return code and errors out on failure. Returns the same thing as core.check_system() - dbdump() -- create a dump of one or all mysql databases in the given file
Python
apache-2.0
efajardo/osg-test,efajardo/osg-test
import os from osgtest.library import core from osgtest.library import service def name(): if core.el_release() < 7: return 'mysql' else: return 'mariadb' def daemon_name(): if core.el_release() < 7: return 'mysqld' else: return 'mariadb' def init_script(): return daemon_name() def pidfile(): return os.path.join('/var/run', daemon_name(), daemon_name() + '.pid') def server_rpm(): return name() + '-server' def client_rpm(): return name() def start(): service.start('mysql', init_script=init_script(), sentinel_file=pidfile()) def stop(): service.stop('mysql') def is_running(): service.is_running('mysql', init_script=init_script()) Add several useful MySQL functions Functions useful for examining and manipulating MySQL databases: - execute() -- execute one or more MySQL statements (as a single string), optionally on a specific database. Returns the same thing as core.system() - check_execute() -- same as execute(), but checks return code and errors out on failure. Returns the same thing as core.check_system() - dbdump() -- create a dump of one or all mysql databases in the given file
import os import re from osgtest.library import core from osgtest.library import service def name(): if core.el_release() < 7: return 'mysql' else: return 'mariadb' def daemon_name(): if core.el_release() < 7: return 'mysqld' else: return 'mariadb' def init_script(): return daemon_name() def pidfile(): return os.path.join('/var/run', daemon_name(), daemon_name() + '.pid') def server_rpm(): return name() + '-server' def client_rpm(): return name() def start(): service.start('mysql', init_script=init_script(), sentinel_file=pidfile()) def stop(): service.stop('mysql') def is_running(): service.is_running('mysql', init_script=init_script()) def _get_command(user='root', database=None): command = ['mysql', '-N', '-B', '--user=' + str(user)] if database: command.append('--database=' + str(database)) return command def execute(statements, database=None): return core.system(_get_command(database=database), stdin=statements) def check_execute(statements, message, database=None, exit=0): return core.check_system(_get_command(database=database), message, stdin=statements, exit=exit) def dbdump(destfile, database=None): command = "mysqldump --skip-comments --skip-extended-insert -u root " if database: command += re.escape(database) else: command += "--all-databases" command += ">" + re.escape(destfile) core.system(command, user=None, stdin=None, log_output=False, shell=True)
<commit_before>import os from osgtest.library import core from osgtest.library import service def name(): if core.el_release() < 7: return 'mysql' else: return 'mariadb' def daemon_name(): if core.el_release() < 7: return 'mysqld' else: return 'mariadb' def init_script(): return daemon_name() def pidfile(): return os.path.join('/var/run', daemon_name(), daemon_name() + '.pid') def server_rpm(): return name() + '-server' def client_rpm(): return name() def start(): service.start('mysql', init_script=init_script(), sentinel_file=pidfile()) def stop(): service.stop('mysql') def is_running(): service.is_running('mysql', init_script=init_script()) <commit_msg>Add several useful MySQL functions Functions useful for examining and manipulating MySQL databases: - execute() -- execute one or more MySQL statements (as a single string), optionally on a specific database. Returns the same thing as core.system() - check_execute() -- same as execute(), but checks return code and errors out on failure. Returns the same thing as core.check_system() - dbdump() -- create a dump of one or all mysql databases in the given file<commit_after>
import os import re from osgtest.library import core from osgtest.library import service def name(): if core.el_release() < 7: return 'mysql' else: return 'mariadb' def daemon_name(): if core.el_release() < 7: return 'mysqld' else: return 'mariadb' def init_script(): return daemon_name() def pidfile(): return os.path.join('/var/run', daemon_name(), daemon_name() + '.pid') def server_rpm(): return name() + '-server' def client_rpm(): return name() def start(): service.start('mysql', init_script=init_script(), sentinel_file=pidfile()) def stop(): service.stop('mysql') def is_running(): service.is_running('mysql', init_script=init_script()) def _get_command(user='root', database=None): command = ['mysql', '-N', '-B', '--user=' + str(user)] if database: command.append('--database=' + str(database)) return command def execute(statements, database=None): return core.system(_get_command(database=database), stdin=statements) def check_execute(statements, message, database=None, exit=0): return core.check_system(_get_command(database=database), message, stdin=statements, exit=exit) def dbdump(destfile, database=None): command = "mysqldump --skip-comments --skip-extended-insert -u root " if database: command += re.escape(database) else: command += "--all-databases" command += ">" + re.escape(destfile) core.system(command, user=None, stdin=None, log_output=False, shell=True)
import os from osgtest.library import core from osgtest.library import service def name(): if core.el_release() < 7: return 'mysql' else: return 'mariadb' def daemon_name(): if core.el_release() < 7: return 'mysqld' else: return 'mariadb' def init_script(): return daemon_name() def pidfile(): return os.path.join('/var/run', daemon_name(), daemon_name() + '.pid') def server_rpm(): return name() + '-server' def client_rpm(): return name() def start(): service.start('mysql', init_script=init_script(), sentinel_file=pidfile()) def stop(): service.stop('mysql') def is_running(): service.is_running('mysql', init_script=init_script()) Add several useful MySQL functions Functions useful for examining and manipulating MySQL databases: - execute() -- execute one or more MySQL statements (as a single string), optionally on a specific database. Returns the same thing as core.system() - check_execute() -- same as execute(), but checks return code and errors out on failure. Returns the same thing as core.check_system() - dbdump() -- create a dump of one or all mysql databases in the given fileimport os import re from osgtest.library import core from osgtest.library import service def name(): if core.el_release() < 7: return 'mysql' else: return 'mariadb' def daemon_name(): if core.el_release() < 7: return 'mysqld' else: return 'mariadb' def init_script(): return daemon_name() def pidfile(): return os.path.join('/var/run', daemon_name(), daemon_name() + '.pid') def server_rpm(): return name() + '-server' def client_rpm(): return name() def start(): service.start('mysql', init_script=init_script(), sentinel_file=pidfile()) def stop(): service.stop('mysql') def is_running(): service.is_running('mysql', init_script=init_script()) def _get_command(user='root', database=None): command = ['mysql', '-N', '-B', '--user=' + str(user)] if database: command.append('--database=' + str(database)) return command def execute(statements, database=None): return core.system(_get_command(database=database), stdin=statements) def check_execute(statements, message, database=None, exit=0): return core.check_system(_get_command(database=database), message, stdin=statements, exit=exit) def dbdump(destfile, database=None): command = "mysqldump --skip-comments --skip-extended-insert -u root " if database: command += re.escape(database) else: command += "--all-databases" command += ">" + re.escape(destfile) core.system(command, user=None, stdin=None, log_output=False, shell=True)
<commit_before>import os from osgtest.library import core from osgtest.library import service def name(): if core.el_release() < 7: return 'mysql' else: return 'mariadb' def daemon_name(): if core.el_release() < 7: return 'mysqld' else: return 'mariadb' def init_script(): return daemon_name() def pidfile(): return os.path.join('/var/run', daemon_name(), daemon_name() + '.pid') def server_rpm(): return name() + '-server' def client_rpm(): return name() def start(): service.start('mysql', init_script=init_script(), sentinel_file=pidfile()) def stop(): service.stop('mysql') def is_running(): service.is_running('mysql', init_script=init_script()) <commit_msg>Add several useful MySQL functions Functions useful for examining and manipulating MySQL databases: - execute() -- execute one or more MySQL statements (as a single string), optionally on a specific database. Returns the same thing as core.system() - check_execute() -- same as execute(), but checks return code and errors out on failure. Returns the same thing as core.check_system() - dbdump() -- create a dump of one or all mysql databases in the given file<commit_after>import os import re from osgtest.library import core from osgtest.library import service def name(): if core.el_release() < 7: return 'mysql' else: return 'mariadb' def daemon_name(): if core.el_release() < 7: return 'mysqld' else: return 'mariadb' def init_script(): return daemon_name() def pidfile(): return os.path.join('/var/run', daemon_name(), daemon_name() + '.pid') def server_rpm(): return name() + '-server' def client_rpm(): return name() def start(): service.start('mysql', init_script=init_script(), sentinel_file=pidfile()) def stop(): service.stop('mysql') def is_running(): service.is_running('mysql', init_script=init_script()) def _get_command(user='root', database=None): command = ['mysql', '-N', '-B', '--user=' + str(user)] if database: command.append('--database=' + str(database)) return command def execute(statements, database=None): return core.system(_get_command(database=database), stdin=statements) def check_execute(statements, message, database=None, exit=0): return core.check_system(_get_command(database=database), message, stdin=statements, exit=exit) def dbdump(destfile, database=None): command = "mysqldump --skip-comments --skip-extended-insert -u root " if database: command += re.escape(database) else: command += "--all-databases" command += ">" + re.escape(destfile) core.system(command, user=None, stdin=None, log_output=False, shell=True)
4cd0d2a947bbfa9ba830c4dc543b1688ecf2e54f
produceEports.py
produceEports.py
#!/usr/bin/env python from app.views.export import write_all_measurements_csv import tempfile import os f = open("app/static/exports/AllMeasurements_inprogress.csv", "w") try: write_all_measurements_csv(f) finally: f.close os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/AllMeasurements.csv")
#!/usr/bin/env python from app.views.export import write_all_measurements_csv import tempfile import os f = open("{}/app/static/exports/AllMeasurements_inprogress.csv".format(os.path.dirname(os.path.realpath(__file__))), "w") try: write_all_measurements_csv(f) finally: f.close os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/AllMeasurements.csv")
Add application directory to export directory
Add application directory to export directory
Python
mit
rabramley/telomere,rabramley/telomere,rabramley/telomere
#!/usr/bin/env python from app.views.export import write_all_measurements_csv import tempfile import os f = open("app/static/exports/AllMeasurements_inprogress.csv", "w") try: write_all_measurements_csv(f) finally: f.close os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/AllMeasurements.csv") Add application directory to export directory
#!/usr/bin/env python from app.views.export import write_all_measurements_csv import tempfile import os f = open("{}/app/static/exports/AllMeasurements_inprogress.csv".format(os.path.dirname(os.path.realpath(__file__))), "w") try: write_all_measurements_csv(f) finally: f.close os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/AllMeasurements.csv")
<commit_before>#!/usr/bin/env python from app.views.export import write_all_measurements_csv import tempfile import os f = open("app/static/exports/AllMeasurements_inprogress.csv", "w") try: write_all_measurements_csv(f) finally: f.close os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/AllMeasurements.csv") <commit_msg>Add application directory to export directory<commit_after>
#!/usr/bin/env python from app.views.export import write_all_measurements_csv import tempfile import os f = open("{}/app/static/exports/AllMeasurements_inprogress.csv".format(os.path.dirname(os.path.realpath(__file__))), "w") try: write_all_measurements_csv(f) finally: f.close os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/AllMeasurements.csv")
#!/usr/bin/env python from app.views.export import write_all_measurements_csv import tempfile import os f = open("app/static/exports/AllMeasurements_inprogress.csv", "w") try: write_all_measurements_csv(f) finally: f.close os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/AllMeasurements.csv") Add application directory to export directory#!/usr/bin/env python from app.views.export import write_all_measurements_csv import tempfile import os f = open("{}/app/static/exports/AllMeasurements_inprogress.csv".format(os.path.dirname(os.path.realpath(__file__))), "w") try: write_all_measurements_csv(f) finally: f.close os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/AllMeasurements.csv")
<commit_before>#!/usr/bin/env python from app.views.export import write_all_measurements_csv import tempfile import os f = open("app/static/exports/AllMeasurements_inprogress.csv", "w") try: write_all_measurements_csv(f) finally: f.close os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/AllMeasurements.csv") <commit_msg>Add application directory to export directory<commit_after>#!/usr/bin/env python from app.views.export import write_all_measurements_csv import tempfile import os f = open("{}/app/static/exports/AllMeasurements_inprogress.csv".format(os.path.dirname(os.path.realpath(__file__))), "w") try: write_all_measurements_csv(f) finally: f.close os.rename("app/static/exports/AllMeasurements_inprogress.csv", "app/static/exports/AllMeasurements.csv")
4072f8ec6e1908d6e84859c8a0bd6c96562ea5cc
parts/plugins/x-shell.py
parts/plugins/x-shell.py
import snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ])
import snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, 'SNAPDIR=' + self.builddir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ]) # vim:set ts=4 noet:
Add "SNAPDIR" and simple vim modeline
Add "SNAPDIR" and simple vim modeline
Python
mit
infosiftr/snap-docker,docker-snap/docker,docker-snap/docker
import snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ]) Add "SNAPDIR" and simple vim modeline
import snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, 'SNAPDIR=' + self.builddir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ]) # vim:set ts=4 noet:
<commit_before>import snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ]) <commit_msg>Add "SNAPDIR" and simple vim modeline<commit_after>
import snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, 'SNAPDIR=' + self.builddir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ]) # vim:set ts=4 noet:
import snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ]) Add "SNAPDIR" and simple vim modelineimport snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, 'SNAPDIR=' + self.builddir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ]) # vim:set ts=4 noet:
<commit_before>import snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ]) <commit_msg>Add "SNAPDIR" and simple vim modeline<commit_after>import snapcraft class ShellPlugin(snapcraft.BasePlugin): @classmethod def schema(cls): schema = super().schema() schema['required'] = [] schema['properties']['shell'] = { 'type': 'string', 'default': '/bin/sh', } schema['required'].append('shell') schema['properties']['shell-flags'] = { 'type': 'array', 'items': { 'type': 'string', }, 'default': [], } schema['properties']['shell-command'] = { 'type': 'string', } schema['required'].append('shell-command') return schema def env(self, root): return super().env(root) + [ 'DESTDIR=' + self.installdir, 'SNAPDIR=' + self.builddir, ] def build(self): super().build() return self.run([ self.options.shell, ] + self.options.shell_flags + [ '-c', self.options.shell_command, ]) # vim:set ts=4 noet:
338672c4f79fe01b4801346594bcd0d95a925e75
python-prefix.py
python-prefix.py
#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <python version>\n' % \ os.path.basename(sys.argv[0]) sys.stderr.write(msg) return 1 python_prefix = sys.argv[1] python_version = sys.argv[2] path = '%s/lib/python%s' % (python_prefix, python_version) path = os.path.normpath(path) if path[-1] != '/': path = path + '/' prefix = None for p in sys.path: if p.startswith(path): prefix = path break if not prefix: prefix = site.PREFIXES[-1] sys.stdout.write('%s\n' % prefix) return 0 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <python version>\n' % \ os.path.basename(sys.argv[0]) sys.stderr.write(msg) return 1 python_prefix = sys.argv[1] python_version = sys.argv[2] path = '%s/lib/python%s' % (python_prefix, python_version) path = os.path.normpath(path) if path[-1] != '/': path = path + '/' prefix = None for p in sys.path: if p.startswith(path): prefix = python_prefix break if not prefix: prefix = site.PREFIXES[-1] sys.stdout.write('%s\n' % prefix) return 0 if __name__ == '__main__': sys.exit(main())
Fix typo in previous commit.
Fix typo in previous commit.
Python
bsd-2-clause
D3f0/coreemu,abn/coreemu,cudadog/coreemu,cudadog/coreemu,abn/coreemu,D3f0/coreemu,abn/coreemu,D3f0/coreemu,eiginn/coreemu,eiginn/coreemu,cudadog/coreemu,eiginn/coreemu
#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <python version>\n' % \ os.path.basename(sys.argv[0]) sys.stderr.write(msg) return 1 python_prefix = sys.argv[1] python_version = sys.argv[2] path = '%s/lib/python%s' % (python_prefix, python_version) path = os.path.normpath(path) if path[-1] != '/': path = path + '/' prefix = None for p in sys.path: if p.startswith(path): prefix = path break if not prefix: prefix = site.PREFIXES[-1] sys.stdout.write('%s\n' % prefix) return 0 if __name__ == '__main__': sys.exit(main()) Fix typo in previous commit.
#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <python version>\n' % \ os.path.basename(sys.argv[0]) sys.stderr.write(msg) return 1 python_prefix = sys.argv[1] python_version = sys.argv[2] path = '%s/lib/python%s' % (python_prefix, python_version) path = os.path.normpath(path) if path[-1] != '/': path = path + '/' prefix = None for p in sys.path: if p.startswith(path): prefix = python_prefix break if not prefix: prefix = site.PREFIXES[-1] sys.stdout.write('%s\n' % prefix) return 0 if __name__ == '__main__': sys.exit(main())
<commit_before>#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <python version>\n' % \ os.path.basename(sys.argv[0]) sys.stderr.write(msg) return 1 python_prefix = sys.argv[1] python_version = sys.argv[2] path = '%s/lib/python%s' % (python_prefix, python_version) path = os.path.normpath(path) if path[-1] != '/': path = path + '/' prefix = None for p in sys.path: if p.startswith(path): prefix = path break if not prefix: prefix = site.PREFIXES[-1] sys.stdout.write('%s\n' % prefix) return 0 if __name__ == '__main__': sys.exit(main()) <commit_msg>Fix typo in previous commit.<commit_after>
#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <python version>\n' % \ os.path.basename(sys.argv[0]) sys.stderr.write(msg) return 1 python_prefix = sys.argv[1] python_version = sys.argv[2] path = '%s/lib/python%s' % (python_prefix, python_version) path = os.path.normpath(path) if path[-1] != '/': path = path + '/' prefix = None for p in sys.path: if p.startswith(path): prefix = python_prefix break if not prefix: prefix = site.PREFIXES[-1] sys.stdout.write('%s\n' % prefix) return 0 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <python version>\n' % \ os.path.basename(sys.argv[0]) sys.stderr.write(msg) return 1 python_prefix = sys.argv[1] python_version = sys.argv[2] path = '%s/lib/python%s' % (python_prefix, python_version) path = os.path.normpath(path) if path[-1] != '/': path = path + '/' prefix = None for p in sys.path: if p.startswith(path): prefix = path break if not prefix: prefix = site.PREFIXES[-1] sys.stdout.write('%s\n' % prefix) return 0 if __name__ == '__main__': sys.exit(main()) Fix typo in previous commit.#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <python version>\n' % \ os.path.basename(sys.argv[0]) sys.stderr.write(msg) return 1 python_prefix = sys.argv[1] python_version = sys.argv[2] path = '%s/lib/python%s' % (python_prefix, python_version) path = os.path.normpath(path) if path[-1] != '/': path = path + '/' prefix = None for p in sys.path: if p.startswith(path): prefix = python_prefix break if not prefix: prefix = site.PREFIXES[-1] sys.stdout.write('%s\n' % prefix) return 0 if __name__ == '__main__': sys.exit(main())
<commit_before>#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <python version>\n' % \ os.path.basename(sys.argv[0]) sys.stderr.write(msg) return 1 python_prefix = sys.argv[1] python_version = sys.argv[2] path = '%s/lib/python%s' % (python_prefix, python_version) path = os.path.normpath(path) if path[-1] != '/': path = path + '/' prefix = None for p in sys.path: if p.startswith(path): prefix = path break if not prefix: prefix = site.PREFIXES[-1] sys.stdout.write('%s\n' % prefix) return 0 if __name__ == '__main__': sys.exit(main()) <commit_msg>Fix typo in previous commit.<commit_after>#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <python version>\n' % \ os.path.basename(sys.argv[0]) sys.stderr.write(msg) return 1 python_prefix = sys.argv[1] python_version = sys.argv[2] path = '%s/lib/python%s' % (python_prefix, python_version) path = os.path.normpath(path) if path[-1] != '/': path = path + '/' prefix = None for p in sys.path: if p.startswith(path): prefix = python_prefix break if not prefix: prefix = site.PREFIXES[-1] sys.stdout.write('%s\n' % prefix) return 0 if __name__ == '__main__': sys.exit(main())
f035ca424504a37e350fd009e973b89ba7e00670
desertbot/datastore.py
desertbot/datastore.py
import json import os class DataStore(object): def __init__(self, storagePath="desertbot_data.json"): self.storagePath = storagePath self.data = {} self.load() def load(self): if not os.path.exists(self.storagePath): with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: self.data = json.load(templateFile) self.save() return with open(self.storagePath) as storageFile: self.data = json.load(storageFile) def save(self): tmpFile = "{}.tmp".format(self.storagePath) with open(tmpFile, "w") as storageFile: storageFile.write(json.dumps(self.data, indent=4)) os.rename(tmpFile, self.storagePath) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value self.save() def __contains__(self, key): return key in self.data
import json import os class DataStore(object): def __init__(self, storagePath="desertbot_data.json"): self.storagePath = storagePath self.data = {} self.load() def load(self): if not os.path.exists(self.storagePath): with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: self.data = json.load(templateFile) self.save() return with open(self.storagePath) as storageFile: self.data = json.load(storageFile) self.checkDefaults() def checkDefaults(self): """ If data exists, we still wanna make sure we load in things from defaults if there's things in the defaults that aren't in our actual data """ with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: defaultData = json.load(templateFile) for key, data in defaultData.items(): if key not in self.data: self.data[key] = data def save(self): tmpFile = "{}.tmp".format(self.storagePath) with open(tmpFile, "w") as storageFile: storageFile.write(json.dumps(self.data, indent=4)) os.rename(tmpFile, self.storagePath) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value self.save() def __contains__(self, key): return key in self.data
Load data from defaults if defaults has keys that data doesn't.
Load data from defaults if defaults has keys that data doesn't.
Python
mit
DesertBot/DesertBot
import json import os class DataStore(object): def __init__(self, storagePath="desertbot_data.json"): self.storagePath = storagePath self.data = {} self.load() def load(self): if not os.path.exists(self.storagePath): with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: self.data = json.load(templateFile) self.save() return with open(self.storagePath) as storageFile: self.data = json.load(storageFile) def save(self): tmpFile = "{}.tmp".format(self.storagePath) with open(tmpFile, "w") as storageFile: storageFile.write(json.dumps(self.data, indent=4)) os.rename(tmpFile, self.storagePath) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value self.save() def __contains__(self, key): return key in self.data Load data from defaults if defaults has keys that data doesn't.
import json import os class DataStore(object): def __init__(self, storagePath="desertbot_data.json"): self.storagePath = storagePath self.data = {} self.load() def load(self): if not os.path.exists(self.storagePath): with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: self.data = json.load(templateFile) self.save() return with open(self.storagePath) as storageFile: self.data = json.load(storageFile) self.checkDefaults() def checkDefaults(self): """ If data exists, we still wanna make sure we load in things from defaults if there's things in the defaults that aren't in our actual data """ with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: defaultData = json.load(templateFile) for key, data in defaultData.items(): if key not in self.data: self.data[key] = data def save(self): tmpFile = "{}.tmp".format(self.storagePath) with open(tmpFile, "w") as storageFile: storageFile.write(json.dumps(self.data, indent=4)) os.rename(tmpFile, self.storagePath) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value self.save() def __contains__(self, key): return key in self.data
<commit_before>import json import os class DataStore(object): def __init__(self, storagePath="desertbot_data.json"): self.storagePath = storagePath self.data = {} self.load() def load(self): if not os.path.exists(self.storagePath): with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: self.data = json.load(templateFile) self.save() return with open(self.storagePath) as storageFile: self.data = json.load(storageFile) def save(self): tmpFile = "{}.tmp".format(self.storagePath) with open(tmpFile, "w") as storageFile: storageFile.write(json.dumps(self.data, indent=4)) os.rename(tmpFile, self.storagePath) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value self.save() def __contains__(self, key): return key in self.data <commit_msg>Load data from defaults if defaults has keys that data doesn't.<commit_after>
import json import os class DataStore(object): def __init__(self, storagePath="desertbot_data.json"): self.storagePath = storagePath self.data = {} self.load() def load(self): if not os.path.exists(self.storagePath): with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: self.data = json.load(templateFile) self.save() return with open(self.storagePath) as storageFile: self.data = json.load(storageFile) self.checkDefaults() def checkDefaults(self): """ If data exists, we still wanna make sure we load in things from defaults if there's things in the defaults that aren't in our actual data """ with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: defaultData = json.load(templateFile) for key, data in defaultData.items(): if key not in self.data: self.data[key] = data def save(self): tmpFile = "{}.tmp".format(self.storagePath) with open(tmpFile, "w") as storageFile: storageFile.write(json.dumps(self.data, indent=4)) os.rename(tmpFile, self.storagePath) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value self.save() def __contains__(self, key): return key in self.data
import json import os class DataStore(object): def __init__(self, storagePath="desertbot_data.json"): self.storagePath = storagePath self.data = {} self.load() def load(self): if not os.path.exists(self.storagePath): with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: self.data = json.load(templateFile) self.save() return with open(self.storagePath) as storageFile: self.data = json.load(storageFile) def save(self): tmpFile = "{}.tmp".format(self.storagePath) with open(tmpFile, "w") as storageFile: storageFile.write(json.dumps(self.data, indent=4)) os.rename(tmpFile, self.storagePath) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value self.save() def __contains__(self, key): return key in self.data Load data from defaults if defaults has keys that data doesn't.import json import os class DataStore(object): def __init__(self, storagePath="desertbot_data.json"): self.storagePath = storagePath self.data = {} self.load() def load(self): if not os.path.exists(self.storagePath): with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: self.data = json.load(templateFile) self.save() return with open(self.storagePath) as storageFile: self.data = json.load(storageFile) self.checkDefaults() def checkDefaults(self): """ If data exists, we still wanna make sure we load in things from defaults if there's things in the defaults that aren't in our actual data """ with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: defaultData = json.load(templateFile) for key, data in defaultData.items(): if key not in self.data: self.data[key] = data def save(self): tmpFile = "{}.tmp".format(self.storagePath) with open(tmpFile, "w") as storageFile: storageFile.write(json.dumps(self.data, indent=4)) os.rename(tmpFile, self.storagePath) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value self.save() def __contains__(self, key): return key in self.data
<commit_before>import json import os class DataStore(object): def __init__(self, storagePath="desertbot_data.json"): self.storagePath = storagePath self.data = {} self.load() def load(self): if not os.path.exists(self.storagePath): with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: self.data = json.load(templateFile) self.save() return with open(self.storagePath) as storageFile: self.data = json.load(storageFile) def save(self): tmpFile = "{}.tmp".format(self.storagePath) with open(tmpFile, "w") as storageFile: storageFile.write(json.dumps(self.data, indent=4)) os.rename(tmpFile, self.storagePath) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value self.save() def __contains__(self, key): return key in self.data <commit_msg>Load data from defaults if defaults has keys that data doesn't.<commit_after>import json import os class DataStore(object): def __init__(self, storagePath="desertbot_data.json"): self.storagePath = storagePath self.data = {} self.load() def load(self): if not os.path.exists(self.storagePath): with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: self.data = json.load(templateFile) self.save() return with open(self.storagePath) as storageFile: self.data = json.load(storageFile) self.checkDefaults() def checkDefaults(self): """ If data exists, we still wanna make sure we load in things from defaults if there's things in the defaults that aren't in our actual data """ with open(os.path.join("desertbot", "datastore_default.json")) as templateFile: defaultData = json.load(templateFile) for key, data in defaultData.items(): if key not in self.data: self.data[key] = data def save(self): tmpFile = "{}.tmp".format(self.storagePath) with open(tmpFile, "w") as storageFile: storageFile.write(json.dumps(self.data, indent=4)) os.rename(tmpFile, self.storagePath) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): self.data[key] = value self.save() def __contains__(self, key): return key in self.data
bbb12dd60222ae617e5ed70d37c0ea3d350b9f3a
satsound/views.py
satsound/views.py
from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'not found'} try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: pass if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form})
from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'TBD'} newsat = False try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: newsat = True st = SpaceTrackClient(identity=settings.SPACETRACK_IDENTITY, password=settings.SPACETRACK_PASSWORD) # https://www.space-track.org/basicspacedata/query/class/satcat/NORAD_CAT_ID/3/orderby/INTLDES asc/metadata/false params = { 'norad_cat_id': norad_id, 'metadata': False } response = st.satcat(**params) if len(response) == 1: sat = Satellite( norad_id=norad_id, name=response[0].get('OBJECT_NAME', '') ) if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() if newsat: sat.save() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form})
Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite
Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite
Python
mit
saanobhaai/apman,saanobhaai/apman
from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'not found'} try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: pass if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form}) Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite
from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'TBD'} newsat = False try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: newsat = True st = SpaceTrackClient(identity=settings.SPACETRACK_IDENTITY, password=settings.SPACETRACK_PASSWORD) # https://www.space-track.org/basicspacedata/query/class/satcat/NORAD_CAT_ID/3/orderby/INTLDES asc/metadata/false params = { 'norad_cat_id': norad_id, 'metadata': False } response = st.satcat(**params) if len(response) == 1: sat = Satellite( norad_id=norad_id, name=response[0].get('OBJECT_NAME', '') ) if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() if newsat: sat.save() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form})
<commit_before>from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'not found'} try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: pass if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form}) <commit_msg>Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite<commit_after>
from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'TBD'} newsat = False try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: newsat = True st = SpaceTrackClient(identity=settings.SPACETRACK_IDENTITY, password=settings.SPACETRACK_PASSWORD) # https://www.space-track.org/basicspacedata/query/class/satcat/NORAD_CAT_ID/3/orderby/INTLDES asc/metadata/false params = { 'norad_cat_id': norad_id, 'metadata': False } response = st.satcat(**params) if len(response) == 1: sat = Satellite( norad_id=norad_id, name=response[0].get('OBJECT_NAME', '') ) if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() if newsat: sat.save() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form})
from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'not found'} try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: pass if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form}) Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellitefrom django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'TBD'} newsat = False try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: newsat = True st = SpaceTrackClient(identity=settings.SPACETRACK_IDENTITY, password=settings.SPACETRACK_PASSWORD) # https://www.space-track.org/basicspacedata/query/class/satcat/NORAD_CAT_ID/3/orderby/INTLDES asc/metadata/false params = { 'norad_cat_id': norad_id, 'metadata': False } response = st.satcat(**params) if len(response) == 1: sat = Satellite( norad_id=norad_id, name=response[0].get('OBJECT_NAME', '') ) if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() if newsat: sat.save() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form})
<commit_before>from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'not found'} try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: pass if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form}) <commit_msg>Create new satellite from spacetrack if satellite audio upload is for a nonexistent satellite<commit_after>from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import * from .models import * @login_required def index(request): return render(request, 'satsound/index.html') @login_required def satellite(request, norad_id): sat = {'pk': norad_id, 'name': 'TBD'} newsat = False try: sat = Satellite.objects.get(pk=norad_id) except Satellite.DoesNotExist: newsat = True st = SpaceTrackClient(identity=settings.SPACETRACK_IDENTITY, password=settings.SPACETRACK_PASSWORD) # https://www.space-track.org/basicspacedata/query/class/satcat/NORAD_CAT_ID/3/orderby/INTLDES asc/metadata/false params = { 'norad_cat_id': norad_id, 'metadata': False } response = st.satcat(**params) if len(response) == 1: sat = Satellite( norad_id=norad_id, name=response[0].get('OBJECT_NAME', '') ) if request.method == 'POST': form = SatelliteAudioForm(request.POST, request.FILES) if form.is_valid(): sa = SatelliteAudio() if newsat: sat.save() sa.satellite = sat sa.user = request.user sa.attribution = form.cleaned_data['attribution'] sa.audio = request.FILES['audio'] sa.type = form.cleaned_data['type'] sa.save() return HttpResponseRedirect(reverse('index')) else: form = SatelliteAudioForm() return render(request, 'satsound/satellite.html', {'sat': sat, 'form': form})
a967b62c5f11b35ac3b31d64975ea62471be8295
script_helpers.py
script_helpers.py
"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser
"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def add_destination_directory(parser): """ Add a destination directory option Parameters ---------- parser : `ArgumentParser` """ arg_help = 'Directory in which output from this script will be stored' parser.add_argument("-d", "--destination-dir", help=arg_help, default=None) def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) add_destination_directory(parser) return parser
Add destination directory to default arguments for scripts
Add destination directory to default arguments for scripts
Python
bsd-3-clause
mwcraig/msumastro
"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser Add destination directory to default arguments for scripts
"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def add_destination_directory(parser): """ Add a destination directory option Parameters ---------- parser : `ArgumentParser` """ arg_help = 'Directory in which output from this script will be stored' parser.add_argument("-d", "--destination-dir", help=arg_help, default=None) def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) add_destination_directory(parser) return parser
<commit_before>"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser <commit_msg>Add destination directory to default arguments for scripts<commit_after>
"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def add_destination_directory(parser): """ Add a destination directory option Parameters ---------- parser : `ArgumentParser` """ arg_help = 'Directory in which output from this script will be stored' parser.add_argument("-d", "--destination-dir", help=arg_help, default=None) def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) add_destination_directory(parser) return parser
"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser Add destination directory to default arguments for scripts"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def add_destination_directory(parser): """ Add a destination directory option Parameters ---------- parser : `ArgumentParser` """ arg_help = 'Directory in which output from this script will be stored' parser.add_argument("-d", "--destination-dir", help=arg_help, default=None) def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) add_destination_directory(parser) return parser
<commit_before>"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser <commit_msg>Add destination directory to default arguments for scripts<commit_after>"""A set of functions to standardize some options for python scripts.""" def setup_parser_help(parser, additional_docs=None): """ Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """ from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """ Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """ verbose_help = "provide more information during processing" parser.add_argument("-v", "--verbose", help=verbose_help, action="store_true") def add_directories(parser, nargs_in='+'): """ Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """ parser.add_argument("dir", metavar='dir', nargs=nargs_in, help="Directory to process") def add_destination_directory(parser): """ Add a destination directory option Parameters ---------- parser : `ArgumentParser` """ arg_help = 'Directory in which output from this script will be stored' parser.add_argument("-d", "--destination-dir", help=arg_help, default=None) def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) add_destination_directory(parser) return parser
1d828dfdb77cf69ce88386c3bb98036d851a891a
data_structures/linked_list.py
data_structures/linked_list.py
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self): pass def size(self): pass def search(self): pass def display(self): pass def remove(self): pass def pop(self): pass
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self, val): '''Insert new Node at head of Linked List.''' self.head = Node(val, self.head) self.length += 1 return None def pop(self): '''Pop the first Node from the head of Linked List, return val''' if self.head is None: raise IndexError else: to_return = self.head self.head = to_return.next self.length -= 1 return to_return.val def size(self): '''Return current length of Linked List.''' return len(self) def search(self, search): '''Return given node of Linked List if present, else None.''' for node in self: if node.val == search: return node else: return None def remove(self, search): '''Remove given node from Linked List, return None.''' for node in self: if node.next == search: node.next = node.next.next return None def display(self): '''Display Linked List as string.''' return repr(self)
Add methods to linked list.
Add methods to linked list.
Python
mit
sjschmidt44/python_data_structures
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self): pass def size(self): pass def search(self): pass def display(self): pass def remove(self): pass def pop(self): pass Add methods to linked list.
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self, val): '''Insert new Node at head of Linked List.''' self.head = Node(val, self.head) self.length += 1 return None def pop(self): '''Pop the first Node from the head of Linked List, return val''' if self.head is None: raise IndexError else: to_return = self.head self.head = to_return.next self.length -= 1 return to_return.val def size(self): '''Return current length of Linked List.''' return len(self) def search(self, search): '''Return given node of Linked List if present, else None.''' for node in self: if node.val == search: return node else: return None def remove(self, search): '''Remove given node from Linked List, return None.''' for node in self: if node.next == search: node.next = node.next.next return None def display(self): '''Display Linked List as string.''' return repr(self)
<commit_before>class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self): pass def size(self): pass def search(self): pass def display(self): pass def remove(self): pass def pop(self): pass <commit_msg>Add methods to linked list.<commit_after>
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self, val): '''Insert new Node at head of Linked List.''' self.head = Node(val, self.head) self.length += 1 return None def pop(self): '''Pop the first Node from the head of Linked List, return val''' if self.head is None: raise IndexError else: to_return = self.head self.head = to_return.next self.length -= 1 return to_return.val def size(self): '''Return current length of Linked List.''' return len(self) def search(self, search): '''Return given node of Linked List if present, else None.''' for node in self: if node.val == search: return node else: return None def remove(self, search): '''Remove given node from Linked List, return None.''' for node in self: if node.next == search: node.next = node.next.next return None def display(self): '''Display Linked List as string.''' return repr(self)
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self): pass def size(self): pass def search(self): pass def display(self): pass def remove(self): pass def pop(self): pass Add methods to linked list.class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self, val): '''Insert new Node at head of Linked List.''' self.head = Node(val, self.head) self.length += 1 return None def pop(self): '''Pop the first Node from the head of Linked List, return val''' if self.head is None: raise IndexError else: to_return = self.head self.head = to_return.next self.length -= 1 return to_return.val def size(self): '''Return current length of Linked List.''' return len(self) def search(self, search): '''Return given node of Linked List if present, else None.''' for node in self: if node.val == search: return node else: return None def remove(self, search): '''Remove given node from Linked List, return None.''' for node in self: if node.next == search: node.next = node.next.next return None def display(self): '''Display Linked List as string.''' return repr(self)
<commit_before>class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self): pass def size(self): pass def search(self): pass def display(self): pass def remove(self): pass def pop(self): pass <commit_msg>Add methods to linked list.<commit_after>class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self, val): '''Insert new Node at head of Linked List.''' self.head = Node(val, self.head) self.length += 1 return None def pop(self): '''Pop the first Node from the head of Linked List, return val''' if self.head is None: raise IndexError else: to_return = self.head self.head = to_return.next self.length -= 1 return to_return.val def size(self): '''Return current length of Linked List.''' return len(self) def search(self, search): '''Return given node of Linked List if present, else None.''' for node in self: if node.val == search: return node else: return None def remove(self, search): '''Remove given node from Linked List, return None.''' for node in self: if node.next == search: node.next = node.next.next return None def display(self): '''Display Linked List as string.''' return repr(self)
788f9f3d917491355e819263c754ec637caaf261
evesrp/util/request.py
evesrp/util/request.py
from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._json_mimetypes + \ self._html_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes
from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._html_mimetypes + \ self._json_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes
Reorder preferred mimetypes to prefer HTML over JSON
Reorder preferred mimetypes to prefer HTML over JSON
Python
bsd-2-clause
paxswill/evesrp,paxswill/evesrp,paxswill/evesrp
from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._json_mimetypes + \ self._html_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes Reorder preferred mimetypes to prefer HTML over JSON
from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._html_mimetypes + \ self._json_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes
<commit_before>from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._json_mimetypes + \ self._html_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes <commit_msg>Reorder preferred mimetypes to prefer HTML over JSON<commit_after>
from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._html_mimetypes + \ self._json_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes
from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._json_mimetypes + \ self._html_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes Reorder preferred mimetypes to prefer HTML over JSONfrom __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._html_mimetypes + \ self._json_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes
<commit_before>from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._json_mimetypes + \ self._html_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes <commit_msg>Reorder preferred mimetypes to prefer HTML over JSON<commit_after>from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._html_mimetypes + \ self._json_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes
9ba1a13de76881c9951e8ca330d6f99b8a279446
devtools/ci/set_doc_version.py
devtools/ci/set_doc_version.py
import os import shutil import msmbuilder.version if msmbuilder.version.release: docversion = msmbuilder.version.short_version else: docversion = 'latest' os.mkdir("doc/_deploy") shutil.copytree("doc/_build", "doc/_deploy/{docversion}" .format(docversion=docversion))
import os import shutil import msmbuilder.version if msmbuilder.version.release: docversion = msmbuilder.version.short_version else: docversion = 'development' os.mkdir("doc/_deploy") shutil.copytree("doc/_build", "doc/_deploy/{docversion}" .format(docversion=docversion))
Send docs to development/ not latest/
Send docs to development/ not latest/
Python
lgpl-2.1
Eigenstate/msmbuilder,brookehus/msmbuilder,rmcgibbo/msmbuilder,rmcgibbo/msmbuilder,mpharrigan/mixtape,rmcgibbo/msmbuilder,dr-nate/msmbuilder,msultan/msmbuilder,peastman/msmbuilder,dr-nate/msmbuilder,brookehus/msmbuilder,msmbuilder/msmbuilder,rmcgibbo/msmbuilder,msultan/msmbuilder,cxhernandez/msmbuilder,dr-nate/msmbuilder,msmbuilder/msmbuilder,cxhernandez/msmbuilder,dr-nate/msmbuilder,rafwiewiora/msmbuilder,peastman/msmbuilder,mpharrigan/mixtape,cxhernandez/msmbuilder,rafwiewiora/msmbuilder,brookehus/msmbuilder,mpharrigan/mixtape,msultan/msmbuilder,msmbuilder/msmbuilder,msultan/msmbuilder,stephenliu1989/msmbuilder,msmbuilder/msmbuilder,peastman/msmbuilder,msmbuilder/msmbuilder,rafwiewiora/msmbuilder,peastman/msmbuilder,brookehus/msmbuilder,brookehus/msmbuilder,Eigenstate/msmbuilder,stephenliu1989/msmbuilder,Eigenstate/msmbuilder,Eigenstate/msmbuilder,peastman/msmbuilder,rafwiewiora/msmbuilder,msultan/msmbuilder,mpharrigan/mixtape,rafwiewiora/msmbuilder,Eigenstate/msmbuilder,stephenliu1989/msmbuilder,cxhernandez/msmbuilder,mpharrigan/mixtape,stephenliu1989/msmbuilder,dr-nate/msmbuilder,cxhernandez/msmbuilder
import os import shutil import msmbuilder.version if msmbuilder.version.release: docversion = msmbuilder.version.short_version else: docversion = 'latest' os.mkdir("doc/_deploy") shutil.copytree("doc/_build", "doc/_deploy/{docversion}" .format(docversion=docversion)) Send docs to development/ not latest/
import os import shutil import msmbuilder.version if msmbuilder.version.release: docversion = msmbuilder.version.short_version else: docversion = 'development' os.mkdir("doc/_deploy") shutil.copytree("doc/_build", "doc/_deploy/{docversion}" .format(docversion=docversion))
<commit_before>import os import shutil import msmbuilder.version if msmbuilder.version.release: docversion = msmbuilder.version.short_version else: docversion = 'latest' os.mkdir("doc/_deploy") shutil.copytree("doc/_build", "doc/_deploy/{docversion}" .format(docversion=docversion)) <commit_msg>Send docs to development/ not latest/<commit_after>
import os import shutil import msmbuilder.version if msmbuilder.version.release: docversion = msmbuilder.version.short_version else: docversion = 'development' os.mkdir("doc/_deploy") shutil.copytree("doc/_build", "doc/_deploy/{docversion}" .format(docversion=docversion))
import os import shutil import msmbuilder.version if msmbuilder.version.release: docversion = msmbuilder.version.short_version else: docversion = 'latest' os.mkdir("doc/_deploy") shutil.copytree("doc/_build", "doc/_deploy/{docversion}" .format(docversion=docversion)) Send docs to development/ not latest/import os import shutil import msmbuilder.version if msmbuilder.version.release: docversion = msmbuilder.version.short_version else: docversion = 'development' os.mkdir("doc/_deploy") shutil.copytree("doc/_build", "doc/_deploy/{docversion}" .format(docversion=docversion))
<commit_before>import os import shutil import msmbuilder.version if msmbuilder.version.release: docversion = msmbuilder.version.short_version else: docversion = 'latest' os.mkdir("doc/_deploy") shutil.copytree("doc/_build", "doc/_deploy/{docversion}" .format(docversion=docversion)) <commit_msg>Send docs to development/ not latest/<commit_after>import os import shutil import msmbuilder.version if msmbuilder.version.release: docversion = msmbuilder.version.short_version else: docversion = 'development' os.mkdir("doc/_deploy") shutil.copytree("doc/_build", "doc/_deploy/{docversion}" .format(docversion=docversion))
46ab82bf387b6f7d13abc94bacb16b76bc292080
util/cron/verify_config_names.py
util/cron/verify_config_names.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Ensure filenames for test-*.bash scripts match the config name registered inside them. """ from __future__ import print_function import sys for line in sys.stdin.readlines(): filename, content = line.split(':', 1) config_name = content.split('"')[1] expected_script_name = 'test-{0}.bash'.format(config_name) if not filename.endswith(expected_script_name): print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format( filename, config_name))
#!/usr/bin/env python # -*- coding: utf-8 -*- """Ensure filenames for test-*.bash scripts match the config name registered inside them. """ from __future__ import print_function import os.path import re import sys for line in sys.stdin.readlines(): filename, content = line.split(':', 1) filename_parts = os.path.splitext(filename) filename_base = filename_parts[0] pattern = re.compile(r'CHPL_NIGHTLY_TEST_CONFIG_NAME="(?P<config_name>[a-z0-9\-.]+)"', re.IGNORECASE) match = pattern.search(content) config_name = None if match is not None: config_name = match.group('config_name') else: print('[ERROR] Could not find nightly test config name ' 'in: {0}'.format(filename)) sys.exit(0) if not filename_base.endswith(config_name): print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format( filename, config_name))
Update config name verify script to work with the .bat files.
Update config name verify script to work with the .bat files.
Python
apache-2.0
chizarlicious/chapel,CoryMcCartan/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,hildeth/chapel,chizarlicious/chapel,hildeth/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,chizarlicious/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,hildeth/chapel
#!/usr/bin/env python # -*- coding: utf-8 -*- """Ensure filenames for test-*.bash scripts match the config name registered inside them. """ from __future__ import print_function import sys for line in sys.stdin.readlines(): filename, content = line.split(':', 1) config_name = content.split('"')[1] expected_script_name = 'test-{0}.bash'.format(config_name) if not filename.endswith(expected_script_name): print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format( filename, config_name)) Update config name verify script to work with the .bat files.
#!/usr/bin/env python # -*- coding: utf-8 -*- """Ensure filenames for test-*.bash scripts match the config name registered inside them. """ from __future__ import print_function import os.path import re import sys for line in sys.stdin.readlines(): filename, content = line.split(':', 1) filename_parts = os.path.splitext(filename) filename_base = filename_parts[0] pattern = re.compile(r'CHPL_NIGHTLY_TEST_CONFIG_NAME="(?P<config_name>[a-z0-9\-.]+)"', re.IGNORECASE) match = pattern.search(content) config_name = None if match is not None: config_name = match.group('config_name') else: print('[ERROR] Could not find nightly test config name ' 'in: {0}'.format(filename)) sys.exit(0) if not filename_base.endswith(config_name): print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format( filename, config_name))
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """Ensure filenames for test-*.bash scripts match the config name registered inside them. """ from __future__ import print_function import sys for line in sys.stdin.readlines(): filename, content = line.split(':', 1) config_name = content.split('"')[1] expected_script_name = 'test-{0}.bash'.format(config_name) if not filename.endswith(expected_script_name): print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format( filename, config_name)) <commit_msg>Update config name verify script to work with the .bat files.<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- """Ensure filenames for test-*.bash scripts match the config name registered inside them. """ from __future__ import print_function import os.path import re import sys for line in sys.stdin.readlines(): filename, content = line.split(':', 1) filename_parts = os.path.splitext(filename) filename_base = filename_parts[0] pattern = re.compile(r'CHPL_NIGHTLY_TEST_CONFIG_NAME="(?P<config_name>[a-z0-9\-.]+)"', re.IGNORECASE) match = pattern.search(content) config_name = None if match is not None: config_name = match.group('config_name') else: print('[ERROR] Could not find nightly test config name ' 'in: {0}'.format(filename)) sys.exit(0) if not filename_base.endswith(config_name): print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format( filename, config_name))
#!/usr/bin/env python # -*- coding: utf-8 -*- """Ensure filenames for test-*.bash scripts match the config name registered inside them. """ from __future__ import print_function import sys for line in sys.stdin.readlines(): filename, content = line.split(':', 1) config_name = content.split('"')[1] expected_script_name = 'test-{0}.bash'.format(config_name) if not filename.endswith(expected_script_name): print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format( filename, config_name)) Update config name verify script to work with the .bat files.#!/usr/bin/env python # -*- coding: utf-8 -*- """Ensure filenames for test-*.bash scripts match the config name registered inside them. """ from __future__ import print_function import os.path import re import sys for line in sys.stdin.readlines(): filename, content = line.split(':', 1) filename_parts = os.path.splitext(filename) filename_base = filename_parts[0] pattern = re.compile(r'CHPL_NIGHTLY_TEST_CONFIG_NAME="(?P<config_name>[a-z0-9\-.]+)"', re.IGNORECASE) match = pattern.search(content) config_name = None if match is not None: config_name = match.group('config_name') else: print('[ERROR] Could not find nightly test config name ' 'in: {0}'.format(filename)) sys.exit(0) if not filename_base.endswith(config_name): print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format( filename, config_name))
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """Ensure filenames for test-*.bash scripts match the config name registered inside them. """ from __future__ import print_function import sys for line in sys.stdin.readlines(): filename, content = line.split(':', 1) config_name = content.split('"')[1] expected_script_name = 'test-{0}.bash'.format(config_name) if not filename.endswith(expected_script_name): print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format( filename, config_name)) <commit_msg>Update config name verify script to work with the .bat files.<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- """Ensure filenames for test-*.bash scripts match the config name registered inside them. """ from __future__ import print_function import os.path import re import sys for line in sys.stdin.readlines(): filename, content = line.split(':', 1) filename_parts = os.path.splitext(filename) filename_base = filename_parts[0] pattern = re.compile(r'CHPL_NIGHTLY_TEST_CONFIG_NAME="(?P<config_name>[a-z0-9\-.]+)"', re.IGNORECASE) match = pattern.search(content) config_name = None if match is not None: config_name = match.group('config_name') else: print('[ERROR] Could not find nightly test config name ' 'in: {0}'.format(filename)) sys.exit(0) if not filename_base.endswith(config_name): print('[ERROR] test script name: "{0}" does not match its config name: "{1}"'.format( filename, config_name))
637953efa1f71b123bb28c8404b79219a6bd6b3e
fablab-businessplan.py
fablab-businessplan.py
# -*- encoding: utf-8 -*- # # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: MIT # import xlsxwriter # Create the file workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx') # Create the worksheets expenses = workbook.add_worksheet('Expenses') activities = workbook.add_worksheet('Activities') membership = workbook.add_worksheet('Membership') total = workbook.add_worksheet('Total') # Add content to the Expenses worksheet expenses.write('A1', 'Hello world') # Save and close the file workbook.close()
# -*- encoding: utf-8 -*- # # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: MIT # import xlsxwriter # Create document ------------------------------------------------------------- # Create the file workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx') # Create the worksheets expenses = workbook.add_worksheet('Expenses') activities = workbook.add_worksheet('Activities') membership = workbook.add_worksheet('Membership') total = workbook.add_worksheet('Total') # Create styles ------------------------------------------------------------- # Add a bold style to highlight heading cells bold_style = workbook.add_format() bold_style.set_font_color('white') bold_style.set_bg_color('F56A2F') bold_style.set_bold() # Add a total style to highlight total cells total_style = workbook.add_format() total_style.set_font_color('red') total_style.set_bg_color('FAECC5') total_style.set_bold() # Add a style for money money_style = workbook.add_format({'num_format': u'€#,##0'}) # Add green/red color for positive/negative numbers #money_style.set_num_format('[Green]General;[Red]-General;General') # Add a number format for cells with money #money_style.set_num_format('0 "dollar and" .00 "cents"') # Add content ------------------------------------------------------------- # Add content to the Expenses worksheet expenses.write('A1', 'Hello world', bold_style) expenses.write('A2', '12.33', money_style) expenses.write('A3', 'Total', total_style) # Save document ------------------------------------------------------------- # Save and close the file workbook.close()
Add structure and first styles
Add structure and first styles
Python
mit
openp2pdesign/FabLab-BusinessPlan
# -*- encoding: utf-8 -*- # # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: MIT # import xlsxwriter # Create the file workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx') # Create the worksheets expenses = workbook.add_worksheet('Expenses') activities = workbook.add_worksheet('Activities') membership = workbook.add_worksheet('Membership') total = workbook.add_worksheet('Total') # Add content to the Expenses worksheet expenses.write('A1', 'Hello world') # Save and close the file workbook.close()Add structure and first styles
# -*- encoding: utf-8 -*- # # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: MIT # import xlsxwriter # Create document ------------------------------------------------------------- # Create the file workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx') # Create the worksheets expenses = workbook.add_worksheet('Expenses') activities = workbook.add_worksheet('Activities') membership = workbook.add_worksheet('Membership') total = workbook.add_worksheet('Total') # Create styles ------------------------------------------------------------- # Add a bold style to highlight heading cells bold_style = workbook.add_format() bold_style.set_font_color('white') bold_style.set_bg_color('F56A2F') bold_style.set_bold() # Add a total style to highlight total cells total_style = workbook.add_format() total_style.set_font_color('red') total_style.set_bg_color('FAECC5') total_style.set_bold() # Add a style for money money_style = workbook.add_format({'num_format': u'€#,##0'}) # Add green/red color for positive/negative numbers #money_style.set_num_format('[Green]General;[Red]-General;General') # Add a number format for cells with money #money_style.set_num_format('0 "dollar and" .00 "cents"') # Add content ------------------------------------------------------------- # Add content to the Expenses worksheet expenses.write('A1', 'Hello world', bold_style) expenses.write('A2', '12.33', money_style) expenses.write('A3', 'Total', total_style) # Save document ------------------------------------------------------------- # Save and close the file workbook.close()
<commit_before># -*- encoding: utf-8 -*- # # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: MIT # import xlsxwriter # Create the file workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx') # Create the worksheets expenses = workbook.add_worksheet('Expenses') activities = workbook.add_worksheet('Activities') membership = workbook.add_worksheet('Membership') total = workbook.add_worksheet('Total') # Add content to the Expenses worksheet expenses.write('A1', 'Hello world') # Save and close the file workbook.close()<commit_msg>Add structure and first styles<commit_after>
# -*- encoding: utf-8 -*- # # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: MIT # import xlsxwriter # Create document ------------------------------------------------------------- # Create the file workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx') # Create the worksheets expenses = workbook.add_worksheet('Expenses') activities = workbook.add_worksheet('Activities') membership = workbook.add_worksheet('Membership') total = workbook.add_worksheet('Total') # Create styles ------------------------------------------------------------- # Add a bold style to highlight heading cells bold_style = workbook.add_format() bold_style.set_font_color('white') bold_style.set_bg_color('F56A2F') bold_style.set_bold() # Add a total style to highlight total cells total_style = workbook.add_format() total_style.set_font_color('red') total_style.set_bg_color('FAECC5') total_style.set_bold() # Add a style for money money_style = workbook.add_format({'num_format': u'€#,##0'}) # Add green/red color for positive/negative numbers #money_style.set_num_format('[Green]General;[Red]-General;General') # Add a number format for cells with money #money_style.set_num_format('0 "dollar and" .00 "cents"') # Add content ------------------------------------------------------------- # Add content to the Expenses worksheet expenses.write('A1', 'Hello world', bold_style) expenses.write('A2', '12.33', money_style) expenses.write('A3', 'Total', total_style) # Save document ------------------------------------------------------------- # Save and close the file workbook.close()
# -*- encoding: utf-8 -*- # # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: MIT # import xlsxwriter # Create the file workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx') # Create the worksheets expenses = workbook.add_worksheet('Expenses') activities = workbook.add_worksheet('Activities') membership = workbook.add_worksheet('Membership') total = workbook.add_worksheet('Total') # Add content to the Expenses worksheet expenses.write('A1', 'Hello world') # Save and close the file workbook.close()Add structure and first styles# -*- encoding: utf-8 -*- # # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: MIT # import xlsxwriter # Create document ------------------------------------------------------------- # Create the file workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx') # Create the worksheets expenses = workbook.add_worksheet('Expenses') activities = workbook.add_worksheet('Activities') membership = workbook.add_worksheet('Membership') total = workbook.add_worksheet('Total') # Create styles ------------------------------------------------------------- # Add a bold style to highlight heading cells bold_style = workbook.add_format() bold_style.set_font_color('white') bold_style.set_bg_color('F56A2F') bold_style.set_bold() # Add a total style to highlight total cells total_style = workbook.add_format() total_style.set_font_color('red') total_style.set_bg_color('FAECC5') total_style.set_bold() # Add a style for money money_style = workbook.add_format({'num_format': u'€#,##0'}) # Add green/red color for positive/negative numbers #money_style.set_num_format('[Green]General;[Red]-General;General') # Add a number format for cells with money #money_style.set_num_format('0 "dollar and" .00 "cents"') # Add content ------------------------------------------------------------- # Add content to the Expenses worksheet expenses.write('A1', 'Hello world', bold_style) expenses.write('A2', '12.33', money_style) expenses.write('A3', 'Total', total_style) # Save document ------------------------------------------------------------- # Save and close the file workbook.close()
<commit_before># -*- encoding: utf-8 -*- # # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: MIT # import xlsxwriter # Create the file workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx') # Create the worksheets expenses = workbook.add_worksheet('Expenses') activities = workbook.add_worksheet('Activities') membership = workbook.add_worksheet('Membership') total = workbook.add_worksheet('Total') # Add content to the Expenses worksheet expenses.write('A1', 'Hello world') # Save and close the file workbook.close()<commit_msg>Add structure and first styles<commit_after># -*- encoding: utf-8 -*- # # Author: Massimo Menichinelli # Homepage: http://www.openp2pdesign.org # License: MIT # import xlsxwriter # Create document ------------------------------------------------------------- # Create the file workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx') # Create the worksheets expenses = workbook.add_worksheet('Expenses') activities = workbook.add_worksheet('Activities') membership = workbook.add_worksheet('Membership') total = workbook.add_worksheet('Total') # Create styles ------------------------------------------------------------- # Add a bold style to highlight heading cells bold_style = workbook.add_format() bold_style.set_font_color('white') bold_style.set_bg_color('F56A2F') bold_style.set_bold() # Add a total style to highlight total cells total_style = workbook.add_format() total_style.set_font_color('red') total_style.set_bg_color('FAECC5') total_style.set_bold() # Add a style for money money_style = workbook.add_format({'num_format': u'€#,##0'}) # Add green/red color for positive/negative numbers #money_style.set_num_format('[Green]General;[Red]-General;General') # Add a number format for cells with money #money_style.set_num_format('0 "dollar and" .00 "cents"') # Add content ------------------------------------------------------------- # Add content to the Expenses worksheet expenses.write('A1', 'Hello world', bold_style) expenses.write('A2', '12.33', money_style) expenses.write('A3', 'Total', total_style) # Save document ------------------------------------------------------------- # Save and close the file workbook.close()
54691f9be052e5564ca0e5c6a503e641ea3142e1
keras/layers/normalization.py
keras/layers/normalization.py
from ..layers.core import Layer from ..utils.theano_utils import shared_zeros from .. import initializations class BatchNormalization(Layer): ''' Reference: Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift http://arxiv.org/pdf/1502.03167v3.pdf ''' def __init__(self, input_shape, epsilon=1e-6, weights=None): self.init = initializations.get("uniform") self.input_shape = input_shape self.epsilon = epsilon self.gamma = self.init((self.input_shape)) self.beta = shared_zeros(self.input_shape) self.params = [self.gamma, self.beta] if weights is not None: self.set_weights(weights) def output(self, train): X = self.get_input(train) X_normed = (X - X.mean(keepdims=True)) / (X.std(keepdims=True) + self.epsilon) out = self.gamma * X_normed + self.beta return out def get_config(self): return {"name":self.__class__.__name__, "input_shape":self.input_shape, "epsilon":self.epsilon}
from ..layers.core import Layer from ..utils.theano_utils import shared_zeros from .. import initializations import theano.tensor as T class BatchNormalization(Layer): ''' Reference: Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift http://arxiv.org/pdf/1502.03167v3.pdf mode: 0 -> featurewise normalization 1 -> samplewise normalization (may sometimes outperform featurewise mode) ''' def __init__(self, input_shape, epsilon=1e-6, mode=0, weights=None): self.init = initializations.get("uniform") self.input_shape = input_shape self.epsilon = epsilon self.mode = mode self.gamma = self.init((self.input_shape)) self.beta = shared_zeros(self.input_shape) self.params = [self.gamma, self.beta] if weights is not None: self.set_weights(weights) def output(self, train): X = self.get_input(train) if self.mode == 0: m = X.mean(axis=0) # manual computation of std to prevent NaNs std = T.mean((X-m)**2 + self.epsilon, axis=0) ** 0.5 X_normed = (X - m) / (std + self.epsilon) elif self.mode == 1: m = X.mean(axis=-1, keepdims=True) std = X.std(axis=-1, keepdims=True) X_normed = (X - m) / (std + self.epsilon) out = self.gamma * X_normed + self.beta return out def get_config(self): return {"name":self.__class__.__name__, "input_shape":self.input_shape, "epsilon":self.epsilon, "mode":self.mode}
Add modes to BatchNormalization, fix BN issues
Add modes to BatchNormalization, fix BN issues
Python
mit
yingzha/keras,imcomking/Convolutional-GRU-keras-extension-,jayhetee/keras,why11002526/keras,marchick209/keras,relh/keras,mikekestemont/keras,florentchandelier/keras,jbolinge/keras,tencrance/keras,meanmee/keras,kuza55/keras,nehz/keras,keras-team/keras,EderSantana/keras,kemaswill/keras,abayowbo/keras,dhruvparamhans/keras,cheng6076/keras,jasonyaw/keras,3dconv/keras,ogrisel/keras,marcelo-amancio/keras,jalexvig/keras,johmathe/keras,ekamioka/keras,stonebig/keras,Smerity/keras,dribnet/keras,Aureliu/keras,nt/keras,nebw/keras,ashhher3/keras,ypkang/keras,fmacias64/keras,gamer13/keras,harshhemani/keras,LIBOTAO/keras,rudaoshi/keras,danielforsyth/keras,hhaoyan/keras,jiumem/keras,Yingmin-Li/keras,iScienceLuvr/keras,dxj19831029/keras,aleju/keras,nzer0/keras,bottler/keras,printedheart/keras,wxs/keras,jfsantos/keras,ml-lab/keras,navyjeff/keras,wubr2000/keras,rlkelly/keras,zxytim/keras,gavinmh/keras,keras-team/keras,brainwater/keras,pthaike/keras,DeepGnosis/keras,pjadzinsky/keras,jonberliner/keras,rodrigob/keras,zxsted/keras,vseledkin/keras,asampat3090/keras,OlafLee/keras,daviddiazvico/keras,Cadene/keras,llcao/keras,sjuvekar/keras,zhmz90/keras,stephenbalaban/keras,dolaameng/keras,kfoss/keras,jimgoo/keras,iamtrask/keras,xiaoda99/keras,keskarnitish/keras,untom/keras,happyboy310/keras,bboalimoe/keras,DLlearn/keras,JasonTam/keras,kod3r/keras,MagicSen/keras,chenych11/keras,jmportilla/keras,jslhs/keras,xurantju/keras,saurav111/keras,zhangxujinsh/keras,amy12xx/keras,cmyr/keras,ledbetdr/keras,eulerreich/keras,cvfish/keras,jhauswald/keras
from ..layers.core import Layer from ..utils.theano_utils import shared_zeros from .. import initializations class BatchNormalization(Layer): ''' Reference: Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift http://arxiv.org/pdf/1502.03167v3.pdf ''' def __init__(self, input_shape, epsilon=1e-6, weights=None): self.init = initializations.get("uniform") self.input_shape = input_shape self.epsilon = epsilon self.gamma = self.init((self.input_shape)) self.beta = shared_zeros(self.input_shape) self.params = [self.gamma, self.beta] if weights is not None: self.set_weights(weights) def output(self, train): X = self.get_input(train) X_normed = (X - X.mean(keepdims=True)) / (X.std(keepdims=True) + self.epsilon) out = self.gamma * X_normed + self.beta return out def get_config(self): return {"name":self.__class__.__name__, "input_shape":self.input_shape, "epsilon":self.epsilon}Add modes to BatchNormalization, fix BN issues
from ..layers.core import Layer from ..utils.theano_utils import shared_zeros from .. import initializations import theano.tensor as T class BatchNormalization(Layer): ''' Reference: Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift http://arxiv.org/pdf/1502.03167v3.pdf mode: 0 -> featurewise normalization 1 -> samplewise normalization (may sometimes outperform featurewise mode) ''' def __init__(self, input_shape, epsilon=1e-6, mode=0, weights=None): self.init = initializations.get("uniform") self.input_shape = input_shape self.epsilon = epsilon self.mode = mode self.gamma = self.init((self.input_shape)) self.beta = shared_zeros(self.input_shape) self.params = [self.gamma, self.beta] if weights is not None: self.set_weights(weights) def output(self, train): X = self.get_input(train) if self.mode == 0: m = X.mean(axis=0) # manual computation of std to prevent NaNs std = T.mean((X-m)**2 + self.epsilon, axis=0) ** 0.5 X_normed = (X - m) / (std + self.epsilon) elif self.mode == 1: m = X.mean(axis=-1, keepdims=True) std = X.std(axis=-1, keepdims=True) X_normed = (X - m) / (std + self.epsilon) out = self.gamma * X_normed + self.beta return out def get_config(self): return {"name":self.__class__.__name__, "input_shape":self.input_shape, "epsilon":self.epsilon, "mode":self.mode}
<commit_before>from ..layers.core import Layer from ..utils.theano_utils import shared_zeros from .. import initializations class BatchNormalization(Layer): ''' Reference: Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift http://arxiv.org/pdf/1502.03167v3.pdf ''' def __init__(self, input_shape, epsilon=1e-6, weights=None): self.init = initializations.get("uniform") self.input_shape = input_shape self.epsilon = epsilon self.gamma = self.init((self.input_shape)) self.beta = shared_zeros(self.input_shape) self.params = [self.gamma, self.beta] if weights is not None: self.set_weights(weights) def output(self, train): X = self.get_input(train) X_normed = (X - X.mean(keepdims=True)) / (X.std(keepdims=True) + self.epsilon) out = self.gamma * X_normed + self.beta return out def get_config(self): return {"name":self.__class__.__name__, "input_shape":self.input_shape, "epsilon":self.epsilon}<commit_msg>Add modes to BatchNormalization, fix BN issues<commit_after>
from ..layers.core import Layer from ..utils.theano_utils import shared_zeros from .. import initializations import theano.tensor as T class BatchNormalization(Layer): ''' Reference: Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift http://arxiv.org/pdf/1502.03167v3.pdf mode: 0 -> featurewise normalization 1 -> samplewise normalization (may sometimes outperform featurewise mode) ''' def __init__(self, input_shape, epsilon=1e-6, mode=0, weights=None): self.init = initializations.get("uniform") self.input_shape = input_shape self.epsilon = epsilon self.mode = mode self.gamma = self.init((self.input_shape)) self.beta = shared_zeros(self.input_shape) self.params = [self.gamma, self.beta] if weights is not None: self.set_weights(weights) def output(self, train): X = self.get_input(train) if self.mode == 0: m = X.mean(axis=0) # manual computation of std to prevent NaNs std = T.mean((X-m)**2 + self.epsilon, axis=0) ** 0.5 X_normed = (X - m) / (std + self.epsilon) elif self.mode == 1: m = X.mean(axis=-1, keepdims=True) std = X.std(axis=-1, keepdims=True) X_normed = (X - m) / (std + self.epsilon) out = self.gamma * X_normed + self.beta return out def get_config(self): return {"name":self.__class__.__name__, "input_shape":self.input_shape, "epsilon":self.epsilon, "mode":self.mode}
from ..layers.core import Layer from ..utils.theano_utils import shared_zeros from .. import initializations class BatchNormalization(Layer): ''' Reference: Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift http://arxiv.org/pdf/1502.03167v3.pdf ''' def __init__(self, input_shape, epsilon=1e-6, weights=None): self.init = initializations.get("uniform") self.input_shape = input_shape self.epsilon = epsilon self.gamma = self.init((self.input_shape)) self.beta = shared_zeros(self.input_shape) self.params = [self.gamma, self.beta] if weights is not None: self.set_weights(weights) def output(self, train): X = self.get_input(train) X_normed = (X - X.mean(keepdims=True)) / (X.std(keepdims=True) + self.epsilon) out = self.gamma * X_normed + self.beta return out def get_config(self): return {"name":self.__class__.__name__, "input_shape":self.input_shape, "epsilon":self.epsilon}Add modes to BatchNormalization, fix BN issuesfrom ..layers.core import Layer from ..utils.theano_utils import shared_zeros from .. import initializations import theano.tensor as T class BatchNormalization(Layer): ''' Reference: Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift http://arxiv.org/pdf/1502.03167v3.pdf mode: 0 -> featurewise normalization 1 -> samplewise normalization (may sometimes outperform featurewise mode) ''' def __init__(self, input_shape, epsilon=1e-6, mode=0, weights=None): self.init = initializations.get("uniform") self.input_shape = input_shape self.epsilon = epsilon self.mode = mode self.gamma = self.init((self.input_shape)) self.beta = shared_zeros(self.input_shape) self.params = [self.gamma, self.beta] if weights is not None: self.set_weights(weights) def output(self, train): X = self.get_input(train) if self.mode == 0: m = X.mean(axis=0) # manual computation of std to prevent NaNs std = T.mean((X-m)**2 + self.epsilon, axis=0) ** 0.5 X_normed = (X - m) / (std + self.epsilon) elif self.mode == 1: m = X.mean(axis=-1, keepdims=True) std = X.std(axis=-1, keepdims=True) X_normed = (X - m) / (std + self.epsilon) out = self.gamma * X_normed + self.beta return out def get_config(self): return {"name":self.__class__.__name__, "input_shape":self.input_shape, "epsilon":self.epsilon, "mode":self.mode}
<commit_before>from ..layers.core import Layer from ..utils.theano_utils import shared_zeros from .. import initializations class BatchNormalization(Layer): ''' Reference: Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift http://arxiv.org/pdf/1502.03167v3.pdf ''' def __init__(self, input_shape, epsilon=1e-6, weights=None): self.init = initializations.get("uniform") self.input_shape = input_shape self.epsilon = epsilon self.gamma = self.init((self.input_shape)) self.beta = shared_zeros(self.input_shape) self.params = [self.gamma, self.beta] if weights is not None: self.set_weights(weights) def output(self, train): X = self.get_input(train) X_normed = (X - X.mean(keepdims=True)) / (X.std(keepdims=True) + self.epsilon) out = self.gamma * X_normed + self.beta return out def get_config(self): return {"name":self.__class__.__name__, "input_shape":self.input_shape, "epsilon":self.epsilon}<commit_msg>Add modes to BatchNormalization, fix BN issues<commit_after>from ..layers.core import Layer from ..utils.theano_utils import shared_zeros from .. import initializations import theano.tensor as T class BatchNormalization(Layer): ''' Reference: Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift http://arxiv.org/pdf/1502.03167v3.pdf mode: 0 -> featurewise normalization 1 -> samplewise normalization (may sometimes outperform featurewise mode) ''' def __init__(self, input_shape, epsilon=1e-6, mode=0, weights=None): self.init = initializations.get("uniform") self.input_shape = input_shape self.epsilon = epsilon self.mode = mode self.gamma = self.init((self.input_shape)) self.beta = shared_zeros(self.input_shape) self.params = [self.gamma, self.beta] if weights is not None: self.set_weights(weights) def output(self, train): X = self.get_input(train) if self.mode == 0: m = X.mean(axis=0) # manual computation of std to prevent NaNs std = T.mean((X-m)**2 + self.epsilon, axis=0) ** 0.5 X_normed = (X - m) / (std + self.epsilon) elif self.mode == 1: m = X.mean(axis=-1, keepdims=True) std = X.std(axis=-1, keepdims=True) X_normed = (X - m) / (std + self.epsilon) out = self.gamma * X_normed + self.beta return out def get_config(self): return {"name":self.__class__.__name__, "input_shape":self.input_shape, "epsilon":self.epsilon, "mode":self.mode}
3b30a036f9f9fb861c0ed1711b5bd967756a072d
flask_cors/__init__.py
flask_cors/__init__.py
# -*- coding: utf-8 -*- """ flask_cors ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())
# -*- coding: utf-8 -*- """ flask_cors ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass # Set initial level to WARN. Users must manually enable logging for # flask_cors to see our logging. rootlogger = logging.getLogger(__name__) rootlogger.addHandler(NullHandler()) if rootlogger.level == logging.NOTSET: rootlogger.setLevel(logging.WARN)
Disable logging for flask_cors by default
Disable logging for flask_cors by default
Python
mit
corydolphin/flask-cors,ashleysommer/sanic-cors
# -*- coding: utf-8 -*- """ flask_cors ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())Disable logging for flask_cors by default
# -*- coding: utf-8 -*- """ flask_cors ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass # Set initial level to WARN. Users must manually enable logging for # flask_cors to see our logging. rootlogger = logging.getLogger(__name__) rootlogger.addHandler(NullHandler()) if rootlogger.level == logging.NOTSET: rootlogger.setLevel(logging.WARN)
<commit_before># -*- coding: utf-8 -*- """ flask_cors ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())<commit_msg>Disable logging for flask_cors by default<commit_after>
# -*- coding: utf-8 -*- """ flask_cors ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass # Set initial level to WARN. Users must manually enable logging for # flask_cors to see our logging. rootlogger = logging.getLogger(__name__) rootlogger.addHandler(NullHandler()) if rootlogger.level == logging.NOTSET: rootlogger.setLevel(logging.WARN)
# -*- coding: utf-8 -*- """ flask_cors ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())Disable logging for flask_cors by default# -*- coding: utf-8 -*- """ flask_cors ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass # Set initial level to WARN. Users must manually enable logging for # flask_cors to see our logging. rootlogger = logging.getLogger(__name__) rootlogger.addHandler(NullHandler()) if rootlogger.level == logging.NOTSET: rootlogger.setLevel(logging.WARN)
<commit_before># -*- coding: utf-8 -*- """ flask_cors ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())<commit_msg>Disable logging for flask_cors by default<commit_after># -*- coding: utf-8 -*- """ flask_cors ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass # Set initial level to WARN. Users must manually enable logging for # flask_cors to see our logging. rootlogger = logging.getLogger(__name__) rootlogger.addHandler(NullHandler()) if rootlogger.level == logging.NOTSET: rootlogger.setLevel(logging.WARN)
3699cc594d9a4f02d24308cb41b8757124616f78
boltiot/requesting.py
boltiot/requesting.py
from boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message":str(err)}) def request_test(function): result = function return result
from boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message": "ERROR: " + str(err)}) def request_test(function): result = function return result
Add ERROR: keyword in error message return
Add ERROR: keyword in error message return
Python
mit
Inventrom/bolt-api-python
from boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message":str(err)}) def request_test(function): result = function return result Add ERROR: keyword in error message return
from boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message": "ERROR: " + str(err)}) def request_test(function): result = function return result
<commit_before>from boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message":str(err)}) def request_test(function): result = function return result <commit_msg>Add ERROR: keyword in error message return<commit_after>
from boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message": "ERROR: " + str(err)}) def request_test(function): result = function return result
from boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message":str(err)}) def request_test(function): result = function return result Add ERROR: keyword in error message returnfrom boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message": "ERROR: " + str(err)}) def request_test(function): result = function return result
<commit_before>from boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message":str(err)}) def request_test(function): result = function return result <commit_msg>Add ERROR: keyword in error message return<commit_after>from boltiot.urls import url import requests def request_from(url, *kwargs): try: response = str(requests.get(url.format(*kwargs)).text) return response except requests.exceptions.ConnectionError as err: return str({"success":"0", "message":"A Connection error occurred"}) except requests.exceptions.Timeout as err: return str({"success":"0", "message":"The request timed out"}) except requests.exceptions.TooManyRedirects as err : return str({"success":"0", "message":"Too many redirects"}) except requests.exceptions.RequestException as err: return str({"success":"0", "message":"Not able to handle error"}) except Exception as err: return str({"success":"0", "message": "ERROR: " + str(err)}) def request_test(function): result = function return result
7feb7eeba7e591f7a0c1cbf3b72efb099bd9f644
hijack/urls.py
hijack/urls.py
from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') )
from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[^@]+@[^@]+\.[^@]+)/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') )
Use a more liberal/naive approach to regex checking for an email
Use a more liberal/naive approach to regex checking for an email The problem with the old method is that it does not support - Internationalized TLDs, domains or users, such as .xn--4gbrim domains - Geographic TLDs, such as .europe - ICANN-era TLDs, such as .audio and .clothing The new regex still matches <anything>@<anything>.<anything> so we still have some mail characteristics in the URL.
Python
mit
arteria/django-hijack,arteria/django-hijack,arteria/django-hijack
from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') ) Use a more liberal/naive approach to regex checking for an email The problem with the old method is that it does not support - Internationalized TLDs, domains or users, such as .xn--4gbrim domains - Geographic TLDs, such as .europe - ICANN-era TLDs, such as .audio and .clothing The new regex still matches <anything>@<anything>.<anything> so we still have some mail characteristics in the URL.
from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[^@]+@[^@]+\.[^@]+)/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') )
<commit_before>from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') ) <commit_msg>Use a more liberal/naive approach to regex checking for an email The problem with the old method is that it does not support - Internationalized TLDs, domains or users, such as .xn--4gbrim domains - Geographic TLDs, such as .europe - ICANN-era TLDs, such as .audio and .clothing The new regex still matches <anything>@<anything>.<anything> so we still have some mail characteristics in the URL.<commit_after>
from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[^@]+@[^@]+\.[^@]+)/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') )
from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') ) Use a more liberal/naive approach to regex checking for an email The problem with the old method is that it does not support - Internationalized TLDs, domains or users, such as .xn--4gbrim domains - Geographic TLDs, such as .europe - ICANN-era TLDs, such as .audio and .clothing The new regex still matches <anything>@<anything>.<anything> so we still have some mail characteristics in the URL.from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[^@]+@[^@]+\.[^@]+)/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') )
<commit_before>from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') ) <commit_msg>Use a more liberal/naive approach to regex checking for an email The problem with the old method is that it does not support - Internationalized TLDs, domains or users, such as .xn--4gbrim domains - Geographic TLDs, such as .europe - ICANN-era TLDs, such as .audio and .clothing The new regex still matches <anything>@<anything>.<anything> so we still have some mail characteristics in the URL.<commit_after>from compat import patterns, url from django.conf import settings urlpatterns = patterns('hijack.views', url(r'^release-hijack/$', 'release_hijack', name='release_hijack'), ) if getattr(settings, "HIJACK_NOTIFY_ADMIN", False): urlpatterns += patterns('hijack.views', url(r'^disable-hijack-warning/$', 'disable_hijack_warning', name='disable_hijack_warning'), ) hijacking_user_attributes = getattr(settings, "ALLOWED_HIJACKING_USER_ATTRIBUTES", False) if not hijacking_user_attributes or 'email' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^email/(?P<email>[^@]+@[^@]+\.[^@]+)/$', 'login_with_email', name='login_with_email') ) if not hijacking_user_attributes or 'username' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^username/(?P<username>\w+)/$', 'login_with_username', name='login_with_username'), ) if not hijacking_user_attributes or 'user_id' in hijacking_user_attributes: urlpatterns += patterns('hijack.views', url(r'^(?P<user_id>\w+)/$', 'login_with_id', name='login_with_id') )
5f6ba1b3a1f2798df1e17d2c29785f04939bd847
src/test/testlexer.py
src/test/testlexer.py
from cStringIO import StringIO from nose.tools import * from parse import EeyoreLexer def _lex( string ): return list( EeyoreLexer.Lexer( StringIO( string ) ) ) def _assert_token( token, ( text, tp ) ): assert_equal( token.getText(), text ) assert_equal( token.getType(), tp ) def test_hello_world(): tokens = _lex( """print( "Hello, world!" )""" ) _assert_token( tokens[0], ( "print", EeyoreLexer.SYMBOL ) ) _assert_token( tokens[1], ( "(", EeyoreLexer.LPAREN ) ) _assert_token( tokens[2], ( "Hello, world!", EeyoreLexer.STRING ) ) _assert_token( tokens[3], ( ")", EeyoreLexer.RPAREN ) ) # TODO: test line numbers
from cStringIO import StringIO from nose.tools import * from parse import EeyoreLexer def _lex( string ): return list( EeyoreLexer.Lexer( StringIO( string ) ) ) def _assert_token( token, text, tp, line = None, col = None ): assert_equal( token.getText(), text ) assert_equal( token.getType(), tp ) if line is not None: assert_equal( token.getLine(), line ) if col is not None: assert_equal( token.getColumn(), col ) def test_hello_world(): tokens = _lex( """print( "Hello, world!" )""" ) _assert_token( tokens[0], "print", EeyoreLexer.SYMBOL, 1, 1 ) _assert_token( tokens[1], "(", EeyoreLexer.LPAREN, 1, 6 ) _assert_token( tokens[2], "Hello, world!", EeyoreLexer.STRING, 1, 8 ) _assert_token( tokens[3], ")", EeyoreLexer.RPAREN, 1, 24 ) assert_equal( len( tokens ), 4 )
Test line numbers in lexer tests.
Test line numbers in lexer tests.
Python
mit
andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper
from cStringIO import StringIO from nose.tools import * from parse import EeyoreLexer def _lex( string ): return list( EeyoreLexer.Lexer( StringIO( string ) ) ) def _assert_token( token, ( text, tp ) ): assert_equal( token.getText(), text ) assert_equal( token.getType(), tp ) def test_hello_world(): tokens = _lex( """print( "Hello, world!" )""" ) _assert_token( tokens[0], ( "print", EeyoreLexer.SYMBOL ) ) _assert_token( tokens[1], ( "(", EeyoreLexer.LPAREN ) ) _assert_token( tokens[2], ( "Hello, world!", EeyoreLexer.STRING ) ) _assert_token( tokens[3], ( ")", EeyoreLexer.RPAREN ) ) # TODO: test line numbers Test line numbers in lexer tests.
from cStringIO import StringIO from nose.tools import * from parse import EeyoreLexer def _lex( string ): return list( EeyoreLexer.Lexer( StringIO( string ) ) ) def _assert_token( token, text, tp, line = None, col = None ): assert_equal( token.getText(), text ) assert_equal( token.getType(), tp ) if line is not None: assert_equal( token.getLine(), line ) if col is not None: assert_equal( token.getColumn(), col ) def test_hello_world(): tokens = _lex( """print( "Hello, world!" )""" ) _assert_token( tokens[0], "print", EeyoreLexer.SYMBOL, 1, 1 ) _assert_token( tokens[1], "(", EeyoreLexer.LPAREN, 1, 6 ) _assert_token( tokens[2], "Hello, world!", EeyoreLexer.STRING, 1, 8 ) _assert_token( tokens[3], ")", EeyoreLexer.RPAREN, 1, 24 ) assert_equal( len( tokens ), 4 )
<commit_before> from cStringIO import StringIO from nose.tools import * from parse import EeyoreLexer def _lex( string ): return list( EeyoreLexer.Lexer( StringIO( string ) ) ) def _assert_token( token, ( text, tp ) ): assert_equal( token.getText(), text ) assert_equal( token.getType(), tp ) def test_hello_world(): tokens = _lex( """print( "Hello, world!" )""" ) _assert_token( tokens[0], ( "print", EeyoreLexer.SYMBOL ) ) _assert_token( tokens[1], ( "(", EeyoreLexer.LPAREN ) ) _assert_token( tokens[2], ( "Hello, world!", EeyoreLexer.STRING ) ) _assert_token( tokens[3], ( ")", EeyoreLexer.RPAREN ) ) # TODO: test line numbers <commit_msg>Test line numbers in lexer tests.<commit_after>
from cStringIO import StringIO from nose.tools import * from parse import EeyoreLexer def _lex( string ): return list( EeyoreLexer.Lexer( StringIO( string ) ) ) def _assert_token( token, text, tp, line = None, col = None ): assert_equal( token.getText(), text ) assert_equal( token.getType(), tp ) if line is not None: assert_equal( token.getLine(), line ) if col is not None: assert_equal( token.getColumn(), col ) def test_hello_world(): tokens = _lex( """print( "Hello, world!" )""" ) _assert_token( tokens[0], "print", EeyoreLexer.SYMBOL, 1, 1 ) _assert_token( tokens[1], "(", EeyoreLexer.LPAREN, 1, 6 ) _assert_token( tokens[2], "Hello, world!", EeyoreLexer.STRING, 1, 8 ) _assert_token( tokens[3], ")", EeyoreLexer.RPAREN, 1, 24 ) assert_equal( len( tokens ), 4 )
from cStringIO import StringIO from nose.tools import * from parse import EeyoreLexer def _lex( string ): return list( EeyoreLexer.Lexer( StringIO( string ) ) ) def _assert_token( token, ( text, tp ) ): assert_equal( token.getText(), text ) assert_equal( token.getType(), tp ) def test_hello_world(): tokens = _lex( """print( "Hello, world!" )""" ) _assert_token( tokens[0], ( "print", EeyoreLexer.SYMBOL ) ) _assert_token( tokens[1], ( "(", EeyoreLexer.LPAREN ) ) _assert_token( tokens[2], ( "Hello, world!", EeyoreLexer.STRING ) ) _assert_token( tokens[3], ( ")", EeyoreLexer.RPAREN ) ) # TODO: test line numbers Test line numbers in lexer tests. from cStringIO import StringIO from nose.tools import * from parse import EeyoreLexer def _lex( string ): return list( EeyoreLexer.Lexer( StringIO( string ) ) ) def _assert_token( token, text, tp, line = None, col = None ): assert_equal( token.getText(), text ) assert_equal( token.getType(), tp ) if line is not None: assert_equal( token.getLine(), line ) if col is not None: assert_equal( token.getColumn(), col ) def test_hello_world(): tokens = _lex( """print( "Hello, world!" )""" ) _assert_token( tokens[0], "print", EeyoreLexer.SYMBOL, 1, 1 ) _assert_token( tokens[1], "(", EeyoreLexer.LPAREN, 1, 6 ) _assert_token( tokens[2], "Hello, world!", EeyoreLexer.STRING, 1, 8 ) _assert_token( tokens[3], ")", EeyoreLexer.RPAREN, 1, 24 ) assert_equal( len( tokens ), 4 )
<commit_before> from cStringIO import StringIO from nose.tools import * from parse import EeyoreLexer def _lex( string ): return list( EeyoreLexer.Lexer( StringIO( string ) ) ) def _assert_token( token, ( text, tp ) ): assert_equal( token.getText(), text ) assert_equal( token.getType(), tp ) def test_hello_world(): tokens = _lex( """print( "Hello, world!" )""" ) _assert_token( tokens[0], ( "print", EeyoreLexer.SYMBOL ) ) _assert_token( tokens[1], ( "(", EeyoreLexer.LPAREN ) ) _assert_token( tokens[2], ( "Hello, world!", EeyoreLexer.STRING ) ) _assert_token( tokens[3], ( ")", EeyoreLexer.RPAREN ) ) # TODO: test line numbers <commit_msg>Test line numbers in lexer tests.<commit_after> from cStringIO import StringIO from nose.tools import * from parse import EeyoreLexer def _lex( string ): return list( EeyoreLexer.Lexer( StringIO( string ) ) ) def _assert_token( token, text, tp, line = None, col = None ): assert_equal( token.getText(), text ) assert_equal( token.getType(), tp ) if line is not None: assert_equal( token.getLine(), line ) if col is not None: assert_equal( token.getColumn(), col ) def test_hello_world(): tokens = _lex( """print( "Hello, world!" )""" ) _assert_token( tokens[0], "print", EeyoreLexer.SYMBOL, 1, 1 ) _assert_token( tokens[1], "(", EeyoreLexer.LPAREN, 1, 6 ) _assert_token( tokens[2], "Hello, world!", EeyoreLexer.STRING, 1, 8 ) _assert_token( tokens[3], ")", EeyoreLexer.RPAREN, 1, 24 ) assert_equal( len( tokens ), 4 )
a8811b5a746533467281437575b1fbaf776e5df9
nhlstats/__init__.py
nhlstats/__init__.py
import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def GetDataForGame(game): pass def GetDataForGames(games=[]): for game in games: GetDataForGame(game) def GetGames(active=True, beginning=None, end=None): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. beginning and end allow you set a range for the search, with no end indicating until the time. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': GetDataForGames(GetGames(active=True)) # Otherwise we can look to update finished games elif action == 'update': GetDataForGames(GetGames(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action)
import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def get_data_for_game(game): pass def get_data_for_games(games=[]): for game in games: get_data_for_game(game) def get_games(active=True, beginning=None, end=None): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. beginning and end allow you set a range for the search, with no end indicating until the time. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': get_data_for_games(get_games(active=True)) # Otherwise we can look to update finished games elif action == 'update': get_data_for_games(get_games(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action)
Fix case in function names to be PEP8 compatible
Fix case in function names to be PEP8 compatible
Python
mit
fancystats/nhlstats
import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def GetDataForGame(game): pass def GetDataForGames(games=[]): for game in games: GetDataForGame(game) def GetGames(active=True, beginning=None, end=None): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. beginning and end allow you set a range for the search, with no end indicating until the time. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': GetDataForGames(GetGames(active=True)) # Otherwise we can look to update finished games elif action == 'update': GetDataForGames(GetGames(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action) Fix case in function names to be PEP8 compatible
import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def get_data_for_game(game): pass def get_data_for_games(games=[]): for game in games: get_data_for_game(game) def get_games(active=True, beginning=None, end=None): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. beginning and end allow you set a range for the search, with no end indicating until the time. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': get_data_for_games(get_games(active=True)) # Otherwise we can look to update finished games elif action == 'update': get_data_for_games(get_games(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action)
<commit_before> import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def GetDataForGame(game): pass def GetDataForGames(games=[]): for game in games: GetDataForGame(game) def GetGames(active=True, beginning=None, end=None): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. beginning and end allow you set a range for the search, with no end indicating until the time. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': GetDataForGames(GetGames(active=True)) # Otherwise we can look to update finished games elif action == 'update': GetDataForGames(GetGames(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action) <commit_msg>Fix case in function names to be PEP8 compatible<commit_after>
import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def get_data_for_game(game): pass def get_data_for_games(games=[]): for game in games: get_data_for_game(game) def get_games(active=True, beginning=None, end=None): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. beginning and end allow you set a range for the search, with no end indicating until the time. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': get_data_for_games(get_games(active=True)) # Otherwise we can look to update finished games elif action == 'update': get_data_for_games(get_games(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action)
import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def GetDataForGame(game): pass def GetDataForGames(games=[]): for game in games: GetDataForGame(game) def GetGames(active=True, beginning=None, end=None): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. beginning and end allow you set a range for the search, with no end indicating until the time. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': GetDataForGames(GetGames(active=True)) # Otherwise we can look to update finished games elif action == 'update': GetDataForGames(GetGames(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action) Fix case in function names to be PEP8 compatible import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def get_data_for_game(game): pass def get_data_for_games(games=[]): for game in games: get_data_for_game(game) def get_games(active=True, beginning=None, end=None): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. beginning and end allow you set a range for the search, with no end indicating until the time. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': get_data_for_games(get_games(active=True)) # Otherwise we can look to update finished games elif action == 'update': get_data_for_games(get_games(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action)
<commit_before> import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def GetDataForGame(game): pass def GetDataForGames(games=[]): for game in games: GetDataForGame(game) def GetGames(active=True, beginning=None, end=None): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. beginning and end allow you set a range for the search, with no end indicating until the time. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': GetDataForGames(GetGames(active=True)) # Otherwise we can look to update finished games elif action == 'update': GetDataForGames(GetGames(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action) <commit_msg>Fix case in function names to be PEP8 compatible<commit_after> import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def get_data_for_game(game): pass def get_data_for_games(games=[]): for game in games: get_data_for_game(game) def get_games(active=True, beginning=None, end=None): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. beginning and end allow you set a range for the search, with no end indicating until the time. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': get_data_for_games(get_games(active=True)) # Otherwise we can look to update finished games elif action == 'update': get_data_for_games(get_games(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action)
ebe7e1012ddc1286d61de5c5a565aff9cd4faedf
stdnum/jp/__init__.py
stdnum/jp/__init__.py
# __init__.py - collection of Japanese numbers # coding: utf-8 # # Copyright (C) 2019 Alan Hettinger # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Japanese numbers."""
# __init__.py - collection of Japanese numbers # coding: utf-8 # # Copyright (C) 2019 Alan Hettinger # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Japanese numbers.""" from stdnum.jp import cn as vat # noqa: F401
Add missing vat alias for Japan
Add missing vat alias for Japan
Python
lgpl-2.1
arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum
# __init__.py - collection of Japanese numbers # coding: utf-8 # # Copyright (C) 2019 Alan Hettinger # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Japanese numbers.""" Add missing vat alias for Japan
# __init__.py - collection of Japanese numbers # coding: utf-8 # # Copyright (C) 2019 Alan Hettinger # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Japanese numbers.""" from stdnum.jp import cn as vat # noqa: F401
<commit_before># __init__.py - collection of Japanese numbers # coding: utf-8 # # Copyright (C) 2019 Alan Hettinger # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Japanese numbers.""" <commit_msg>Add missing vat alias for Japan<commit_after>
# __init__.py - collection of Japanese numbers # coding: utf-8 # # Copyright (C) 2019 Alan Hettinger # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Japanese numbers.""" from stdnum.jp import cn as vat # noqa: F401
# __init__.py - collection of Japanese numbers # coding: utf-8 # # Copyright (C) 2019 Alan Hettinger # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Japanese numbers.""" Add missing vat alias for Japan# __init__.py - collection of Japanese numbers # coding: utf-8 # # Copyright (C) 2019 Alan Hettinger # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Japanese numbers.""" from stdnum.jp import cn as vat # noqa: F401
<commit_before># __init__.py - collection of Japanese numbers # coding: utf-8 # # Copyright (C) 2019 Alan Hettinger # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Japanese numbers.""" <commit_msg>Add missing vat alias for Japan<commit_after># __init__.py - collection of Japanese numbers # coding: utf-8 # # Copyright (C) 2019 Alan Hettinger # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Collection of Japanese numbers.""" from stdnum.jp import cn as vat # noqa: F401
e0308672543d0bbe8309351c9d63732d0d0e3e30
steel/fields/mixin.py
steel/fields/mixin.py
from gettext import gettext as _ class Fixed: _("A mixin that ensures the presence of a predetermined value") def __init__(self, value, *args, **kwargs): self.value = value super(Fixed, self).__init__(*args, **kwargs) def encode(self, value): # Always encode the fixed value return super(Fixed, self).encode(self.value) def decode(self, value): value = super(Fixed, self).decode(value) # Check that the value matches what it should be if value != self.value: raise ValueError(_("Expected %r, got %r" % (self.value, value))) return value
from gettext import gettext as _ class Fixed: _("A mixin that ensures the presence of a predetermined value") def __init__(self, value, *args, **kwargs): self.value = value # Pass the value in as a default as well, to make # sure it goes through when no value was supplied super(Fixed, self).__init__(*args, default=value, **kwargs) def encode(self, value): # Always encode the fixed value return super(Fixed, self).encode(self.value) def decode(self, value): value = super(Fixed, self).decode(value) # Check that the value matches what it should be if value != self.value: raise ValueError(_("Expected %r, got %r" % (self.value, value))) return value
Include fixed values as defaults
Include fixed values as defaults I'm not a big fan of this approach, but it avoids a good bit of code duplication
Python
bsd-3-clause
gulopine/steel-experiment
from gettext import gettext as _ class Fixed: _("A mixin that ensures the presence of a predetermined value") def __init__(self, value, *args, **kwargs): self.value = value super(Fixed, self).__init__(*args, **kwargs) def encode(self, value): # Always encode the fixed value return super(Fixed, self).encode(self.value) def decode(self, value): value = super(Fixed, self).decode(value) # Check that the value matches what it should be if value != self.value: raise ValueError(_("Expected %r, got %r" % (self.value, value))) return value Include fixed values as defaults I'm not a big fan of this approach, but it avoids a good bit of code duplication
from gettext import gettext as _ class Fixed: _("A mixin that ensures the presence of a predetermined value") def __init__(self, value, *args, **kwargs): self.value = value # Pass the value in as a default as well, to make # sure it goes through when no value was supplied super(Fixed, self).__init__(*args, default=value, **kwargs) def encode(self, value): # Always encode the fixed value return super(Fixed, self).encode(self.value) def decode(self, value): value = super(Fixed, self).decode(value) # Check that the value matches what it should be if value != self.value: raise ValueError(_("Expected %r, got %r" % (self.value, value))) return value
<commit_before>from gettext import gettext as _ class Fixed: _("A mixin that ensures the presence of a predetermined value") def __init__(self, value, *args, **kwargs): self.value = value super(Fixed, self).__init__(*args, **kwargs) def encode(self, value): # Always encode the fixed value return super(Fixed, self).encode(self.value) def decode(self, value): value = super(Fixed, self).decode(value) # Check that the value matches what it should be if value != self.value: raise ValueError(_("Expected %r, got %r" % (self.value, value))) return value <commit_msg>Include fixed values as defaults I'm not a big fan of this approach, but it avoids a good bit of code duplication<commit_after>
from gettext import gettext as _ class Fixed: _("A mixin that ensures the presence of a predetermined value") def __init__(self, value, *args, **kwargs): self.value = value # Pass the value in as a default as well, to make # sure it goes through when no value was supplied super(Fixed, self).__init__(*args, default=value, **kwargs) def encode(self, value): # Always encode the fixed value return super(Fixed, self).encode(self.value) def decode(self, value): value = super(Fixed, self).decode(value) # Check that the value matches what it should be if value != self.value: raise ValueError(_("Expected %r, got %r" % (self.value, value))) return value
from gettext import gettext as _ class Fixed: _("A mixin that ensures the presence of a predetermined value") def __init__(self, value, *args, **kwargs): self.value = value super(Fixed, self).__init__(*args, **kwargs) def encode(self, value): # Always encode the fixed value return super(Fixed, self).encode(self.value) def decode(self, value): value = super(Fixed, self).decode(value) # Check that the value matches what it should be if value != self.value: raise ValueError(_("Expected %r, got %r" % (self.value, value))) return value Include fixed values as defaults I'm not a big fan of this approach, but it avoids a good bit of code duplicationfrom gettext import gettext as _ class Fixed: _("A mixin that ensures the presence of a predetermined value") def __init__(self, value, *args, **kwargs): self.value = value # Pass the value in as a default as well, to make # sure it goes through when no value was supplied super(Fixed, self).__init__(*args, default=value, **kwargs) def encode(self, value): # Always encode the fixed value return super(Fixed, self).encode(self.value) def decode(self, value): value = super(Fixed, self).decode(value) # Check that the value matches what it should be if value != self.value: raise ValueError(_("Expected %r, got %r" % (self.value, value))) return value
<commit_before>from gettext import gettext as _ class Fixed: _("A mixin that ensures the presence of a predetermined value") def __init__(self, value, *args, **kwargs): self.value = value super(Fixed, self).__init__(*args, **kwargs) def encode(self, value): # Always encode the fixed value return super(Fixed, self).encode(self.value) def decode(self, value): value = super(Fixed, self).decode(value) # Check that the value matches what it should be if value != self.value: raise ValueError(_("Expected %r, got %r" % (self.value, value))) return value <commit_msg>Include fixed values as defaults I'm not a big fan of this approach, but it avoids a good bit of code duplication<commit_after>from gettext import gettext as _ class Fixed: _("A mixin that ensures the presence of a predetermined value") def __init__(self, value, *args, **kwargs): self.value = value # Pass the value in as a default as well, to make # sure it goes through when no value was supplied super(Fixed, self).__init__(*args, default=value, **kwargs) def encode(self, value): # Always encode the fixed value return super(Fixed, self).encode(self.value) def decode(self, value): value = super(Fixed, self).decode(value) # Check that the value matches what it should be if value != self.value: raise ValueError(_("Expected %r, got %r" % (self.value, value))) return value
ad477313b38ff97c69c5bd281a540138c04354e2
githistorydata/main.py
githistorydata/main.py
import subprocess import sys from githistorydata.csv import Csv from githistorydata.expand_commits import expand_authors, expand_lines from githistorydata.git import Git from githistorydata.rawgit import RawGit def main( argv, out, err ): try: git = Git( RawGit() ) csv = Csv( out, ( "Hash", "Date", "Author", "Added", "Removed", "File" ) ) for cod in expand_lines( git, expand_authors( git.log() ) ): csv.line( ( cod.commit_hash, cod.date.date().isoformat(), cod.author, cod.added, cod.removed, cod.filename, ) ) except subprocess.CalledProcessError, e: print str( e ) sys.exit( 1 ) finally: out.flush()
import subprocess import sys from githistorydata.csv import Csv from githistorydata.expand_commits import expand_authors, expand_lines from githistorydata.git import Git from githistorydata.rawgit import RawGit def main( argv, out, err ): try: git = Git( RawGit() ) csv = Csv( out, ( "Commit", "Date", "Author", "Added", "Removed", "File" ) ) for cod in expand_lines( git, expand_authors( git.log() ) ): csv.line( ( cod.commit_hash, cod.date.date().isoformat(), cod.author, cod.added, cod.removed, cod.filename, ) ) except subprocess.CalledProcessError, e: print str( e ) sys.exit( 1 ) finally: out.flush()
Rename column "Hash" to "Commit".
Rename column "Hash" to "Commit".
Python
bsd-2-clause
andybalaam/git-history-data,andybalaam/git-history-data
import subprocess import sys from githistorydata.csv import Csv from githistorydata.expand_commits import expand_authors, expand_lines from githistorydata.git import Git from githistorydata.rawgit import RawGit def main( argv, out, err ): try: git = Git( RawGit() ) csv = Csv( out, ( "Hash", "Date", "Author", "Added", "Removed", "File" ) ) for cod in expand_lines( git, expand_authors( git.log() ) ): csv.line( ( cod.commit_hash, cod.date.date().isoformat(), cod.author, cod.added, cod.removed, cod.filename, ) ) except subprocess.CalledProcessError, e: print str( e ) sys.exit( 1 ) finally: out.flush() Rename column "Hash" to "Commit".
import subprocess import sys from githistorydata.csv import Csv from githistorydata.expand_commits import expand_authors, expand_lines from githistorydata.git import Git from githistorydata.rawgit import RawGit def main( argv, out, err ): try: git = Git( RawGit() ) csv = Csv( out, ( "Commit", "Date", "Author", "Added", "Removed", "File" ) ) for cod in expand_lines( git, expand_authors( git.log() ) ): csv.line( ( cod.commit_hash, cod.date.date().isoformat(), cod.author, cod.added, cod.removed, cod.filename, ) ) except subprocess.CalledProcessError, e: print str( e ) sys.exit( 1 ) finally: out.flush()
<commit_before> import subprocess import sys from githistorydata.csv import Csv from githistorydata.expand_commits import expand_authors, expand_lines from githistorydata.git import Git from githistorydata.rawgit import RawGit def main( argv, out, err ): try: git = Git( RawGit() ) csv = Csv( out, ( "Hash", "Date", "Author", "Added", "Removed", "File" ) ) for cod in expand_lines( git, expand_authors( git.log() ) ): csv.line( ( cod.commit_hash, cod.date.date().isoformat(), cod.author, cod.added, cod.removed, cod.filename, ) ) except subprocess.CalledProcessError, e: print str( e ) sys.exit( 1 ) finally: out.flush() <commit_msg>Rename column "Hash" to "Commit".<commit_after>
import subprocess import sys from githistorydata.csv import Csv from githistorydata.expand_commits import expand_authors, expand_lines from githistorydata.git import Git from githistorydata.rawgit import RawGit def main( argv, out, err ): try: git = Git( RawGit() ) csv = Csv( out, ( "Commit", "Date", "Author", "Added", "Removed", "File" ) ) for cod in expand_lines( git, expand_authors( git.log() ) ): csv.line( ( cod.commit_hash, cod.date.date().isoformat(), cod.author, cod.added, cod.removed, cod.filename, ) ) except subprocess.CalledProcessError, e: print str( e ) sys.exit( 1 ) finally: out.flush()
import subprocess import sys from githistorydata.csv import Csv from githistorydata.expand_commits import expand_authors, expand_lines from githistorydata.git import Git from githistorydata.rawgit import RawGit def main( argv, out, err ): try: git = Git( RawGit() ) csv = Csv( out, ( "Hash", "Date", "Author", "Added", "Removed", "File" ) ) for cod in expand_lines( git, expand_authors( git.log() ) ): csv.line( ( cod.commit_hash, cod.date.date().isoformat(), cod.author, cod.added, cod.removed, cod.filename, ) ) except subprocess.CalledProcessError, e: print str( e ) sys.exit( 1 ) finally: out.flush() Rename column "Hash" to "Commit". import subprocess import sys from githistorydata.csv import Csv from githistorydata.expand_commits import expand_authors, expand_lines from githistorydata.git import Git from githistorydata.rawgit import RawGit def main( argv, out, err ): try: git = Git( RawGit() ) csv = Csv( out, ( "Commit", "Date", "Author", "Added", "Removed", "File" ) ) for cod in expand_lines( git, expand_authors( git.log() ) ): csv.line( ( cod.commit_hash, cod.date.date().isoformat(), cod.author, cod.added, cod.removed, cod.filename, ) ) except subprocess.CalledProcessError, e: print str( e ) sys.exit( 1 ) finally: out.flush()
<commit_before> import subprocess import sys from githistorydata.csv import Csv from githistorydata.expand_commits import expand_authors, expand_lines from githistorydata.git import Git from githistorydata.rawgit import RawGit def main( argv, out, err ): try: git = Git( RawGit() ) csv = Csv( out, ( "Hash", "Date", "Author", "Added", "Removed", "File" ) ) for cod in expand_lines( git, expand_authors( git.log() ) ): csv.line( ( cod.commit_hash, cod.date.date().isoformat(), cod.author, cod.added, cod.removed, cod.filename, ) ) except subprocess.CalledProcessError, e: print str( e ) sys.exit( 1 ) finally: out.flush() <commit_msg>Rename column "Hash" to "Commit".<commit_after> import subprocess import sys from githistorydata.csv import Csv from githistorydata.expand_commits import expand_authors, expand_lines from githistorydata.git import Git from githistorydata.rawgit import RawGit def main( argv, out, err ): try: git = Git( RawGit() ) csv = Csv( out, ( "Commit", "Date", "Author", "Added", "Removed", "File" ) ) for cod in expand_lines( git, expand_authors( git.log() ) ): csv.line( ( cod.commit_hash, cod.date.date().isoformat(), cod.author, cod.added, cod.removed, cod.filename, ) ) except subprocess.CalledProcessError, e: print str( e ) sys.exit( 1 ) finally: out.flush()
a287c1e7a6e96a2a2143e9270a5f9b2ec295022e
fireplace/cards/removed/all.py
fireplace/cards/removed/all.py
""" Cards removed from the game """ from ..utils import * # Adrenaline Rush class NEW1_006: action = drawCard combo = drawCards(2) # Bolstered (Bloodsail Corsair) class NEW1_025e: Health = 1
""" Cards removed from the game """ from ..utils import * # Dagger Mastery class CS2_083: def action(self): if self.hero.weapon: self.hero.weapon.buff("CS2_083e") else: self.hero.summon("CS2_082") class CS2_083e: Atk = 1 # Adrenaline Rush class NEW1_006: action = drawCard combo = drawCards(2) # Bolstered (Bloodsail Corsair) class NEW1_025e: Health = 1
Implement the old Dagger Mastery
Implement the old Dagger Mastery
Python
agpl-3.0
Ragowit/fireplace,beheh/fireplace,NightKev/fireplace,liujimj/fireplace,amw2104/fireplace,butozerca/fireplace,oftc-ftw/fireplace,jleclanche/fireplace,liujimj/fireplace,butozerca/fireplace,oftc-ftw/fireplace,smallnamespace/fireplace,Meerkov/fireplace,smallnamespace/fireplace,amw2104/fireplace,Ragowit/fireplace,Meerkov/fireplace
""" Cards removed from the game """ from ..utils import * # Adrenaline Rush class NEW1_006: action = drawCard combo = drawCards(2) # Bolstered (Bloodsail Corsair) class NEW1_025e: Health = 1 Implement the old Dagger Mastery
""" Cards removed from the game """ from ..utils import * # Dagger Mastery class CS2_083: def action(self): if self.hero.weapon: self.hero.weapon.buff("CS2_083e") else: self.hero.summon("CS2_082") class CS2_083e: Atk = 1 # Adrenaline Rush class NEW1_006: action = drawCard combo = drawCards(2) # Bolstered (Bloodsail Corsair) class NEW1_025e: Health = 1
<commit_before>""" Cards removed from the game """ from ..utils import * # Adrenaline Rush class NEW1_006: action = drawCard combo = drawCards(2) # Bolstered (Bloodsail Corsair) class NEW1_025e: Health = 1 <commit_msg>Implement the old Dagger Mastery<commit_after>
""" Cards removed from the game """ from ..utils import * # Dagger Mastery class CS2_083: def action(self): if self.hero.weapon: self.hero.weapon.buff("CS2_083e") else: self.hero.summon("CS2_082") class CS2_083e: Atk = 1 # Adrenaline Rush class NEW1_006: action = drawCard combo = drawCards(2) # Bolstered (Bloodsail Corsair) class NEW1_025e: Health = 1
""" Cards removed from the game """ from ..utils import * # Adrenaline Rush class NEW1_006: action = drawCard combo = drawCards(2) # Bolstered (Bloodsail Corsair) class NEW1_025e: Health = 1 Implement the old Dagger Mastery""" Cards removed from the game """ from ..utils import * # Dagger Mastery class CS2_083: def action(self): if self.hero.weapon: self.hero.weapon.buff("CS2_083e") else: self.hero.summon("CS2_082") class CS2_083e: Atk = 1 # Adrenaline Rush class NEW1_006: action = drawCard combo = drawCards(2) # Bolstered (Bloodsail Corsair) class NEW1_025e: Health = 1
<commit_before>""" Cards removed from the game """ from ..utils import * # Adrenaline Rush class NEW1_006: action = drawCard combo = drawCards(2) # Bolstered (Bloodsail Corsair) class NEW1_025e: Health = 1 <commit_msg>Implement the old Dagger Mastery<commit_after>""" Cards removed from the game """ from ..utils import * # Dagger Mastery class CS2_083: def action(self): if self.hero.weapon: self.hero.weapon.buff("CS2_083e") else: self.hero.summon("CS2_082") class CS2_083e: Atk = 1 # Adrenaline Rush class NEW1_006: action = drawCard combo = drawCards(2) # Bolstered (Bloodsail Corsair) class NEW1_025e: Health = 1
a6a405cbcb3ba2696d63473f0f7892b18ac0e6dc
application.py
application.py
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) cloud_watch_handler = watchtower.CloudWatchLogHandler() logging.basicConfig(level=logging.INFO) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run()
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) cloud_watch_handler = watchtower.CloudWatchLogHandler() levels = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG } logging.basicConfig(level=levels[os.getenv('EQ_LOG_LEVEL') or 'WARNING']) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run()
Allow logging level to be selected through environment variable
Allow logging level to be selected through environment variable
Python
mit
ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) cloud_watch_handler = watchtower.CloudWatchLogHandler() logging.basicConfig(level=logging.INFO) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run() Allow logging level to be selected through environment variable
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) cloud_watch_handler = watchtower.CloudWatchLogHandler() levels = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG } logging.basicConfig(level=levels[os.getenv('EQ_LOG_LEVEL') or 'WARNING']) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run()
<commit_before>#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) cloud_watch_handler = watchtower.CloudWatchLogHandler() logging.basicConfig(level=logging.INFO) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run() <commit_msg>Allow logging level to be selected through environment variable<commit_after>
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) cloud_watch_handler = watchtower.CloudWatchLogHandler() levels = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG } logging.basicConfig(level=levels[os.getenv('EQ_LOG_LEVEL') or 'WARNING']) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run()
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) cloud_watch_handler = watchtower.CloudWatchLogHandler() logging.basicConfig(level=logging.INFO) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run() Allow logging level to be selected through environment variable#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) cloud_watch_handler = watchtower.CloudWatchLogHandler() levels = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG } logging.basicConfig(level=levels[os.getenv('EQ_LOG_LEVEL') or 'WARNING']) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run()
<commit_before>#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) cloud_watch_handler = watchtower.CloudWatchLogHandler() logging.basicConfig(level=logging.INFO) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run() <commit_msg>Allow logging level to be selected through environment variable<commit_after>#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) cloud_watch_handler = watchtower.CloudWatchLogHandler() levels = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG } logging.basicConfig(level=levels[os.getenv('EQ_LOG_LEVEL') or 'WARNING']) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run()
6184fb10b7a48df4e7c75485ed12b4a389dd3c3c
avatar/conf.py
avatar/conf.py
from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,))
from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'https://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,))
Use https to gravatar url
Use https to gravatar url
Python
bsd-3-clause
therocode/django-avatar,dannybrowne86/django-avatar,brajeshvit/avatarmodule,barbuza/django-avatar,imgmix/django-avatar,grantmcconnaughey/django-avatar,jezdez/django-avatar,ad-m/django-avatar,MachineandMagic/django-avatar,jezdez/django-avatar,grantmcconnaughey/django-avatar,brajeshvit/avatarmodule,therocode/django-avatar,barbuza/django-avatar,dannybrowne86/django-avatar,imgmix/django-avatar,MachineandMagic/django-avatar,ad-m/django-avatar
from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,)) Use https to gravatar url
from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'https://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,))
<commit_before>from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,)) <commit_msg>Use https to gravatar url<commit_after>
from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'https://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,))
from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,)) Use https to gravatar urlfrom django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'https://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,))
<commit_before>from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,)) <commit_msg>Use https to gravatar url<commit_after>from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 80 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'https://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE,) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,))
01fce49f6ecb0a5c6ff5db858efd0ea1e88608b3
sensors/dylos.py
sensors/dylos.py
import logging import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.UART as UART import serial DYLOS_POWER_PIN = "P8_10" LOGGER = logging.getLogger(__name__) class Dylos: def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5): self.running = True # Setup UART UART.setup("UART1") # Make sure Dylos sensor is turned on GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT) GPIO.output(DYLOS_POWER_PIN, GPIO.LOW) self.ser = serial.Serial(port=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=timeout) if not self.ser.isOpen(): self.ser.open() def read(self): # Keep reading from serial port until we get some data while True: line = self.ser.readline() if not self.running: raise Exception("Stop reading from serial port") if line != b'': break LOGGER.debug("Read from serial port: %s", line) small, large = [int(x.strip()) for x in line.split(b',')] LOGGER.debug("Small: %s, Large: %s", small, large) return {"small": small, "large": large} def stop(self): self.running = False self.ser.close()
import logging import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.UART as UART import serial DYLOS_POWER_PIN = "P8_10" LOGGER = logging.getLogger(__name__) class Dylos: def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5): self.running = True # Setup UART UART.setup("UART1") # Make sure Dylos sensor is turned on GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT) GPIO.output(DYLOS_POWER_PIN, GPIO.LOW) self.ser = serial.Serial(port=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=timeout) if not self.ser.isOpen(): self.ser.open() def read(self): # Keep reading from serial port until we get some data while True: line = self.ser.readline() if not self.running: raise Exception("Stop reading from serial port") if line != b'': break LOGGER.debug("Read from serial port: %s", line) small, large = [int(x.strip()) for x in line.split(b',')] LOGGER.debug("Small: %s, Large: %s", small, large) return {"small": small, "large": large} def stop(self): self.running = False GPIO.cleanup(DYLOS_POWER_PIN) self.ser.close()
Fix bug with fan turning itself off
Fix bug with fan turning itself off This would happen when the service was restarted. In the stopping code, I added a call to clean up.
Python
apache-2.0
VDL-PRISM/dylos
import logging import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.UART as UART import serial DYLOS_POWER_PIN = "P8_10" LOGGER = logging.getLogger(__name__) class Dylos: def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5): self.running = True # Setup UART UART.setup("UART1") # Make sure Dylos sensor is turned on GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT) GPIO.output(DYLOS_POWER_PIN, GPIO.LOW) self.ser = serial.Serial(port=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=timeout) if not self.ser.isOpen(): self.ser.open() def read(self): # Keep reading from serial port until we get some data while True: line = self.ser.readline() if not self.running: raise Exception("Stop reading from serial port") if line != b'': break LOGGER.debug("Read from serial port: %s", line) small, large = [int(x.strip()) for x in line.split(b',')] LOGGER.debug("Small: %s, Large: %s", small, large) return {"small": small, "large": large} def stop(self): self.running = False self.ser.close() Fix bug with fan turning itself off This would happen when the service was restarted. In the stopping code, I added a call to clean up.
import logging import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.UART as UART import serial DYLOS_POWER_PIN = "P8_10" LOGGER = logging.getLogger(__name__) class Dylos: def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5): self.running = True # Setup UART UART.setup("UART1") # Make sure Dylos sensor is turned on GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT) GPIO.output(DYLOS_POWER_PIN, GPIO.LOW) self.ser = serial.Serial(port=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=timeout) if not self.ser.isOpen(): self.ser.open() def read(self): # Keep reading from serial port until we get some data while True: line = self.ser.readline() if not self.running: raise Exception("Stop reading from serial port") if line != b'': break LOGGER.debug("Read from serial port: %s", line) small, large = [int(x.strip()) for x in line.split(b',')] LOGGER.debug("Small: %s, Large: %s", small, large) return {"small": small, "large": large} def stop(self): self.running = False GPIO.cleanup(DYLOS_POWER_PIN) self.ser.close()
<commit_before>import logging import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.UART as UART import serial DYLOS_POWER_PIN = "P8_10" LOGGER = logging.getLogger(__name__) class Dylos: def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5): self.running = True # Setup UART UART.setup("UART1") # Make sure Dylos sensor is turned on GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT) GPIO.output(DYLOS_POWER_PIN, GPIO.LOW) self.ser = serial.Serial(port=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=timeout) if not self.ser.isOpen(): self.ser.open() def read(self): # Keep reading from serial port until we get some data while True: line = self.ser.readline() if not self.running: raise Exception("Stop reading from serial port") if line != b'': break LOGGER.debug("Read from serial port: %s", line) small, large = [int(x.strip()) for x in line.split(b',')] LOGGER.debug("Small: %s, Large: %s", small, large) return {"small": small, "large": large} def stop(self): self.running = False self.ser.close() <commit_msg>Fix bug with fan turning itself off This would happen when the service was restarted. In the stopping code, I added a call to clean up.<commit_after>
import logging import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.UART as UART import serial DYLOS_POWER_PIN = "P8_10" LOGGER = logging.getLogger(__name__) class Dylos: def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5): self.running = True # Setup UART UART.setup("UART1") # Make sure Dylos sensor is turned on GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT) GPIO.output(DYLOS_POWER_PIN, GPIO.LOW) self.ser = serial.Serial(port=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=timeout) if not self.ser.isOpen(): self.ser.open() def read(self): # Keep reading from serial port until we get some data while True: line = self.ser.readline() if not self.running: raise Exception("Stop reading from serial port") if line != b'': break LOGGER.debug("Read from serial port: %s", line) small, large = [int(x.strip()) for x in line.split(b',')] LOGGER.debug("Small: %s, Large: %s", small, large) return {"small": small, "large": large} def stop(self): self.running = False GPIO.cleanup(DYLOS_POWER_PIN) self.ser.close()
import logging import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.UART as UART import serial DYLOS_POWER_PIN = "P8_10" LOGGER = logging.getLogger(__name__) class Dylos: def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5): self.running = True # Setup UART UART.setup("UART1") # Make sure Dylos sensor is turned on GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT) GPIO.output(DYLOS_POWER_PIN, GPIO.LOW) self.ser = serial.Serial(port=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=timeout) if not self.ser.isOpen(): self.ser.open() def read(self): # Keep reading from serial port until we get some data while True: line = self.ser.readline() if not self.running: raise Exception("Stop reading from serial port") if line != b'': break LOGGER.debug("Read from serial port: %s", line) small, large = [int(x.strip()) for x in line.split(b',')] LOGGER.debug("Small: %s, Large: %s", small, large) return {"small": small, "large": large} def stop(self): self.running = False self.ser.close() Fix bug with fan turning itself off This would happen when the service was restarted. In the stopping code, I added a call to clean up.import logging import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.UART as UART import serial DYLOS_POWER_PIN = "P8_10" LOGGER = logging.getLogger(__name__) class Dylos: def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5): self.running = True # Setup UART UART.setup("UART1") # Make sure Dylos sensor is turned on GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT) GPIO.output(DYLOS_POWER_PIN, GPIO.LOW) self.ser = serial.Serial(port=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=timeout) if not self.ser.isOpen(): self.ser.open() def read(self): # Keep reading from serial port until we get some data while True: line = self.ser.readline() if not self.running: raise Exception("Stop reading from serial port") if line != b'': break LOGGER.debug("Read from serial port: %s", line) small, large = [int(x.strip()) for x in line.split(b',')] LOGGER.debug("Small: %s, Large: %s", small, large) return {"small": small, "large": large} def stop(self): self.running = False GPIO.cleanup(DYLOS_POWER_PIN) self.ser.close()
<commit_before>import logging import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.UART as UART import serial DYLOS_POWER_PIN = "P8_10" LOGGER = logging.getLogger(__name__) class Dylos: def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5): self.running = True # Setup UART UART.setup("UART1") # Make sure Dylos sensor is turned on GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT) GPIO.output(DYLOS_POWER_PIN, GPIO.LOW) self.ser = serial.Serial(port=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=timeout) if not self.ser.isOpen(): self.ser.open() def read(self): # Keep reading from serial port until we get some data while True: line = self.ser.readline() if not self.running: raise Exception("Stop reading from serial port") if line != b'': break LOGGER.debug("Read from serial port: %s", line) small, large = [int(x.strip()) for x in line.split(b',')] LOGGER.debug("Small: %s, Large: %s", small, large) return {"small": small, "large": large} def stop(self): self.running = False self.ser.close() <commit_msg>Fix bug with fan turning itself off This would happen when the service was restarted. In the stopping code, I added a call to clean up.<commit_after>import logging import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.UART as UART import serial DYLOS_POWER_PIN = "P8_10" LOGGER = logging.getLogger(__name__) class Dylos: def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5): self.running = True # Setup UART UART.setup("UART1") # Make sure Dylos sensor is turned on GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT) GPIO.output(DYLOS_POWER_PIN, GPIO.LOW) self.ser = serial.Serial(port=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=timeout) if not self.ser.isOpen(): self.ser.open() def read(self): # Keep reading from serial port until we get some data while True: line = self.ser.readline() if not self.running: raise Exception("Stop reading from serial port") if line != b'': break LOGGER.debug("Read from serial port: %s", line) small, large = [int(x.strip()) for x in line.split(b',')] LOGGER.debug("Small: %s, Large: %s", small, large) return {"small": small, "large": large} def stop(self): self.running = False GPIO.cleanup(DYLOS_POWER_PIN) self.ser.close()
2d94532e316e9ad563b3b7506d47cfd78ca7f689
tests/test_cattery.py
tests/test_cattery.py
import pytest from catinabox import cattery ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(): c = cattery.Cattery() with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(): c = cattery.Cattery() c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums")
import pytest from catinabox import cattery ########################################################################### # fixtures ########################################################################### @pytest.fixture def c(): return cattery.Cattery() ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(c): c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(c): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(c): with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(c): c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums")
Add fixtures to cattery tests
Step_5: Add fixtures to cattery tests Add a fixture to remove initialisation of the cattery in every test. Signed-off-by: Meghan Halton <3ef2199560b9c9d063f7146fc0f2e3c408894741@gmail.com>
Python
mit
indexOutOfBound5/catinabox
import pytest from catinabox import cattery ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(): c = cattery.Cattery() with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(): c = cattery.Cattery() c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums") Step_5: Add fixtures to cattery tests Add a fixture to remove initialisation of the cattery in every test. Signed-off-by: Meghan Halton <3ef2199560b9c9d063f7146fc0f2e3c408894741@gmail.com>
import pytest from catinabox import cattery ########################################################################### # fixtures ########################################################################### @pytest.fixture def c(): return cattery.Cattery() ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(c): c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(c): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(c): with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(c): c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums")
<commit_before>import pytest from catinabox import cattery ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(): c = cattery.Cattery() with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(): c = cattery.Cattery() c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums") <commit_msg>Step_5: Add fixtures to cattery tests Add a fixture to remove initialisation of the cattery in every test. Signed-off-by: Meghan Halton <3ef2199560b9c9d063f7146fc0f2e3c408894741@gmail.com><commit_after>
import pytest from catinabox import cattery ########################################################################### # fixtures ########################################################################### @pytest.fixture def c(): return cattery.Cattery() ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(c): c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(c): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(c): with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(c): c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums")
import pytest from catinabox import cattery ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(): c = cattery.Cattery() with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(): c = cattery.Cattery() c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums") Step_5: Add fixtures to cattery tests Add a fixture to remove initialisation of the cattery in every test. Signed-off-by: Meghan Halton <3ef2199560b9c9d063f7146fc0f2e3c408894741@gmail.com>import pytest from catinabox import cattery ########################################################################### # fixtures ########################################################################### @pytest.fixture def c(): return cattery.Cattery() ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(c): c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(c): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(c): with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(c): c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums")
<commit_before>import pytest from catinabox import cattery ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(): c = cattery.Cattery() with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(): c = cattery.Cattery() c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums") <commit_msg>Step_5: Add fixtures to cattery tests Add a fixture to remove initialisation of the cattery in every test. Signed-off-by: Meghan Halton <3ef2199560b9c9d063f7146fc0f2e3c408894741@gmail.com><commit_after>import pytest from catinabox import cattery ########################################################################### # fixtures ########################################################################### @pytest.fixture def c(): return cattery.Cattery() ########################################################################### # add_cats ########################################################################### def test__add_cats__succeeds(c): c.add_cats(["Fluffy", "Snookums"]) assert c.cats == ["Fluffy", "Snookums"] assert c.num_cats == 2 ########################################################################### # remove_cat ########################################################################### def test__remove_cat__succeeds(c): c = cattery.Cattery() c.add_cats(["Fluffy", "Junior"]) c.remove_cat("Fluffy") assert c.cats == ["Junior"] assert c.num_cats == 1 def test__remove_cat__no_cats__fails(c): with pytest.raises(cattery.CatNotFound): c.remove_cat("Fluffles") def test__remove_cat__cat_not_in_cattery__fails(c): c.add_cats(["Fluffy"]) with pytest.raises(cattery.CatNotFound): c.remove_cat("Snookums")
6d859d72ac2091b1f5bc50c5a5c8d13cd13ff697
photobox/photobox.py
photobox/photobox.py
from os.path import expanduser from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from switch import KeyboardSwitch # from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' windowwidth = 1024 windowheight = 768 camera = Gphoto() # switch = RCSwitch("TRIGGER", "SHUTDOWN", "EXIT") switch = KeyboardSwitch() ########## filesystemFolder = RealFolder(photodirectory) photofolder = Photofolder(filesystemFolder) photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch) photobox.start()
from os.path import expanduser from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from switch import KeyboardSwitch # from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' windowwidth = 1024 windowheight = 768 camera = Gphoto() # switch = RCSwitch(iTRIGGER", iSHUTDOWN, iEXIT) switch = KeyboardSwitch() ########## filesystemFolder = RealFolder(photodirectory) photofolder = Photofolder(filesystemFolder) photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch) photobox.start()
Change comments to represents correct type
Change comments to represents correct type
Python
mit
MarkusAmshove/Photobox
from os.path import expanduser from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from switch import KeyboardSwitch # from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' windowwidth = 1024 windowheight = 768 camera = Gphoto() # switch = RCSwitch("TRIGGER", "SHUTDOWN", "EXIT") switch = KeyboardSwitch() ########## filesystemFolder = RealFolder(photodirectory) photofolder = Photofolder(filesystemFolder) photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch) photobox.start() Change comments to represents correct type
from os.path import expanduser from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from switch import KeyboardSwitch # from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' windowwidth = 1024 windowheight = 768 camera = Gphoto() # switch = RCSwitch(iTRIGGER", iSHUTDOWN, iEXIT) switch = KeyboardSwitch() ########## filesystemFolder = RealFolder(photodirectory) photofolder = Photofolder(filesystemFolder) photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch) photobox.start()
<commit_before>from os.path import expanduser from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from switch import KeyboardSwitch # from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' windowwidth = 1024 windowheight = 768 camera = Gphoto() # switch = RCSwitch("TRIGGER", "SHUTDOWN", "EXIT") switch = KeyboardSwitch() ########## filesystemFolder = RealFolder(photodirectory) photofolder = Photofolder(filesystemFolder) photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch) photobox.start() <commit_msg>Change comments to represents correct type<commit_after>
from os.path import expanduser from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from switch import KeyboardSwitch # from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' windowwidth = 1024 windowheight = 768 camera = Gphoto() # switch = RCSwitch(iTRIGGER", iSHUTDOWN, iEXIT) switch = KeyboardSwitch() ########## filesystemFolder = RealFolder(photodirectory) photofolder = Photofolder(filesystemFolder) photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch) photobox.start()
from os.path import expanduser from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from switch import KeyboardSwitch # from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' windowwidth = 1024 windowheight = 768 camera = Gphoto() # switch = RCSwitch("TRIGGER", "SHUTDOWN", "EXIT") switch = KeyboardSwitch() ########## filesystemFolder = RealFolder(photodirectory) photofolder = Photofolder(filesystemFolder) photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch) photobox.start() Change comments to represents correct typefrom os.path import expanduser from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from switch import KeyboardSwitch # from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' windowwidth = 1024 windowheight = 768 camera = Gphoto() # switch = RCSwitch(iTRIGGER", iSHUTDOWN, iEXIT) switch = KeyboardSwitch() ########## filesystemFolder = RealFolder(photodirectory) photofolder = Photofolder(filesystemFolder) photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch) photobox.start()
<commit_before>from os.path import expanduser from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from switch import KeyboardSwitch # from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' windowwidth = 1024 windowheight = 768 camera = Gphoto() # switch = RCSwitch("TRIGGER", "SHUTDOWN", "EXIT") switch = KeyboardSwitch() ########## filesystemFolder = RealFolder(photodirectory) photofolder = Photofolder(filesystemFolder) photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch) photobox.start() <commit_msg>Change comments to represents correct type<commit_after>from os.path import expanduser from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from switch import KeyboardSwitch # from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' windowwidth = 1024 windowheight = 768 camera = Gphoto() # switch = RCSwitch(iTRIGGER", iSHUTDOWN, iEXIT) switch = KeyboardSwitch() ########## filesystemFolder = RealFolder(photodirectory) photofolder = Photofolder(filesystemFolder) photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch) photobox.start()
2ecdd2feb18ef23610e55242b70b64ce0d6f6fe9
src/sentry/app.py
src/sentry/app.py
""" sentry.app ~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
""" sentry.app ~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) if cls is None: raise ImportError('Unable to find module %s' % path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
Raise an import error when import_string fails on get_buffer
Raise an import error when import_string fails on get_buffer
Python
bsd-3-clause
mvaled/sentry,llonchj/sentry,argonemyth/sentry,songyi199111/sentry,1tush/sentry,fotinakis/sentry,BayanGroup/sentry,alexm92/sentry,NickPresta/sentry,fotinakis/sentry,jokey2k/sentry,looker/sentry,fuziontech/sentry,imankulov/sentry,felixbuenemann/sentry,boneyao/sentry,Kryz/sentry,drcapulet/sentry,rdio/sentry,SilentCircle/sentry,Natim/sentry,jean/sentry,kevinastone/sentry,gencer/sentry,gg7/sentry,zenefits/sentry,gencer/sentry,jokey2k/sentry,ifduyue/sentry,ngonzalvez/sentry,kevinastone/sentry,nicholasserra/sentry,wujuguang/sentry,alexm92/sentry,rdio/sentry,felixbuenemann/sentry,pauloschilling/sentry,JTCunning/sentry,hongliang5623/sentry,JamesMura/sentry,mvaled/sentry,ngonzalvez/sentry,JamesMura/sentry,daevaorn/sentry,mvaled/sentry,imankulov/sentry,wujuguang/sentry,korealerts1/sentry,argonemyth/sentry,JTCunning/sentry,drcapulet/sentry,BuildingLink/sentry,zenefits/sentry,kevinlondon/sentry,NickPresta/sentry,jokey2k/sentry,beeftornado/sentry,1tush/sentry,songyi199111/sentry,mvaled/sentry,Kryz/sentry,ewdurbin/sentry,llonchj/sentry,rdio/sentry,boneyao/sentry,Natim/sentry,BuildingLink/sentry,JackDanger/sentry,ewdurbin/sentry,mitsuhiko/sentry,Natim/sentry,korealerts1/sentry,camilonova/sentry,SilentCircle/sentry,beni55/sentry,jean/sentry,TedaLIEz/sentry,SilentCircle/sentry,daevaorn/sentry,nicholasserra/sentry,looker/sentry,mvaled/sentry,1tush/sentry,ewdurbin/sentry,wujuguang/sentry,SilentCircle/sentry,alexm92/sentry,felixbuenemann/sentry,hongliang5623/sentry,Kryz/sentry,JTCunning/sentry,NickPresta/sentry,fotinakis/sentry,TedaLIEz/sentry,mitsuhiko/sentry,vperron/sentry,beni55/sentry,vperron/sentry,zenefits/sentry,JamesMura/sentry,kevinlondon/sentry,TedaLIEz/sentry,camilonova/sentry,fotinakis/sentry,wong2/sentry,BayanGroup/sentry,nicholasserra/sentry,BuildingLink/sentry,wong2/sentry,beeftornado/sentry,zenefits/sentry,boneyao/sentry,songyi199111/sentry,drcapulet/sentry,ifduyue/sentry,gencer/sentry,llonchj/sentry,JackDanger/sentry,BuildingLink/sentry,pauloschilling/sentry,daevaorn/sentry,beeftornado/sentry,ifduyue/sentry,gg7/sentry,ifduyue/sentry,beni55/sentry,argonemyth/sentry,kevinlondon/sentry,JamesMura/sentry,BuildingLink/sentry,kevinastone/sentry,ifduyue/sentry,jean/sentry,NickPresta/sentry,ngonzalvez/sentry,jean/sentry,pauloschilling/sentry,fuziontech/sentry,korealerts1/sentry,imankulov/sentry,looker/sentry,hongliang5623/sentry,mvaled/sentry,vperron/sentry,daevaorn/sentry,fuziontech/sentry,JamesMura/sentry,JackDanger/sentry,gencer/sentry,looker/sentry,jean/sentry,wong2/sentry,BayanGroup/sentry,rdio/sentry,zenefits/sentry,looker/sentry,camilonova/sentry,gg7/sentry,gencer/sentry
""" sentry.app ~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State() Raise an import error when import_string fails on get_buffer
""" sentry.app ~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) if cls is None: raise ImportError('Unable to find module %s' % path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
<commit_before>""" sentry.app ~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State() <commit_msg>Raise an import error when import_string fails on get_buffer<commit_after>
""" sentry.app ~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) if cls is None: raise ImportError('Unable to find module %s' % path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
""" sentry.app ~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State() Raise an import error when import_string fails on get_buffer""" sentry.app ~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) if cls is None: raise ImportError('Unable to find module %s' % path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
<commit_before>""" sentry.app ~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State() <commit_msg>Raise an import error when import_string fails on get_buffer<commit_after>""" sentry.app ~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) if cls is None: raise ImportError('Unable to find module %s' % path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
80de36ddbe4e2eb2e0d00d5910ab8c199d1a6edb
gom_server/char_attr/router.py
gom_server/char_attr/router.py
from rest_framework import routers, serializers, viewsets import models # Serializers define the API representation. class AttributeSerializer(serializers.ModelSerializer): class Meta: model = models.Attribute class AttributeTypeSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) class Meta: model = models.AttributeType fields = ('id', 'game', 'title', 'short_desc', 'attributes') # ViewSets define the view behavior. class AttributesViewSet(viewsets.ModelViewSet): serializer_class = AttributeTypeSerializer def get_queryset(self): gameid = self.kwargs['gameid'] return models.AttributeType.objects.filter(game=gameid) # Register actual routes when called by master urls.py def addRoutes(router): router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes')
from rest_framework import routers, serializers, viewsets import models # Serializers define the API representation. class AttributeSerializer(serializers.ModelSerializer): class Meta: model = models.Attribute class AttributeTypeSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) class Meta: model = models.AttributeType fields = ('id', 'game', 'title', 'short_desc', 'attributes') # ViewSets define the view behavior. class AttributesViewSet(viewsets.ModelViewSet): serializer_class = AttributeTypeSerializer def get_queryset(self): gameid = self.kwargs['gameid'] return models.AttributeType.objects.filter(game=gameid) class AttributeDetailViewSet(viewsets.ModelViewSet): serializer_class = AttributeSerializer queryset = models.Attribute.objects.all() # Register actual routes when called by master urls.py def addRoutes(router): router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes') router.register(r'attrib-detail', AttributeDetailViewSet)
Add api end point /api-detail/
Add api end point /api-detail/
Python
bsd-2-clause
jhogg41/gm-o-matic,jhogg41/gm-o-matic,jhogg41/gm-o-matic
from rest_framework import routers, serializers, viewsets import models # Serializers define the API representation. class AttributeSerializer(serializers.ModelSerializer): class Meta: model = models.Attribute class AttributeTypeSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) class Meta: model = models.AttributeType fields = ('id', 'game', 'title', 'short_desc', 'attributes') # ViewSets define the view behavior. class AttributesViewSet(viewsets.ModelViewSet): serializer_class = AttributeTypeSerializer def get_queryset(self): gameid = self.kwargs['gameid'] return models.AttributeType.objects.filter(game=gameid) # Register actual routes when called by master urls.py def addRoutes(router): router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes') Add api end point /api-detail/
from rest_framework import routers, serializers, viewsets import models # Serializers define the API representation. class AttributeSerializer(serializers.ModelSerializer): class Meta: model = models.Attribute class AttributeTypeSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) class Meta: model = models.AttributeType fields = ('id', 'game', 'title', 'short_desc', 'attributes') # ViewSets define the view behavior. class AttributesViewSet(viewsets.ModelViewSet): serializer_class = AttributeTypeSerializer def get_queryset(self): gameid = self.kwargs['gameid'] return models.AttributeType.objects.filter(game=gameid) class AttributeDetailViewSet(viewsets.ModelViewSet): serializer_class = AttributeSerializer queryset = models.Attribute.objects.all() # Register actual routes when called by master urls.py def addRoutes(router): router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes') router.register(r'attrib-detail', AttributeDetailViewSet)
<commit_before>from rest_framework import routers, serializers, viewsets import models # Serializers define the API representation. class AttributeSerializer(serializers.ModelSerializer): class Meta: model = models.Attribute class AttributeTypeSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) class Meta: model = models.AttributeType fields = ('id', 'game', 'title', 'short_desc', 'attributes') # ViewSets define the view behavior. class AttributesViewSet(viewsets.ModelViewSet): serializer_class = AttributeTypeSerializer def get_queryset(self): gameid = self.kwargs['gameid'] return models.AttributeType.objects.filter(game=gameid) # Register actual routes when called by master urls.py def addRoutes(router): router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes') <commit_msg>Add api end point /api-detail/<commit_after>
from rest_framework import routers, serializers, viewsets import models # Serializers define the API representation. class AttributeSerializer(serializers.ModelSerializer): class Meta: model = models.Attribute class AttributeTypeSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) class Meta: model = models.AttributeType fields = ('id', 'game', 'title', 'short_desc', 'attributes') # ViewSets define the view behavior. class AttributesViewSet(viewsets.ModelViewSet): serializer_class = AttributeTypeSerializer def get_queryset(self): gameid = self.kwargs['gameid'] return models.AttributeType.objects.filter(game=gameid) class AttributeDetailViewSet(viewsets.ModelViewSet): serializer_class = AttributeSerializer queryset = models.Attribute.objects.all() # Register actual routes when called by master urls.py def addRoutes(router): router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes') router.register(r'attrib-detail', AttributeDetailViewSet)
from rest_framework import routers, serializers, viewsets import models # Serializers define the API representation. class AttributeSerializer(serializers.ModelSerializer): class Meta: model = models.Attribute class AttributeTypeSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) class Meta: model = models.AttributeType fields = ('id', 'game', 'title', 'short_desc', 'attributes') # ViewSets define the view behavior. class AttributesViewSet(viewsets.ModelViewSet): serializer_class = AttributeTypeSerializer def get_queryset(self): gameid = self.kwargs['gameid'] return models.AttributeType.objects.filter(game=gameid) # Register actual routes when called by master urls.py def addRoutes(router): router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes') Add api end point /api-detail/from rest_framework import routers, serializers, viewsets import models # Serializers define the API representation. class AttributeSerializer(serializers.ModelSerializer): class Meta: model = models.Attribute class AttributeTypeSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) class Meta: model = models.AttributeType fields = ('id', 'game', 'title', 'short_desc', 'attributes') # ViewSets define the view behavior. class AttributesViewSet(viewsets.ModelViewSet): serializer_class = AttributeTypeSerializer def get_queryset(self): gameid = self.kwargs['gameid'] return models.AttributeType.objects.filter(game=gameid) class AttributeDetailViewSet(viewsets.ModelViewSet): serializer_class = AttributeSerializer queryset = models.Attribute.objects.all() # Register actual routes when called by master urls.py def addRoutes(router): router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes') router.register(r'attrib-detail', AttributeDetailViewSet)
<commit_before>from rest_framework import routers, serializers, viewsets import models # Serializers define the API representation. class AttributeSerializer(serializers.ModelSerializer): class Meta: model = models.Attribute class AttributeTypeSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) class Meta: model = models.AttributeType fields = ('id', 'game', 'title', 'short_desc', 'attributes') # ViewSets define the view behavior. class AttributesViewSet(viewsets.ModelViewSet): serializer_class = AttributeTypeSerializer def get_queryset(self): gameid = self.kwargs['gameid'] return models.AttributeType.objects.filter(game=gameid) # Register actual routes when called by master urls.py def addRoutes(router): router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes') <commit_msg>Add api end point /api-detail/<commit_after>from rest_framework import routers, serializers, viewsets import models # Serializers define the API representation. class AttributeSerializer(serializers.ModelSerializer): class Meta: model = models.Attribute class AttributeTypeSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) class Meta: model = models.AttributeType fields = ('id', 'game', 'title', 'short_desc', 'attributes') # ViewSets define the view behavior. class AttributesViewSet(viewsets.ModelViewSet): serializer_class = AttributeTypeSerializer def get_queryset(self): gameid = self.kwargs['gameid'] return models.AttributeType.objects.filter(game=gameid) class AttributeDetailViewSet(viewsets.ModelViewSet): serializer_class = AttributeSerializer queryset = models.Attribute.objects.all() # Register actual routes when called by master urls.py def addRoutes(router): router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes') router.register(r'attrib-detail', AttributeDetailViewSet)
6611641fec2342fa8dcfdbf12d74558df65ed2eb
isserviceup/services/heroku.py
isserviceup/services/heroku.py
import requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical
import requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical else: raise Exception('unexpected status')
Raise exception for unexpected status
Raise exception for unexpected status
Python
apache-2.0
marcopaz/is-service-up,marcopaz/is-service-up,marcopaz/is-service-up
import requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical Raise exception for unexpected status
import requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical else: raise Exception('unexpected status')
<commit_before>import requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical <commit_msg>Raise exception for unexpected status<commit_after>
import requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical else: raise Exception('unexpected status')
import requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical Raise exception for unexpected statusimport requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical else: raise Exception('unexpected status')
<commit_before>import requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical <commit_msg>Raise exception for unexpected status<commit_after>import requests from isserviceup.services.models.service import Service, Status class Heroku(Service): name = 'Heroku' status_url = 'https://status.heroku.com/' icon_url = '/images/icons/heroku.png' def get_status(self): r = requests.get('https://status.heroku.com/api/v3/current-status') res = r.json() status = res['status']['Production'] if status == 'green': return Status.ok elif status == 'yellow': return Status.minor elif status == 'orange': return Status.major elif status == 'red': return Status.critical else: raise Exception('unexpected status')
fcddaececf4d30fa8588f72812338e551efea056
oscar/apps/wishlists/forms.py
oscar/apps/wishlists/forms.py
# -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory, fields_for_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(WishListLineForm, self).__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['size'] = 2 LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory, fields_for_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(WishListLineForm, self).__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'input-mini' LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
Use bootstrap input styles to shrink quantity field width
Use bootstrap input styles to shrink quantity field width
Python
bsd-3-clause
faratro/django-oscar,vovanbo/django-oscar,ademuk/django-oscar,jinnykoo/wuyisj.com,kapt/django-oscar,eddiep1101/django-oscar,itbabu/django-oscar,nfletton/django-oscar,jlmadurga/django-oscar,solarissmoke/django-oscar,jinnykoo/wuyisj.com,MatthewWilkes/django-oscar,mexeniz/django-oscar,jinnykoo/wuyisj,michaelkuty/django-oscar,rocopartners/django-oscar,sonofatailor/django-oscar,eddiep1101/django-oscar,lijoantony/django-oscar,nickpack/django-oscar,makielab/django-oscar,Jannes123/django-oscar,WillisXChen/django-oscar,mexeniz/django-oscar,machtfit/django-oscar,manevant/django-oscar,spartonia/django-oscar,monikasulik/django-oscar,Bogh/django-oscar,QLGu/django-oscar,michaelkuty/django-oscar,binarydud/django-oscar,sonofatailor/django-oscar,elliotthill/django-oscar,adamend/django-oscar,michaelkuty/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,Bogh/django-oscar,machtfit/django-oscar,amirrpp/django-oscar,jinnykoo/christmas,mexeniz/django-oscar,bschuon/django-oscar,monikasulik/django-oscar,Jannes123/django-oscar,lijoantony/django-oscar,bnprk/django-oscar,rocopartners/django-oscar,makielab/django-oscar,Idematica/django-oscar,django-oscar/django-oscar,jmt4/django-oscar,thechampanurag/django-oscar,WadeYuChen/django-oscar,bnprk/django-oscar,ahmetdaglarbas/e-commerce,django-oscar/django-oscar,thechampanurag/django-oscar,rocopartners/django-oscar,django-oscar/django-oscar,dongguangming/django-oscar,okfish/django-oscar,jinnykoo/wuyisj.com,anentropic/django-oscar,MatthewWilkes/django-oscar,pdonadeo/django-oscar,pdonadeo/django-oscar,pdonadeo/django-oscar,QLGu/django-oscar,bschuon/django-oscar,WadeYuChen/django-oscar,itbabu/django-oscar,sonofatailor/django-oscar,marcoantoniooliveira/labweb,sasha0/django-oscar,jmt4/django-oscar,saadatqadri/django-oscar,ka7eh/django-oscar,vovanbo/django-oscar,jmt4/django-oscar,Bogh/django-oscar,john-parton/django-oscar,DrOctogon/unwash_ecom,jinnykoo/christmas,machtfit/django-oscar,MatthewWilkes/django-oscar,elliotthill/django-oscar,bnprk/django-oscar,lijoantony/django-oscar,ahmetdaglarbas/e-commerce,dongguangming/django-oscar,sasha0/django-oscar,pasqualguerrero/django-oscar,john-parton/django-oscar,ka7eh/django-oscar,vovanbo/django-oscar,adamend/django-oscar,spartonia/django-oscar,marcoantoniooliveira/labweb,monikasulik/django-oscar,amirrpp/django-oscar,DrOctogon/unwash_ecom,WadeYuChen/django-oscar,WadeYuChen/django-oscar,kapari/django-oscar,saadatqadri/django-oscar,DrOctogon/unwash_ecom,binarydud/django-oscar,spartonia/django-oscar,kapari/django-oscar,anentropic/django-oscar,marcoantoniooliveira/labweb,eddiep1101/django-oscar,binarydud/django-oscar,adamend/django-oscar,josesanch/django-oscar,kapari/django-oscar,ka7eh/django-oscar,makielab/django-oscar,taedori81/django-oscar,thechampanurag/django-oscar,josesanch/django-oscar,jinnykoo/wuyisj,dongguangming/django-oscar,jinnykoo/wuyisj,taedori81/django-oscar,jlmadurga/django-oscar,nfletton/django-oscar,pasqualguerrero/django-oscar,pasqualguerrero/django-oscar,itbabu/django-oscar,ahmetdaglarbas/e-commerce,QLGu/django-oscar,mexeniz/django-oscar,marcoantoniooliveira/labweb,QLGu/django-oscar,ademuk/django-oscar,kapt/django-oscar,manevant/django-oscar,Jannes123/django-oscar,anentropic/django-oscar,taedori81/django-oscar,elliotthill/django-oscar,Idematica/django-oscar,WillisXChen/django-oscar,amirrpp/django-oscar,eddiep1101/django-oscar,ademuk/django-oscar,binarydud/django-oscar,jinnykoo/christmas,pdonadeo/django-oscar,adamend/django-oscar,WillisXChen/django-oscar,manevant/django-oscar,bschuon/django-oscar,MatthewWilkes/django-oscar,pasqualguerrero/django-oscar,django-oscar/django-oscar,Idematica/django-oscar,amirrpp/django-oscar,sonofatailor/django-oscar,WillisXChen/django-oscar,anentropic/django-oscar,michaelkuty/django-oscar,nickpack/django-oscar,solarissmoke/django-oscar,kapt/django-oscar,monikasulik/django-oscar,spartonia/django-oscar,saadatqadri/django-oscar,ka7eh/django-oscar,nickpack/django-oscar,okfish/django-oscar,WillisXChen/django-oscar,solarissmoke/django-oscar,faratro/django-oscar,john-parton/django-oscar,sasha0/django-oscar,kapari/django-oscar,okfish/django-oscar,nickpack/django-oscar,okfish/django-oscar,itbabu/django-oscar,nfletton/django-oscar,makielab/django-oscar,ahmetdaglarbas/e-commerce,manevant/django-oscar,lijoantony/django-oscar,Bogh/django-oscar,jinnykoo/wuyisj.com,jinnykoo/wuyisj,josesanch/django-oscar,thechampanurag/django-oscar,jlmadurga/django-oscar,ademuk/django-oscar,bschuon/django-oscar,faratro/django-oscar,taedori81/django-oscar,nfletton/django-oscar,faratro/django-oscar,john-parton/django-oscar,jlmadurga/django-oscar,jmt4/django-oscar,WillisXChen/django-oscar,dongguangming/django-oscar,rocopartners/django-oscar,saadatqadri/django-oscar,vovanbo/django-oscar,bnprk/django-oscar,Jannes123/django-oscar
# -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory, fields_for_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(WishListLineForm, self).__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['size'] = 2 LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False) Use bootstrap input styles to shrink quantity field width
# -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory, fields_for_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(WishListLineForm, self).__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'input-mini' LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
<commit_before># -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory, fields_for_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(WishListLineForm, self).__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['size'] = 2 LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False) <commit_msg>Use bootstrap input styles to shrink quantity field width<commit_after>
# -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory, fields_for_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(WishListLineForm, self).__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'input-mini' LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory, fields_for_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(WishListLineForm, self).__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['size'] = 2 LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False) Use bootstrap input styles to shrink quantity field width# -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory, fields_for_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(WishListLineForm, self).__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'input-mini' LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
<commit_before># -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory, fields_for_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(WishListLineForm, self).__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['size'] = 2 LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False) <commit_msg>Use bootstrap input styles to shrink quantity field width<commit_after># -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory, fields_for_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(WishListLineForm, self).__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'input-mini' LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
903030fc0a0d545e652337d543c6167e2bb192b1
pyaggr3g470r/duplicate.py
pyaggr3g470r/duplicate.py
#! /usr/bin/env python #-*- coding: utf-8 -*- import itertools import utils def compare_documents(feed): """ Compare a list of documents by pair. """ duplicates = [] for pair in itertools.combinations(feed.articles, 2): if pair[0].content != "" and pair[0].content == pair[1].content: duplicates.append(pair) return duplicates
#! /usr/bin/env python #-*- coding: utf-8 -*- import itertools import utils def compare_documents(feed): """ Compare a list of documents by pair. """ duplicates = [] for pair in itertools.combinations(feed.articles, 2): if pair[0].content != "" and \ (utils.clear_string(pair[0].title) == utils.clear_string(pair[1].title) or \ utils.clear_string(pair[0].content) == utils.clear_string(pair[1].content)): duplicates.append(pair) return duplicates
Test the equality of the contents and of the titles.
Test the equality of the contents and of the titles.
Python
agpl-3.0
JARR-aggregator/JARR,jaesivsm/JARR,JARR-aggregator/JARR,cedricbonhomme/pyAggr3g470r,JARR/JARR,jaesivsm/pyAggr3g470r,JARR/JARR,jaesivsm/pyAggr3g470r,JARR-aggregator/JARR,jaesivsm/pyAggr3g470r,cedricbonhomme/pyAggr3g470r,JARR/JARR,cedricbonhomme/pyAggr3g470r,cedricbonhomme/pyAggr3g470r,jaesivsm/pyAggr3g470r,jaesivsm/JARR,cedricbonhomme/pyAggr3g470r,jaesivsm/pyAggr3g470r,jaesivsm/JARR,JARR/JARR,JARR-aggregator/JARR
#! /usr/bin/env python #-*- coding: utf-8 -*- import itertools import utils def compare_documents(feed): """ Compare a list of documents by pair. """ duplicates = [] for pair in itertools.combinations(feed.articles, 2): if pair[0].content != "" and pair[0].content == pair[1].content: duplicates.append(pair) return duplicatesTest the equality of the contents and of the titles.
#! /usr/bin/env python #-*- coding: utf-8 -*- import itertools import utils def compare_documents(feed): """ Compare a list of documents by pair. """ duplicates = [] for pair in itertools.combinations(feed.articles, 2): if pair[0].content != "" and \ (utils.clear_string(pair[0].title) == utils.clear_string(pair[1].title) or \ utils.clear_string(pair[0].content) == utils.clear_string(pair[1].content)): duplicates.append(pair) return duplicates
<commit_before>#! /usr/bin/env python #-*- coding: utf-8 -*- import itertools import utils def compare_documents(feed): """ Compare a list of documents by pair. """ duplicates = [] for pair in itertools.combinations(feed.articles, 2): if pair[0].content != "" and pair[0].content == pair[1].content: duplicates.append(pair) return duplicates<commit_msg>Test the equality of the contents and of the titles.<commit_after>
#! /usr/bin/env python #-*- coding: utf-8 -*- import itertools import utils def compare_documents(feed): """ Compare a list of documents by pair. """ duplicates = [] for pair in itertools.combinations(feed.articles, 2): if pair[0].content != "" and \ (utils.clear_string(pair[0].title) == utils.clear_string(pair[1].title) or \ utils.clear_string(pair[0].content) == utils.clear_string(pair[1].content)): duplicates.append(pair) return duplicates
#! /usr/bin/env python #-*- coding: utf-8 -*- import itertools import utils def compare_documents(feed): """ Compare a list of documents by pair. """ duplicates = [] for pair in itertools.combinations(feed.articles, 2): if pair[0].content != "" and pair[0].content == pair[1].content: duplicates.append(pair) return duplicatesTest the equality of the contents and of the titles.#! /usr/bin/env python #-*- coding: utf-8 -*- import itertools import utils def compare_documents(feed): """ Compare a list of documents by pair. """ duplicates = [] for pair in itertools.combinations(feed.articles, 2): if pair[0].content != "" and \ (utils.clear_string(pair[0].title) == utils.clear_string(pair[1].title) or \ utils.clear_string(pair[0].content) == utils.clear_string(pair[1].content)): duplicates.append(pair) return duplicates
<commit_before>#! /usr/bin/env python #-*- coding: utf-8 -*- import itertools import utils def compare_documents(feed): """ Compare a list of documents by pair. """ duplicates = [] for pair in itertools.combinations(feed.articles, 2): if pair[0].content != "" and pair[0].content == pair[1].content: duplicates.append(pair) return duplicates<commit_msg>Test the equality of the contents and of the titles.<commit_after>#! /usr/bin/env python #-*- coding: utf-8 -*- import itertools import utils def compare_documents(feed): """ Compare a list of documents by pair. """ duplicates = [] for pair in itertools.combinations(feed.articles, 2): if pair[0].content != "" and \ (utils.clear_string(pair[0].title) == utils.clear_string(pair[1].title) or \ utils.clear_string(pair[0].content) == utils.clear_string(pair[1].content)): duplicates.append(pair) return duplicates
177418e6331f8fb02f8176ea37dc7aef2f586586
settings/__init__.py
settings/__init__.py
# this is a hack to work around https://code.djangoproject.com/ticket/15064 # normally we'd just set DJANGO_SETTINGS_MODULE to opencomparison.settings.development and call it a day # this way if you run ./manage.py without specifying a --settings you'll get the dev settings from .development import *
Work around Django bug in manage.py
Work around Django bug in manage.py manage.py is ignoring DJANGO_SETTINGS_MODULE, so this way we can run it without specifying the settings during development
Python
mit
QLGu/djangopackages,nanuxbe/djangopackages,miketheman/opencomparison,miketheman/opencomparison,benracine/opencomparison,pydanny/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages,benracine/opencomparison,QLGu/djangopackages,audreyr/opencomparison,pydanny/djangopackages,nanuxbe/djangopackages,audreyr/opencomparison,pydanny/djangopackages
Work around Django bug in manage.py manage.py is ignoring DJANGO_SETTINGS_MODULE, so this way we can run it without specifying the settings during development
# this is a hack to work around https://code.djangoproject.com/ticket/15064 # normally we'd just set DJANGO_SETTINGS_MODULE to opencomparison.settings.development and call it a day # this way if you run ./manage.py without specifying a --settings you'll get the dev settings from .development import *
<commit_before><commit_msg>Work around Django bug in manage.py manage.py is ignoring DJANGO_SETTINGS_MODULE, so this way we can run it without specifying the settings during development<commit_after>
# this is a hack to work around https://code.djangoproject.com/ticket/15064 # normally we'd just set DJANGO_SETTINGS_MODULE to opencomparison.settings.development and call it a day # this way if you run ./manage.py without specifying a --settings you'll get the dev settings from .development import *
Work around Django bug in manage.py manage.py is ignoring DJANGO_SETTINGS_MODULE, so this way we can run it without specifying the settings during development# this is a hack to work around https://code.djangoproject.com/ticket/15064 # normally we'd just set DJANGO_SETTINGS_MODULE to opencomparison.settings.development and call it a day # this way if you run ./manage.py without specifying a --settings you'll get the dev settings from .development import *
<commit_before><commit_msg>Work around Django bug in manage.py manage.py is ignoring DJANGO_SETTINGS_MODULE, so this way we can run it without specifying the settings during development<commit_after># this is a hack to work around https://code.djangoproject.com/ticket/15064 # normally we'd just set DJANGO_SETTINGS_MODULE to opencomparison.settings.development and call it a day # this way if you run ./manage.py without specifying a --settings you'll get the dev settings from .development import *
a5dd30e38e58c08d67a2f831e2ae3cbc4a288337
diary/admin.py
diary/admin.py
from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem)
from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') exclude = ('author',) def save_model(self, request, obj, form, change): if obj.pk is None: obj.author = request.user obj.save() # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem)
Set author automatically for diary items
Set author automatically for diary items
Python
mit
DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at,DevLoL/devlol.at
from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem) Set author automatically for diary items
from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') exclude = ('author',) def save_model(self, request, obj, form, change): if obj.pk is None: obj.author = request.user obj.save() # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem)
<commit_before>from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem) <commit_msg>Set author automatically for diary items<commit_after>
from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') exclude = ('author',) def save_model(self, request, obj, form, change): if obj.pk is None: obj.author = request.user obj.save() # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem)
from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem) Set author automatically for diary itemsfrom django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') exclude = ('author',) def save_model(self, request, obj, form, change): if obj.pk is None: obj.author = request.user obj.save() # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem)
<commit_before>from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem) <commit_msg>Set author automatically for diary items<commit_after>from django.contrib import admin from diary.models import DiaryItem, EventLocation, ImageItem class DiaryAdmin(admin.ModelAdmin): list_display = ('title', 'start_date', 'start_time', 'author', 'location') exclude = ('author',) def save_model(self, request, obj, form, change): if obj.pk is None: obj.author = request.user obj.save() # Register your models here. admin.site.register(DiaryItem, DiaryAdmin) admin.site.register(EventLocation) admin.site.register(ImageItem)
27a7e589ec3f5b29d99cede4af66780509ab6973
foursquare/tests/test_photos.py
foursquare/tests/test_photos.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2013 Mike Lewis import logging; log = logging.getLogger(__name__) from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase import os TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') class PhotosEndpointTestCase(BaseAuthenticatedEndpointTestCase): """ General """ def test_photo(self): response = self.api.photos(self.default_photoid) assert 'photo' in response def test_attach_photo(self): """Creates a checkin and attaches a photo to it.""" response = self.api.checkins.add(params={'venueId': self.default_venueid}) checkin = response.get('checkin') self.assertIsNotNone(checkin) photo_data = open(os.path.join(TEST_DATA_DIR, 'test-photo.jpg'), 'rb') try: response = self.api.photos.add(params={'checkinId': checkin['id']}, photo_data=photo_data) photo = response.get('photo') self.assertIsNotNone(photo) self.assertEquals(300, photo['width']) self.assertEquals(300, photo['height']) finally: photo_data.close()
#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2013 Mike Lewis import logging; log = logging.getLogger(__name__) from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase import os TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') class PhotosEndpointTestCase(BaseAuthenticatedEndpointTestCase): """ General """ def test_photo(self): response = self.api.photos(self.default_photoid) assert 'photo' in response def test_attach_photo(self): """Creates a checkin and attaches a photo to it.""" response = self.api.checkins.add(params={'venueId': self.default_venueid}) checkin = response.get('checkin') self.assertNotEqual(checkin, None) photo_data = open(os.path.join(TEST_DATA_DIR, 'test-photo.jpg'), 'rb') try: response = self.api.photos.add(params={'checkinId': checkin['id']}, photo_data=photo_data) photo = response.get('photo') self.assertNotEqual(photo, None) self.assertEquals(300, photo['width']) self.assertEquals(300, photo['height']) finally: photo_data.close()
Make test compatible with Python 2.6.
Make test compatible with Python 2.6.
Python
mit
mLewisLogic/foursquare,mLewisLogic/foursquare
#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2013 Mike Lewis import logging; log = logging.getLogger(__name__) from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase import os TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') class PhotosEndpointTestCase(BaseAuthenticatedEndpointTestCase): """ General """ def test_photo(self): response = self.api.photos(self.default_photoid) assert 'photo' in response def test_attach_photo(self): """Creates a checkin and attaches a photo to it.""" response = self.api.checkins.add(params={'venueId': self.default_venueid}) checkin = response.get('checkin') self.assertIsNotNone(checkin) photo_data = open(os.path.join(TEST_DATA_DIR, 'test-photo.jpg'), 'rb') try: response = self.api.photos.add(params={'checkinId': checkin['id']}, photo_data=photo_data) photo = response.get('photo') self.assertIsNotNone(photo) self.assertEquals(300, photo['width']) self.assertEquals(300, photo['height']) finally: photo_data.close() Make test compatible with Python 2.6.
#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2013 Mike Lewis import logging; log = logging.getLogger(__name__) from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase import os TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') class PhotosEndpointTestCase(BaseAuthenticatedEndpointTestCase): """ General """ def test_photo(self): response = self.api.photos(self.default_photoid) assert 'photo' in response def test_attach_photo(self): """Creates a checkin and attaches a photo to it.""" response = self.api.checkins.add(params={'venueId': self.default_venueid}) checkin = response.get('checkin') self.assertNotEqual(checkin, None) photo_data = open(os.path.join(TEST_DATA_DIR, 'test-photo.jpg'), 'rb') try: response = self.api.photos.add(params={'checkinId': checkin['id']}, photo_data=photo_data) photo = response.get('photo') self.assertNotEqual(photo, None) self.assertEquals(300, photo['width']) self.assertEquals(300, photo['height']) finally: photo_data.close()
<commit_before>#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2013 Mike Lewis import logging; log = logging.getLogger(__name__) from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase import os TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') class PhotosEndpointTestCase(BaseAuthenticatedEndpointTestCase): """ General """ def test_photo(self): response = self.api.photos(self.default_photoid) assert 'photo' in response def test_attach_photo(self): """Creates a checkin and attaches a photo to it.""" response = self.api.checkins.add(params={'venueId': self.default_venueid}) checkin = response.get('checkin') self.assertIsNotNone(checkin) photo_data = open(os.path.join(TEST_DATA_DIR, 'test-photo.jpg'), 'rb') try: response = self.api.photos.add(params={'checkinId': checkin['id']}, photo_data=photo_data) photo = response.get('photo') self.assertIsNotNone(photo) self.assertEquals(300, photo['width']) self.assertEquals(300, photo['height']) finally: photo_data.close() <commit_msg>Make test compatible with Python 2.6.<commit_after>
#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2013 Mike Lewis import logging; log = logging.getLogger(__name__) from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase import os TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') class PhotosEndpointTestCase(BaseAuthenticatedEndpointTestCase): """ General """ def test_photo(self): response = self.api.photos(self.default_photoid) assert 'photo' in response def test_attach_photo(self): """Creates a checkin and attaches a photo to it.""" response = self.api.checkins.add(params={'venueId': self.default_venueid}) checkin = response.get('checkin') self.assertNotEqual(checkin, None) photo_data = open(os.path.join(TEST_DATA_DIR, 'test-photo.jpg'), 'rb') try: response = self.api.photos.add(params={'checkinId': checkin['id']}, photo_data=photo_data) photo = response.get('photo') self.assertNotEqual(photo, None) self.assertEquals(300, photo['width']) self.assertEquals(300, photo['height']) finally: photo_data.close()
#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2013 Mike Lewis import logging; log = logging.getLogger(__name__) from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase import os TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') class PhotosEndpointTestCase(BaseAuthenticatedEndpointTestCase): """ General """ def test_photo(self): response = self.api.photos(self.default_photoid) assert 'photo' in response def test_attach_photo(self): """Creates a checkin and attaches a photo to it.""" response = self.api.checkins.add(params={'venueId': self.default_venueid}) checkin = response.get('checkin') self.assertIsNotNone(checkin) photo_data = open(os.path.join(TEST_DATA_DIR, 'test-photo.jpg'), 'rb') try: response = self.api.photos.add(params={'checkinId': checkin['id']}, photo_data=photo_data) photo = response.get('photo') self.assertIsNotNone(photo) self.assertEquals(300, photo['width']) self.assertEquals(300, photo['height']) finally: photo_data.close() Make test compatible with Python 2.6.#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2013 Mike Lewis import logging; log = logging.getLogger(__name__) from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase import os TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') class PhotosEndpointTestCase(BaseAuthenticatedEndpointTestCase): """ General """ def test_photo(self): response = self.api.photos(self.default_photoid) assert 'photo' in response def test_attach_photo(self): """Creates a checkin and attaches a photo to it.""" response = self.api.checkins.add(params={'venueId': self.default_venueid}) checkin = response.get('checkin') self.assertNotEqual(checkin, None) photo_data = open(os.path.join(TEST_DATA_DIR, 'test-photo.jpg'), 'rb') try: response = self.api.photos.add(params={'checkinId': checkin['id']}, photo_data=photo_data) photo = response.get('photo') self.assertNotEqual(photo, None) self.assertEquals(300, photo['width']) self.assertEquals(300, photo['height']) finally: photo_data.close()
<commit_before>#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2013 Mike Lewis import logging; log = logging.getLogger(__name__) from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase import os TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') class PhotosEndpointTestCase(BaseAuthenticatedEndpointTestCase): """ General """ def test_photo(self): response = self.api.photos(self.default_photoid) assert 'photo' in response def test_attach_photo(self): """Creates a checkin and attaches a photo to it.""" response = self.api.checkins.add(params={'venueId': self.default_venueid}) checkin = response.get('checkin') self.assertIsNotNone(checkin) photo_data = open(os.path.join(TEST_DATA_DIR, 'test-photo.jpg'), 'rb') try: response = self.api.photos.add(params={'checkinId': checkin['id']}, photo_data=photo_data) photo = response.get('photo') self.assertIsNotNone(photo) self.assertEquals(300, photo['width']) self.assertEquals(300, photo['height']) finally: photo_data.close() <commit_msg>Make test compatible with Python 2.6.<commit_after>#!/usr/bin/env python # -*- coding: UTF-8 -*- # (c) 2013 Mike Lewis import logging; log = logging.getLogger(__name__) from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase import os TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') class PhotosEndpointTestCase(BaseAuthenticatedEndpointTestCase): """ General """ def test_photo(self): response = self.api.photos(self.default_photoid) assert 'photo' in response def test_attach_photo(self): """Creates a checkin and attaches a photo to it.""" response = self.api.checkins.add(params={'venueId': self.default_venueid}) checkin = response.get('checkin') self.assertNotEqual(checkin, None) photo_data = open(os.path.join(TEST_DATA_DIR, 'test-photo.jpg'), 'rb') try: response = self.api.photos.add(params={'checkinId': checkin['id']}, photo_data=photo_data) photo = response.get('photo') self.assertNotEqual(photo, None) self.assertEquals(300, photo['width']) self.assertEquals(300, photo['height']) finally: photo_data.close()