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
da42140e1620021fda305bbc37f43d1e49ec65da
src/poliastro/examples.py
src/poliastro/examples.py
# coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5.29556871e3] * u.km, [7.37289205, 2.08223573, 4.39999794e-1] * u.km / u.s, time.Time("2013-03-18 12:00", scale='utc')) molniya = State.from_classical(Earth, 26600 * u.km, 0.75 * u.one, 63.4 * u.deg, 0 * u.deg, 270 * u.deg, 80 * u.deg)
# coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Sun, Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5.29556871e3] * u.km, [7.37289205, 2.08223573, 4.39999794e-1] * u.km / u.s, time.Time("2013-03-18 12:00", scale='utc')) molniya = State.from_classical(Earth, 26600 * u.km, 0.75 * u.one, 63.4 * u.deg, 0 * u.deg, 270 * u.deg, 80 * u.deg) churi = State.from_classical(Sun, 3.46250 * u.AU, 0.64 * u.one, 7.04 * u.deg, 50.1350 * u.deg, 12.8007 * u.deg, 63.89 * u.deg, time.Time("2015-11-05 12:00", scale='utc'))
Add 67P/Churyumov–Gerasimenko to example data
Add 67P/Churyumov–Gerasimenko to example data
Python
mit
Juanlu001/poliastro,poliastro/poliastro,Juanlu001/poliastro,newlawrence/poliastro,newlawrence/poliastro,Juanlu001/poliastro,anhiga/poliastro,anhiga/poliastro,anhiga/poliastro,newlawrence/poliastro
# coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5.29556871e3] * u.km, [7.37289205, 2.08223573, 4.39999794e-1] * u.km / u.s, time.Time("2013-03-18 12:00", scale='utc')) molniya = State.from_classical(Earth, 26600 * u.km, 0.75 * u.one, 63.4 * u.deg, 0 * u.deg, 270 * u.deg, 80 * u.deg) Add 67P/Churyumov–Gerasimenko to example data
# coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Sun, Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5.29556871e3] * u.km, [7.37289205, 2.08223573, 4.39999794e-1] * u.km / u.s, time.Time("2013-03-18 12:00", scale='utc')) molniya = State.from_classical(Earth, 26600 * u.km, 0.75 * u.one, 63.4 * u.deg, 0 * u.deg, 270 * u.deg, 80 * u.deg) churi = State.from_classical(Sun, 3.46250 * u.AU, 0.64 * u.one, 7.04 * u.deg, 50.1350 * u.deg, 12.8007 * u.deg, 63.89 * u.deg, time.Time("2015-11-05 12:00", scale='utc'))
<commit_before># coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5.29556871e3] * u.km, [7.37289205, 2.08223573, 4.39999794e-1] * u.km / u.s, time.Time("2013-03-18 12:00", scale='utc')) molniya = State.from_classical(Earth, 26600 * u.km, 0.75 * u.one, 63.4 * u.deg, 0 * u.deg, 270 * u.deg, 80 * u.deg) <commit_msg>Add 67P/Churyumov–Gerasimenko to example data<commit_after>
# coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Sun, Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5.29556871e3] * u.km, [7.37289205, 2.08223573, 4.39999794e-1] * u.km / u.s, time.Time("2013-03-18 12:00", scale='utc')) molniya = State.from_classical(Earth, 26600 * u.km, 0.75 * u.one, 63.4 * u.deg, 0 * u.deg, 270 * u.deg, 80 * u.deg) churi = State.from_classical(Sun, 3.46250 * u.AU, 0.64 * u.one, 7.04 * u.deg, 50.1350 * u.deg, 12.8007 * u.deg, 63.89 * u.deg, time.Time("2015-11-05 12:00", scale='utc'))
# coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5.29556871e3] * u.km, [7.37289205, 2.08223573, 4.39999794e-1] * u.km / u.s, time.Time("2013-03-18 12:00", scale='utc')) molniya = State.from_classical(Earth, 26600 * u.km, 0.75 * u.one, 63.4 * u.deg, 0 * u.deg, 270 * u.deg, 80 * u.deg) Add 67P/Churyumov–Gerasimenko to example data# coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Sun, Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5.29556871e3] * u.km, [7.37289205, 2.08223573, 4.39999794e-1] * u.km / u.s, time.Time("2013-03-18 12:00", scale='utc')) molniya = State.from_classical(Earth, 26600 * u.km, 0.75 * u.one, 63.4 * u.deg, 0 * u.deg, 270 * u.deg, 80 * u.deg) churi = State.from_classical(Sun, 3.46250 * u.AU, 0.64 * u.one, 7.04 * u.deg, 50.1350 * u.deg, 12.8007 * u.deg, 63.89 * u.deg, time.Time("2015-11-05 12:00", scale='utc'))
<commit_before># coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5.29556871e3] * u.km, [7.37289205, 2.08223573, 4.39999794e-1] * u.km / u.s, time.Time("2013-03-18 12:00", scale='utc')) molniya = State.from_classical(Earth, 26600 * u.km, 0.75 * u.one, 63.4 * u.deg, 0 * u.deg, 270 * u.deg, 80 * u.deg) <commit_msg>Add 67P/Churyumov–Gerasimenko to example data<commit_after># coding: utf-8 """Example data. """ from astropy import time from astropy import units as u from poliastro.bodies import Sun, Earth from poliastro.twobody import State # Taken from Plyades (c) 2012 Helge Eichhorn (MIT License) iss = State.from_vectors(Earth, [8.59072560e2, -4.13720368e3, 5.29556871e3] * u.km, [7.37289205, 2.08223573, 4.39999794e-1] * u.km / u.s, time.Time("2013-03-18 12:00", scale='utc')) molniya = State.from_classical(Earth, 26600 * u.km, 0.75 * u.one, 63.4 * u.deg, 0 * u.deg, 270 * u.deg, 80 * u.deg) churi = State.from_classical(Sun, 3.46250 * u.AU, 0.64 * u.one, 7.04 * u.deg, 50.1350 * u.deg, 12.8007 * u.deg, 63.89 * u.deg, time.Time("2015-11-05 12:00", scale='utc'))
59eaf266921d76cf5ef472fa59dbb9e136c800f3
views/main.py
views/main.py
from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) def alias_route(alias): # Attempt to fetch the link mapping from the database link = database.link.get_link_by_alias(alias) if not link: if request.method == 'GET': # For GET requests (likely from a browser), direct to the frontend interface return render_template('index.html') elif request.method == 'POST': # For POST requests (likely programmatic), send a plain-text response with an # appropriate status code return 'Link alias not found', 404 # Redirect to the frontend interface to handle authentication for password-protected links if link.password_hash: return render_template('index.html') database.link.add_link_hit( link_id=link.link_id, remote_ip=request.remote_addr, referer=request.referrer, user_agent=request.user_agent, ) return redirect(link.outgoing_url) @app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods) @app.route(DefaultURI.path, methods=DefaultURI.methods) def frontend(path): return render_template('index.html')
from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * from util.decorators import require_form_args @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) @require_form_args([]) def alias_route(data, alias): # Attempt to fetch the link mapping from the database link = database.link.get_link_by_alias(alias) if not link: if request.method == 'GET': # For GET requests (likely from a browser), direct to the frontend interface return render_template('index.html') elif request.method == 'POST': # For POST requests (likely programmatic), send a plain-text response with an # appropriate status code return 'Link alias not found', 404 # Redirect to the frontend interface to handle authentication for password-protected links if link.password_hash and not link.validate_password(data.get('password', '')): return render_template('index.html') database.link.add_link_hit( link_id=link.link_id, remote_ip=request.remote_addr, referer=request.referrer, user_agent=request.user_agent, ) return redirect(link.outgoing_url) @app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods) @app.route(DefaultURI.path, methods=DefaultURI.methods) def frontend(path): return render_template('index.html')
Support programmatically passing password in alias route
Support programmatically passing password in alias route
Python
mit
LINKIWI/linkr,LINKIWI/linkr,LINKIWI/linkr
from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) def alias_route(alias): # Attempt to fetch the link mapping from the database link = database.link.get_link_by_alias(alias) if not link: if request.method == 'GET': # For GET requests (likely from a browser), direct to the frontend interface return render_template('index.html') elif request.method == 'POST': # For POST requests (likely programmatic), send a plain-text response with an # appropriate status code return 'Link alias not found', 404 # Redirect to the frontend interface to handle authentication for password-protected links if link.password_hash: return render_template('index.html') database.link.add_link_hit( link_id=link.link_id, remote_ip=request.remote_addr, referer=request.referrer, user_agent=request.user_agent, ) return redirect(link.outgoing_url) @app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods) @app.route(DefaultURI.path, methods=DefaultURI.methods) def frontend(path): return render_template('index.html') Support programmatically passing password in alias route
from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * from util.decorators import require_form_args @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) @require_form_args([]) def alias_route(data, alias): # Attempt to fetch the link mapping from the database link = database.link.get_link_by_alias(alias) if not link: if request.method == 'GET': # For GET requests (likely from a browser), direct to the frontend interface return render_template('index.html') elif request.method == 'POST': # For POST requests (likely programmatic), send a plain-text response with an # appropriate status code return 'Link alias not found', 404 # Redirect to the frontend interface to handle authentication for password-protected links if link.password_hash and not link.validate_password(data.get('password', '')): return render_template('index.html') database.link.add_link_hit( link_id=link.link_id, remote_ip=request.remote_addr, referer=request.referrer, user_agent=request.user_agent, ) return redirect(link.outgoing_url) @app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods) @app.route(DefaultURI.path, methods=DefaultURI.methods) def frontend(path): return render_template('index.html')
<commit_before>from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) def alias_route(alias): # Attempt to fetch the link mapping from the database link = database.link.get_link_by_alias(alias) if not link: if request.method == 'GET': # For GET requests (likely from a browser), direct to the frontend interface return render_template('index.html') elif request.method == 'POST': # For POST requests (likely programmatic), send a plain-text response with an # appropriate status code return 'Link alias not found', 404 # Redirect to the frontend interface to handle authentication for password-protected links if link.password_hash: return render_template('index.html') database.link.add_link_hit( link_id=link.link_id, remote_ip=request.remote_addr, referer=request.referrer, user_agent=request.user_agent, ) return redirect(link.outgoing_url) @app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods) @app.route(DefaultURI.path, methods=DefaultURI.methods) def frontend(path): return render_template('index.html') <commit_msg>Support programmatically passing password in alias route<commit_after>
from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * from util.decorators import require_form_args @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) @require_form_args([]) def alias_route(data, alias): # Attempt to fetch the link mapping from the database link = database.link.get_link_by_alias(alias) if not link: if request.method == 'GET': # For GET requests (likely from a browser), direct to the frontend interface return render_template('index.html') elif request.method == 'POST': # For POST requests (likely programmatic), send a plain-text response with an # appropriate status code return 'Link alias not found', 404 # Redirect to the frontend interface to handle authentication for password-protected links if link.password_hash and not link.validate_password(data.get('password', '')): return render_template('index.html') database.link.add_link_hit( link_id=link.link_id, remote_ip=request.remote_addr, referer=request.referrer, user_agent=request.user_agent, ) return redirect(link.outgoing_url) @app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods) @app.route(DefaultURI.path, methods=DefaultURI.methods) def frontend(path): return render_template('index.html')
from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) def alias_route(alias): # Attempt to fetch the link mapping from the database link = database.link.get_link_by_alias(alias) if not link: if request.method == 'GET': # For GET requests (likely from a browser), direct to the frontend interface return render_template('index.html') elif request.method == 'POST': # For POST requests (likely programmatic), send a plain-text response with an # appropriate status code return 'Link alias not found', 404 # Redirect to the frontend interface to handle authentication for password-protected links if link.password_hash: return render_template('index.html') database.link.add_link_hit( link_id=link.link_id, remote_ip=request.remote_addr, referer=request.referrer, user_agent=request.user_agent, ) return redirect(link.outgoing_url) @app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods) @app.route(DefaultURI.path, methods=DefaultURI.methods) def frontend(path): return render_template('index.html') Support programmatically passing password in alias routefrom flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * from util.decorators import require_form_args @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) @require_form_args([]) def alias_route(data, alias): # Attempt to fetch the link mapping from the database link = database.link.get_link_by_alias(alias) if not link: if request.method == 'GET': # For GET requests (likely from a browser), direct to the frontend interface return render_template('index.html') elif request.method == 'POST': # For POST requests (likely programmatic), send a plain-text response with an # appropriate status code return 'Link alias not found', 404 # Redirect to the frontend interface to handle authentication for password-protected links if link.password_hash and not link.validate_password(data.get('password', '')): return render_template('index.html') database.link.add_link_hit( link_id=link.link_id, remote_ip=request.remote_addr, referer=request.referrer, user_agent=request.user_agent, ) return redirect(link.outgoing_url) @app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods) @app.route(DefaultURI.path, methods=DefaultURI.methods) def frontend(path): return render_template('index.html')
<commit_before>from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) def alias_route(alias): # Attempt to fetch the link mapping from the database link = database.link.get_link_by_alias(alias) if not link: if request.method == 'GET': # For GET requests (likely from a browser), direct to the frontend interface return render_template('index.html') elif request.method == 'POST': # For POST requests (likely programmatic), send a plain-text response with an # appropriate status code return 'Link alias not found', 404 # Redirect to the frontend interface to handle authentication for password-protected links if link.password_hash: return render_template('index.html') database.link.add_link_hit( link_id=link.link_id, remote_ip=request.remote_addr, referer=request.referrer, user_agent=request.user_agent, ) return redirect(link.outgoing_url) @app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods) @app.route(DefaultURI.path, methods=DefaultURI.methods) def frontend(path): return render_template('index.html') <commit_msg>Support programmatically passing password in alias route<commit_after>from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * from util.decorators import require_form_args @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) @require_form_args([]) def alias_route(data, alias): # Attempt to fetch the link mapping from the database link = database.link.get_link_by_alias(alias) if not link: if request.method == 'GET': # For GET requests (likely from a browser), direct to the frontend interface return render_template('index.html') elif request.method == 'POST': # For POST requests (likely programmatic), send a plain-text response with an # appropriate status code return 'Link alias not found', 404 # Redirect to the frontend interface to handle authentication for password-protected links if link.password_hash and not link.validate_password(data.get('password', '')): return render_template('index.html') database.link.add_link_hit( link_id=link.link_id, remote_ip=request.remote_addr, referer=request.referrer, user_agent=request.user_agent, ) return redirect(link.outgoing_url) @app.route(HomeURI.path, defaults={'path': ''}, methods=HomeURI.methods) @app.route(DefaultURI.path, methods=DefaultURI.methods) def frontend(path): return render_template('index.html')
aac0f52fa97f75ca6ec5a2744cd1c0942a57c283
src/pybel/struct/utils.py
src/pybel/struct/utils.py
# -*- coding: utf-8 -*- from collections import defaultdict def hash_dict(d): """Hashes a dictionary :param dict d: A dictionary to recursively hash :return: the hash value of the dictionary :rtype: int """ h = 0 for k, v in sorted(d.items()): h += hash(k) if isinstance(v, (set, list)): h += hash(tuple(sorted(v))) if isinstance(v, dict): h += hash_dict(v) if isinstance(v, (bool, int, tuple, str)): h += hash(v) return hash(h) def stratify_hash_edges(graph): """Splits all qualified and unqualified edges by different indexing strategies :param BELGraph graph: A BEL network :rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]] """ qualified_edges = defaultdict(dict) unqualified_edges = defaultdict(lambda: defaultdict(set)) for u, v, k, d in graph.edges_iter(keys=True, data=True): hashed_data = hash_dict(d) if k < 0: unqualified_edges[u, v][k].add(hashed_data) else: qualified_edges[u, v][hashed_data] = k return dict(qualified_edges), dict(unqualified_edges)
# -*- coding: utf-8 -*- from collections import defaultdict from ..utils import hash_edge def stratify_hash_edges(graph): """Splits all qualified and unqualified edges by different indexing strategies :param BELGraph graph: A BEL network :rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]] """ qualified_edges = defaultdict(dict) unqualified_edges = defaultdict(lambda: defaultdict(set)) for u, v, k, d in graph.edges_iter(keys=True, data=True): hashed_data = hash_edge(u, v, k, d) if k < 0: unqualified_edges[u, v][k].add(hashed_data) else: qualified_edges[u, v][hashed_data] = k return dict(qualified_edges), dict(unqualified_edges)
Cut out old hash function
Cut out old hash function
Python
mit
pybel/pybel,pybel/pybel,pybel/pybel
# -*- coding: utf-8 -*- from collections import defaultdict def hash_dict(d): """Hashes a dictionary :param dict d: A dictionary to recursively hash :return: the hash value of the dictionary :rtype: int """ h = 0 for k, v in sorted(d.items()): h += hash(k) if isinstance(v, (set, list)): h += hash(tuple(sorted(v))) if isinstance(v, dict): h += hash_dict(v) if isinstance(v, (bool, int, tuple, str)): h += hash(v) return hash(h) def stratify_hash_edges(graph): """Splits all qualified and unqualified edges by different indexing strategies :param BELGraph graph: A BEL network :rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]] """ qualified_edges = defaultdict(dict) unqualified_edges = defaultdict(lambda: defaultdict(set)) for u, v, k, d in graph.edges_iter(keys=True, data=True): hashed_data = hash_dict(d) if k < 0: unqualified_edges[u, v][k].add(hashed_data) else: qualified_edges[u, v][hashed_data] = k return dict(qualified_edges), dict(unqualified_edges) Cut out old hash function
# -*- coding: utf-8 -*- from collections import defaultdict from ..utils import hash_edge def stratify_hash_edges(graph): """Splits all qualified and unqualified edges by different indexing strategies :param BELGraph graph: A BEL network :rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]] """ qualified_edges = defaultdict(dict) unqualified_edges = defaultdict(lambda: defaultdict(set)) for u, v, k, d in graph.edges_iter(keys=True, data=True): hashed_data = hash_edge(u, v, k, d) if k < 0: unqualified_edges[u, v][k].add(hashed_data) else: qualified_edges[u, v][hashed_data] = k return dict(qualified_edges), dict(unqualified_edges)
<commit_before># -*- coding: utf-8 -*- from collections import defaultdict def hash_dict(d): """Hashes a dictionary :param dict d: A dictionary to recursively hash :return: the hash value of the dictionary :rtype: int """ h = 0 for k, v in sorted(d.items()): h += hash(k) if isinstance(v, (set, list)): h += hash(tuple(sorted(v))) if isinstance(v, dict): h += hash_dict(v) if isinstance(v, (bool, int, tuple, str)): h += hash(v) return hash(h) def stratify_hash_edges(graph): """Splits all qualified and unqualified edges by different indexing strategies :param BELGraph graph: A BEL network :rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]] """ qualified_edges = defaultdict(dict) unqualified_edges = defaultdict(lambda: defaultdict(set)) for u, v, k, d in graph.edges_iter(keys=True, data=True): hashed_data = hash_dict(d) if k < 0: unqualified_edges[u, v][k].add(hashed_data) else: qualified_edges[u, v][hashed_data] = k return dict(qualified_edges), dict(unqualified_edges) <commit_msg>Cut out old hash function<commit_after>
# -*- coding: utf-8 -*- from collections import defaultdict from ..utils import hash_edge def stratify_hash_edges(graph): """Splits all qualified and unqualified edges by different indexing strategies :param BELGraph graph: A BEL network :rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]] """ qualified_edges = defaultdict(dict) unqualified_edges = defaultdict(lambda: defaultdict(set)) for u, v, k, d in graph.edges_iter(keys=True, data=True): hashed_data = hash_edge(u, v, k, d) if k < 0: unqualified_edges[u, v][k].add(hashed_data) else: qualified_edges[u, v][hashed_data] = k return dict(qualified_edges), dict(unqualified_edges)
# -*- coding: utf-8 -*- from collections import defaultdict def hash_dict(d): """Hashes a dictionary :param dict d: A dictionary to recursively hash :return: the hash value of the dictionary :rtype: int """ h = 0 for k, v in sorted(d.items()): h += hash(k) if isinstance(v, (set, list)): h += hash(tuple(sorted(v))) if isinstance(v, dict): h += hash_dict(v) if isinstance(v, (bool, int, tuple, str)): h += hash(v) return hash(h) def stratify_hash_edges(graph): """Splits all qualified and unqualified edges by different indexing strategies :param BELGraph graph: A BEL network :rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]] """ qualified_edges = defaultdict(dict) unqualified_edges = defaultdict(lambda: defaultdict(set)) for u, v, k, d in graph.edges_iter(keys=True, data=True): hashed_data = hash_dict(d) if k < 0: unqualified_edges[u, v][k].add(hashed_data) else: qualified_edges[u, v][hashed_data] = k return dict(qualified_edges), dict(unqualified_edges) Cut out old hash function# -*- coding: utf-8 -*- from collections import defaultdict from ..utils import hash_edge def stratify_hash_edges(graph): """Splits all qualified and unqualified edges by different indexing strategies :param BELGraph graph: A BEL network :rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]] """ qualified_edges = defaultdict(dict) unqualified_edges = defaultdict(lambda: defaultdict(set)) for u, v, k, d in graph.edges_iter(keys=True, data=True): hashed_data = hash_edge(u, v, k, d) if k < 0: unqualified_edges[u, v][k].add(hashed_data) else: qualified_edges[u, v][hashed_data] = k return dict(qualified_edges), dict(unqualified_edges)
<commit_before># -*- coding: utf-8 -*- from collections import defaultdict def hash_dict(d): """Hashes a dictionary :param dict d: A dictionary to recursively hash :return: the hash value of the dictionary :rtype: int """ h = 0 for k, v in sorted(d.items()): h += hash(k) if isinstance(v, (set, list)): h += hash(tuple(sorted(v))) if isinstance(v, dict): h += hash_dict(v) if isinstance(v, (bool, int, tuple, str)): h += hash(v) return hash(h) def stratify_hash_edges(graph): """Splits all qualified and unqualified edges by different indexing strategies :param BELGraph graph: A BEL network :rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]] """ qualified_edges = defaultdict(dict) unqualified_edges = defaultdict(lambda: defaultdict(set)) for u, v, k, d in graph.edges_iter(keys=True, data=True): hashed_data = hash_dict(d) if k < 0: unqualified_edges[u, v][k].add(hashed_data) else: qualified_edges[u, v][hashed_data] = k return dict(qualified_edges), dict(unqualified_edges) <commit_msg>Cut out old hash function<commit_after># -*- coding: utf-8 -*- from collections import defaultdict from ..utils import hash_edge def stratify_hash_edges(graph): """Splits all qualified and unqualified edges by different indexing strategies :param BELGraph graph: A BEL network :rtype dict[tuple, dict[int, int]], dict[tuple, dict[int, set[int]]] """ qualified_edges = defaultdict(dict) unqualified_edges = defaultdict(lambda: defaultdict(set)) for u, v, k, d in graph.edges_iter(keys=True, data=True): hashed_data = hash_edge(u, v, k, d) if k < 0: unqualified_edges[u, v][k].add(hashed_data) else: qualified_edges[u, v][hashed_data] = k return dict(qualified_edges), dict(unqualified_edges)
9d1059bc4cf28b9650bb6386cb5665bfb9b2c138
canopus/views/__init__.py
canopus/views/__init__.py
import os from datetime import date from pyramid.response import FileResponse from pyramid.view import view_config @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.abspath(os.path.dirname(__file__)) response = FileResponse(here + '/../static/robots.txt', request=request) return response
import os from datetime import date from pyramid.httpexceptions import HTTPBadRequest from pyramid.response import FileResponse from pyramid.view import view_config from sqlalchemy.exc import IntegrityError @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.abspath(os.path.dirname(__file__)) response = FileResponse(here + '/../static/robots.txt', request=request) return response @view_config(context=IntegrityError) def bad_request(exc, request): raise HTTPBadRequest()
Throw 500 error on SQLAlchemy integrity error
Throw 500 error on SQLAlchemy integrity error
Python
mit
josuemontano/pyramid-angularjs-starter,josuemontano/API-platform,josuemontano/pyramid-angularjs-starter,josuemontano/api-starter,josuemontano/pyramid-angularjs-starter,josuemontano/api-starter,josuemontano/API-platform,josuemontano/API-platform,josuemontano/API-platform,josuemontano/api-starter
import os from datetime import date from pyramid.response import FileResponse from pyramid.view import view_config @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.abspath(os.path.dirname(__file__)) response = FileResponse(here + '/../static/robots.txt', request=request) return response Throw 500 error on SQLAlchemy integrity error
import os from datetime import date from pyramid.httpexceptions import HTTPBadRequest from pyramid.response import FileResponse from pyramid.view import view_config from sqlalchemy.exc import IntegrityError @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.abspath(os.path.dirname(__file__)) response = FileResponse(here + '/../static/robots.txt', request=request) return response @view_config(context=IntegrityError) def bad_request(exc, request): raise HTTPBadRequest()
<commit_before>import os from datetime import date from pyramid.response import FileResponse from pyramid.view import view_config @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.abspath(os.path.dirname(__file__)) response = FileResponse(here + '/../static/robots.txt', request=request) return response <commit_msg>Throw 500 error on SQLAlchemy integrity error<commit_after>
import os from datetime import date from pyramid.httpexceptions import HTTPBadRequest from pyramid.response import FileResponse from pyramid.view import view_config from sqlalchemy.exc import IntegrityError @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.abspath(os.path.dirname(__file__)) response = FileResponse(here + '/../static/robots.txt', request=request) return response @view_config(context=IntegrityError) def bad_request(exc, request): raise HTTPBadRequest()
import os from datetime import date from pyramid.response import FileResponse from pyramid.view import view_config @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.abspath(os.path.dirname(__file__)) response = FileResponse(here + '/../static/robots.txt', request=request) return response Throw 500 error on SQLAlchemy integrity errorimport os from datetime import date from pyramid.httpexceptions import HTTPBadRequest from pyramid.response import FileResponse from pyramid.view import view_config from sqlalchemy.exc import IntegrityError @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.abspath(os.path.dirname(__file__)) response = FileResponse(here + '/../static/robots.txt', request=request) return response @view_config(context=IntegrityError) def bad_request(exc, request): raise HTTPBadRequest()
<commit_before>import os from datetime import date from pyramid.response import FileResponse from pyramid.view import view_config @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.abspath(os.path.dirname(__file__)) response = FileResponse(here + '/../static/robots.txt', request=request) return response <commit_msg>Throw 500 error on SQLAlchemy integrity error<commit_after>import os from datetime import date from pyramid.httpexceptions import HTTPBadRequest from pyramid.response import FileResponse from pyramid.view import view_config from sqlalchemy.exc import IntegrityError @view_config(route_name='home', renderer='templates/index.html') def index(request): return {'year': date.today().year} @view_config(route_name='robots') def robots(request): here = os.path.abspath(os.path.dirname(__file__)) response = FileResponse(here + '/../static/robots.txt', request=request) return response @view_config(context=IntegrityError) def bad_request(exc, request): raise HTTPBadRequest()
1a0047cddcb2e7799511e57d3f5d13efc1c7e6f7
news/models.py
news/models.py
from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): return get_news_feeds() class Meta: verbose_name = _('News index') def get_context(self, request, *args, **kwargs): context = super(NewsIndexPage, self).get_context(request, *args, **kwargs) news_list = self.news_list # Pagination page = request.GET.get('page') page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10) if page_size is not None: paginator = Paginator(news_list, page_size) # Show 10 blogs per page try: news_list = paginator.page(page) except PageNotAnInteger: news_list = paginator.page(1) except EmptyPage: news_list = paginator.page(paginator.num_pages) context['news_list'] = news_list return context
from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.core.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): return get_news_feeds() class Meta: verbose_name = _('News index') def get_context(self, request, *args, **kwargs): context = super(NewsIndexPage, self).get_context(request, *args, **kwargs) news_list = self.news_list # Pagination page = request.GET.get('page') page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10) if page_size is not None: paginator = Paginator(news_list, page_size) # Show 10 blogs per page try: news_list = paginator.page(page) except PageNotAnInteger: news_list = paginator.page(1) except EmptyPage: news_list = paginator.page(paginator.num_pages) context['news_list'] = news_list return context
Fix wagtail module paths in news
Fix wagtail module paths in news
Python
mit
City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel
from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): return get_news_feeds() class Meta: verbose_name = _('News index') def get_context(self, request, *args, **kwargs): context = super(NewsIndexPage, self).get_context(request, *args, **kwargs) news_list = self.news_list # Pagination page = request.GET.get('page') page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10) if page_size is not None: paginator = Paginator(news_list, page_size) # Show 10 blogs per page try: news_list = paginator.page(page) except PageNotAnInteger: news_list = paginator.page(1) except EmptyPage: news_list = paginator.page(paginator.num_pages) context['news_list'] = news_list return context Fix wagtail module paths in news
from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.core.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): return get_news_feeds() class Meta: verbose_name = _('News index') def get_context(self, request, *args, **kwargs): context = super(NewsIndexPage, self).get_context(request, *args, **kwargs) news_list = self.news_list # Pagination page = request.GET.get('page') page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10) if page_size is not None: paginator = Paginator(news_list, page_size) # Show 10 blogs per page try: news_list = paginator.page(page) except PageNotAnInteger: news_list = paginator.page(1) except EmptyPage: news_list = paginator.page(paginator.num_pages) context['news_list'] = news_list return context
<commit_before>from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): return get_news_feeds() class Meta: verbose_name = _('News index') def get_context(self, request, *args, **kwargs): context = super(NewsIndexPage, self).get_context(request, *args, **kwargs) news_list = self.news_list # Pagination page = request.GET.get('page') page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10) if page_size is not None: paginator = Paginator(news_list, page_size) # Show 10 blogs per page try: news_list = paginator.page(page) except PageNotAnInteger: news_list = paginator.page(1) except EmptyPage: news_list = paginator.page(paginator.num_pages) context['news_list'] = news_list return context <commit_msg>Fix wagtail module paths in news<commit_after>
from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.core.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): return get_news_feeds() class Meta: verbose_name = _('News index') def get_context(self, request, *args, **kwargs): context = super(NewsIndexPage, self).get_context(request, *args, **kwargs) news_list = self.news_list # Pagination page = request.GET.get('page') page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10) if page_size is not None: paginator = Paginator(news_list, page_size) # Show 10 blogs per page try: news_list = paginator.page(page) except PageNotAnInteger: news_list = paginator.page(1) except EmptyPage: news_list = paginator.page(paginator.num_pages) context['news_list'] = news_list return context
from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): return get_news_feeds() class Meta: verbose_name = _('News index') def get_context(self, request, *args, **kwargs): context = super(NewsIndexPage, self).get_context(request, *args, **kwargs) news_list = self.news_list # Pagination page = request.GET.get('page') page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10) if page_size is not None: paginator = Paginator(news_list, page_size) # Show 10 blogs per page try: news_list = paginator.page(page) except PageNotAnInteger: news_list = paginator.page(1) except EmptyPage: news_list = paginator.page(paginator.num_pages) context['news_list'] = news_list return context Fix wagtail module paths in newsfrom django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.core.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): return get_news_feeds() class Meta: verbose_name = _('News index') def get_context(self, request, *args, **kwargs): context = super(NewsIndexPage, self).get_context(request, *args, **kwargs) news_list = self.news_list # Pagination page = request.GET.get('page') page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10) if page_size is not None: paginator = Paginator(news_list, page_size) # Show 10 blogs per page try: news_list = paginator.page(page) except PageNotAnInteger: news_list = paginator.page(1) except EmptyPage: news_list = paginator.page(paginator.num_pages) context['news_list'] = news_list return context
<commit_before>from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): return get_news_feeds() class Meta: verbose_name = _('News index') def get_context(self, request, *args, **kwargs): context = super(NewsIndexPage, self).get_context(request, *args, **kwargs) news_list = self.news_list # Pagination page = request.GET.get('page') page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10) if page_size is not None: paginator = Paginator(news_list, page_size) # Show 10 blogs per page try: news_list = paginator.page(page) except PageNotAnInteger: news_list = paginator.page(1) except EmptyPage: news_list = paginator.page(paginator.num_pages) context['news_list'] = news_list return context <commit_msg>Fix wagtail module paths in news<commit_after>from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.utils.translation import ugettext_lazy as _ from wagtail.core.models import Page from .news import get_news_feeds class NewsIndexPage(Page): @property def news_list(self): return get_news_feeds() class Meta: verbose_name = _('News index') def get_context(self, request, *args, **kwargs): context = super(NewsIndexPage, self).get_context(request, *args, **kwargs) news_list = self.news_list # Pagination page = request.GET.get('page') page_size = getattr(settings, 'NEWS_PAGINATION_PER_PAGE', 10) if page_size is not None: paginator = Paginator(news_list, page_size) # Show 10 blogs per page try: news_list = paginator.page(page) except PageNotAnInteger: news_list = paginator.page(1) except EmptyPage: news_list = paginator.page(paginator.num_pages) context['news_list'] = news_list return context
9195818ef2e7f75528a68a686889721e7f2ff213
idiokit/dns/_hostlookup.py
idiokit/dns/_hostlookup.py
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): _hosts = None def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup
Remove an unnecessary class attribute
Remove an unnecessary class attribute
Python
mit
abusesa/idiokit
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): _hosts = None def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup Remove an unnecessary class attribute
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup
<commit_before>from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): _hosts = None def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup <commit_msg>Remove an unnecessary class attribute<commit_after>
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): _hosts = None def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup Remove an unnecessary class attributefrom .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup
<commit_before>from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): _hosts = None def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup <commit_msg>Remove an unnecessary class attribute<commit_after>from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup
ab5996b9218ec51b2991bb1fd702885414fce8b0
lib/ansiblelint/rules/CommandsInsteadOfModulesRule.py
lib/ansiblelint/rules/CommandsInsteadOfModulesRule.py
import ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad idea' tags = ['resources'] _commands = [ 'command', 'shell', 'raw' ] _modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url', 'svn': 'subversion', 'cp': 'copy', 'service': 'service', 'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get' } def matchtask(self, file, task): if task["action"]["module"] in self._commands: executable = os.path.basename(task["action"]["args"][0]) if self._modules.has_key(executable): message = "{} used in place of {} module" return message.format(executable, self._modules[executable])
import ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad idea' tags = ['resources'] _commands = [ 'command', 'shell', 'raw' ] _modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url', 'svn': 'subversion', 'cp': 'copy', 'service': 'service', 'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get', 'unzip': 'unarchive', 'tar': 'unarchive' } def matchtask(self, file, task): if task["action"]["module"] in self._commands: executable = os.path.basename(task["action"]["args"][0]) if self._modules.has_key(executable): message = "{} used in place of {} module" return message.format(executable, self._modules[executable])
Check whether unzip or tar are used instead of unarchive
Check whether unzip or tar are used instead of unarchive
Python
mit
MatrixCrawler/ansible-lint,dataxu/ansible-lint,charleswhchan/ansible-lint,MiLk/ansible-lint,willthames/ansible-lint,schlueter/ansible-lint
import ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad idea' tags = ['resources'] _commands = [ 'command', 'shell', 'raw' ] _modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url', 'svn': 'subversion', 'cp': 'copy', 'service': 'service', 'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get' } def matchtask(self, file, task): if task["action"]["module"] in self._commands: executable = os.path.basename(task["action"]["args"][0]) if self._modules.has_key(executable): message = "{} used in place of {} module" return message.format(executable, self._modules[executable]) Check whether unzip or tar are used instead of unarchive
import ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad idea' tags = ['resources'] _commands = [ 'command', 'shell', 'raw' ] _modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url', 'svn': 'subversion', 'cp': 'copy', 'service': 'service', 'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get', 'unzip': 'unarchive', 'tar': 'unarchive' } def matchtask(self, file, task): if task["action"]["module"] in self._commands: executable = os.path.basename(task["action"]["args"][0]) if self._modules.has_key(executable): message = "{} used in place of {} module" return message.format(executable, self._modules[executable])
<commit_before>import ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad idea' tags = ['resources'] _commands = [ 'command', 'shell', 'raw' ] _modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url', 'svn': 'subversion', 'cp': 'copy', 'service': 'service', 'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get' } def matchtask(self, file, task): if task["action"]["module"] in self._commands: executable = os.path.basename(task["action"]["args"][0]) if self._modules.has_key(executable): message = "{} used in place of {} module" return message.format(executable, self._modules[executable]) <commit_msg>Check whether unzip or tar are used instead of unarchive<commit_after>
import ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad idea' tags = ['resources'] _commands = [ 'command', 'shell', 'raw' ] _modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url', 'svn': 'subversion', 'cp': 'copy', 'service': 'service', 'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get', 'unzip': 'unarchive', 'tar': 'unarchive' } def matchtask(self, file, task): if task["action"]["module"] in self._commands: executable = os.path.basename(task["action"]["args"][0]) if self._modules.has_key(executable): message = "{} used in place of {} module" return message.format(executable, self._modules[executable])
import ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad idea' tags = ['resources'] _commands = [ 'command', 'shell', 'raw' ] _modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url', 'svn': 'subversion', 'cp': 'copy', 'service': 'service', 'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get' } def matchtask(self, file, task): if task["action"]["module"] in self._commands: executable = os.path.basename(task["action"]["args"][0]) if self._modules.has_key(executable): message = "{} used in place of {} module" return message.format(executable, self._modules[executable]) Check whether unzip or tar are used instead of unarchiveimport ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad idea' tags = ['resources'] _commands = [ 'command', 'shell', 'raw' ] _modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url', 'svn': 'subversion', 'cp': 'copy', 'service': 'service', 'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get', 'unzip': 'unarchive', 'tar': 'unarchive' } def matchtask(self, file, task): if task["action"]["module"] in self._commands: executable = os.path.basename(task["action"]["args"][0]) if self._modules.has_key(executable): message = "{} used in place of {} module" return message.format(executable, self._modules[executable])
<commit_before>import ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad idea' tags = ['resources'] _commands = [ 'command', 'shell', 'raw' ] _modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url', 'svn': 'subversion', 'cp': 'copy', 'service': 'service', 'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get' } def matchtask(self, file, task): if task["action"]["module"] in self._commands: executable = os.path.basename(task["action"]["args"][0]) if self._modules.has_key(executable): message = "{} used in place of {} module" return message.format(executable, self._modules[executable]) <commit_msg>Check whether unzip or tar are used instead of unarchive<commit_after>import ansiblelint.utils import os from ansiblelint import AnsibleLintRule class CommandsInsteadOfModulesRule(AnsibleLintRule): id = 'ANSIBLE0006' shortdesc = 'Using command rather than module' description = 'Executing a command when there is an Ansible module ' + \ 'is generally a bad idea' tags = ['resources'] _commands = [ 'command', 'shell', 'raw' ] _modules = { 'git': 'git', 'hg': 'hg', 'curl': 'get_url', 'wget': 'get_url', 'svn': 'subversion', 'cp': 'copy', 'service': 'service', 'mount': 'mount', 'rpm': 'yum', 'yum': 'yum', 'apt-get': 'apt-get', 'unzip': 'unarchive', 'tar': 'unarchive' } def matchtask(self, file, task): if task["action"]["module"] in self._commands: executable = os.path.basename(task["action"]["args"][0]) if self._modules.has_key(executable): message = "{} used in place of {} module" return message.format(executable, self._modules[executable])
ecac9283bc831a6879f21e80e1b98818683ff6a4
atlas/prodtask/management/commands/pthealthcheck.py
atlas/prodtask/management/commands/pthealthcheck.py
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e)
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: self.stdout.write(f'Start celery beat health check {timezone.now()}') try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e)
Add logging for health check
Add logging for health check
Python
apache-2.0
PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e) Add logging for health check
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: self.stdout.write(f'Start celery beat health check {timezone.now()}') try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e)
<commit_before>from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e) <commit_msg>Add logging for health check<commit_after>
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: self.stdout.write(f'Start celery beat health check {timezone.now()}') try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e)
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e) Add logging for health checkfrom django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: self.stdout.write(f'Start celery beat health check {timezone.now()}') try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e)
<commit_before>from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e) <commit_msg>Add logging for health check<commit_after>from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: self.stdout.write(f'Start celery beat health check {timezone.now()}') try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e)
64c02a8bb7863ee9606b7927540fbf71d806a6e1
sitecustomize.py
sitecustomize.py
import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # detect if coverage was running in forked process if sys.version_info >= (3, 4): klass = multiprocessing.process.BaseProcess else: klass = multiprocessing.Process if Collector._collectors: original = multiprocessing.Process._bootstrap class ProcessWithCoverage(multiprocessing.Process): def _bootstrap(self): cov = coverage( data_suffix=True, config_file=os.getenv('COVERAGE_PROCESS_START', True) ) cov.start() try: return original(self) finally: cov.stop() cov.save() if sys.version_info >= (3, 4): klass._bootstrap = ProcessWithCoverage._bootstrap else: multiprocessing.Process = ProcessWithCoverage if os.getenv('FULL_COVERAGE', 'false') == 'true': try: import coverage coverage.process_startup() patch_process_for_coverage() except ImportError: pass
import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # detect if coverage was running in forked process if sys.version_info >= (3, 4): klass = multiprocessing.process.BaseProcess else: klass = multiprocessing.Process if Collector._collectors: original = multiprocessing.Process._bootstrap class ProcessWithCoverage(multiprocessing.Process): def _bootstrap(self): cov = coverage( data_suffix=True, config_file=os.getenv('COVERAGE_PROCESS_START', True) ) cov.start() try: return original(self) finally: cov.stop() cov.save() if sys.version_info >= (3, 4): klass._bootstrap = ProcessWithCoverage._bootstrap else: multiprocessing.Process = ProcessWithCoverage if os.getenv('FULL_COVERAGE', 'false') == 'true': try: import coverage coverage.process_startup() patch_process_for_coverage() except ImportError: pass
Fix scope when setting up multiprocessing with coverage
Fix scope when setting up multiprocessing with coverage
Python
apache-2.0
Wattpad/luigi,jamesmcm/luigi,wakamori/luigi,casey-green/luigi,mbruggmann/luigi,adaitche/luigi,rayrrr/luigi,stroykova/luigi,riga/luigi,fabriziodemaria/luigi,mfcabrera/luigi,mfcabrera/luigi,Houzz/luigi,h3biomed/luigi,linsomniac/luigi,soxofaan/luigi,oldpa/luigi,edx/luigi,jw0201/luigi,foursquare/luigi,humanlongevity/luigi,Tarrasch/luigi,edx/luigi,samepage-labs/luigi,dstandish/luigi,Tarrasch/luigi,rayrrr/luigi,jw0201/luigi,bmaggard/luigi,spotify/luigi,mbruggmann/luigi,stroykova/luigi,fabriziodemaria/luigi,jw0201/luigi,bmaggard/luigi,mfcabrera/luigi,foursquare/luigi,samuell/luigi,ehdr/luigi,jamesmcm/luigi,rizzatti/luigi,javrasya/luigi,dstandish/luigi,Houzz/luigi,ivannotes/luigi,Houzz/luigi,ivannotes/luigi,Tarrasch/luigi,republic-analytics/luigi,mbruggmann/luigi,lungetech/luigi,riga/luigi,rizzatti/luigi,lungetech/luigi,mbruggmann/luigi,ContextLogic/luigi,stroykova/luigi,oldpa/luigi,soxofaan/luigi,bmaggard/luigi,spotify/luigi,h3biomed/luigi,samepage-labs/luigi,casey-green/luigi,ContextLogic/luigi,fabriziodemaria/luigi,lungetech/luigi,Magnetic/luigi,Wattpad/luigi,jamesmcm/luigi,rayrrr/luigi,rizzatti/luigi,rayrrr/luigi,stroykova/luigi,PeteW/luigi,oldpa/luigi,dstandish/luigi,bmaggard/luigi,soxofaan/luigi,mfcabrera/luigi,wakamori/luigi,PeteW/luigi,thejens/luigi,javrasya/luigi,ContextLogic/luigi,jw0201/luigi,h3biomed/luigi,wakamori/luigi,republic-analytics/luigi,spotify/luigi,jamesmcm/luigi,republic-analytics/luigi,ContextLogic/luigi,humanlongevity/luigi,ivannotes/luigi,ehdr/luigi,republic-analytics/luigi,PeteW/luigi,fabriziodemaria/luigi,thejens/luigi,thejens/luigi,ehdr/luigi,ivannotes/luigi,PeteW/luigi,dlstadther/luigi,edx/luigi,linsomniac/luigi,adaitche/luigi,soxofaan/luigi,wakamori/luigi,linsomniac/luigi,javrasya/luigi,humanlongevity/luigi,javrasya/luigi,dlstadther/luigi,oldpa/luigi,rizzatti/luigi,linsomniac/luigi,Houzz/luigi,riga/luigi,samuell/luigi,spotify/luigi,dstandish/luigi,casey-green/luigi,adaitche/luigi,samepage-labs/luigi,ehdr/luigi,foursquare/luigi,foursquare/luigi,samuell/luigi,Tarrasch/luigi,adaitche/luigi,edx/luigi,samepage-labs/luigi,Wattpad/luigi,Magnetic/luigi,riga/luigi,samuell/luigi,Magnetic/luigi,Magnetic/luigi,lungetech/luigi,casey-green/luigi,dlstadther/luigi,h3biomed/luigi,humanlongevity/luigi,dlstadther/luigi,thejens/luigi
import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # detect if coverage was running in forked process if sys.version_info >= (3, 4): klass = multiprocessing.process.BaseProcess else: klass = multiprocessing.Process if Collector._collectors: original = multiprocessing.Process._bootstrap class ProcessWithCoverage(multiprocessing.Process): def _bootstrap(self): cov = coverage( data_suffix=True, config_file=os.getenv('COVERAGE_PROCESS_START', True) ) cov.start() try: return original(self) finally: cov.stop() cov.save() if sys.version_info >= (3, 4): klass._bootstrap = ProcessWithCoverage._bootstrap else: multiprocessing.Process = ProcessWithCoverage if os.getenv('FULL_COVERAGE', 'false') == 'true': try: import coverage coverage.process_startup() patch_process_for_coverage() except ImportError: pass Fix scope when setting up multiprocessing with coverage
import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # detect if coverage was running in forked process if sys.version_info >= (3, 4): klass = multiprocessing.process.BaseProcess else: klass = multiprocessing.Process if Collector._collectors: original = multiprocessing.Process._bootstrap class ProcessWithCoverage(multiprocessing.Process): def _bootstrap(self): cov = coverage( data_suffix=True, config_file=os.getenv('COVERAGE_PROCESS_START', True) ) cov.start() try: return original(self) finally: cov.stop() cov.save() if sys.version_info >= (3, 4): klass._bootstrap = ProcessWithCoverage._bootstrap else: multiprocessing.Process = ProcessWithCoverage if os.getenv('FULL_COVERAGE', 'false') == 'true': try: import coverage coverage.process_startup() patch_process_for_coverage() except ImportError: pass
<commit_before>import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # detect if coverage was running in forked process if sys.version_info >= (3, 4): klass = multiprocessing.process.BaseProcess else: klass = multiprocessing.Process if Collector._collectors: original = multiprocessing.Process._bootstrap class ProcessWithCoverage(multiprocessing.Process): def _bootstrap(self): cov = coverage( data_suffix=True, config_file=os.getenv('COVERAGE_PROCESS_START', True) ) cov.start() try: return original(self) finally: cov.stop() cov.save() if sys.version_info >= (3, 4): klass._bootstrap = ProcessWithCoverage._bootstrap else: multiprocessing.Process = ProcessWithCoverage if os.getenv('FULL_COVERAGE', 'false') == 'true': try: import coverage coverage.process_startup() patch_process_for_coverage() except ImportError: pass <commit_msg>Fix scope when setting up multiprocessing with coverage<commit_after>
import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # detect if coverage was running in forked process if sys.version_info >= (3, 4): klass = multiprocessing.process.BaseProcess else: klass = multiprocessing.Process if Collector._collectors: original = multiprocessing.Process._bootstrap class ProcessWithCoverage(multiprocessing.Process): def _bootstrap(self): cov = coverage( data_suffix=True, config_file=os.getenv('COVERAGE_PROCESS_START', True) ) cov.start() try: return original(self) finally: cov.stop() cov.save() if sys.version_info >= (3, 4): klass._bootstrap = ProcessWithCoverage._bootstrap else: multiprocessing.Process = ProcessWithCoverage if os.getenv('FULL_COVERAGE', 'false') == 'true': try: import coverage coverage.process_startup() patch_process_for_coverage() except ImportError: pass
import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # detect if coverage was running in forked process if sys.version_info >= (3, 4): klass = multiprocessing.process.BaseProcess else: klass = multiprocessing.Process if Collector._collectors: original = multiprocessing.Process._bootstrap class ProcessWithCoverage(multiprocessing.Process): def _bootstrap(self): cov = coverage( data_suffix=True, config_file=os.getenv('COVERAGE_PROCESS_START', True) ) cov.start() try: return original(self) finally: cov.stop() cov.save() if sys.version_info >= (3, 4): klass._bootstrap = ProcessWithCoverage._bootstrap else: multiprocessing.Process = ProcessWithCoverage if os.getenv('FULL_COVERAGE', 'false') == 'true': try: import coverage coverage.process_startup() patch_process_for_coverage() except ImportError: pass Fix scope when setting up multiprocessing with coverageimport os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # detect if coverage was running in forked process if sys.version_info >= (3, 4): klass = multiprocessing.process.BaseProcess else: klass = multiprocessing.Process if Collector._collectors: original = multiprocessing.Process._bootstrap class ProcessWithCoverage(multiprocessing.Process): def _bootstrap(self): cov = coverage( data_suffix=True, config_file=os.getenv('COVERAGE_PROCESS_START', True) ) cov.start() try: return original(self) finally: cov.stop() cov.save() if sys.version_info >= (3, 4): klass._bootstrap = ProcessWithCoverage._bootstrap else: multiprocessing.Process = ProcessWithCoverage if os.getenv('FULL_COVERAGE', 'false') == 'true': try: import coverage coverage.process_startup() patch_process_for_coverage() except ImportError: pass
<commit_before>import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # detect if coverage was running in forked process if sys.version_info >= (3, 4): klass = multiprocessing.process.BaseProcess else: klass = multiprocessing.Process if Collector._collectors: original = multiprocessing.Process._bootstrap class ProcessWithCoverage(multiprocessing.Process): def _bootstrap(self): cov = coverage( data_suffix=True, config_file=os.getenv('COVERAGE_PROCESS_START', True) ) cov.start() try: return original(self) finally: cov.stop() cov.save() if sys.version_info >= (3, 4): klass._bootstrap = ProcessWithCoverage._bootstrap else: multiprocessing.Process = ProcessWithCoverage if os.getenv('FULL_COVERAGE', 'false') == 'true': try: import coverage coverage.process_startup() patch_process_for_coverage() except ImportError: pass <commit_msg>Fix scope when setting up multiprocessing with coverage<commit_after>import os import sys def patch_process_for_coverage(): # patch multiprocessing module to get coverage # https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by from coverage.collector import Collector from coverage import coverage import multiprocessing # detect if coverage was running in forked process if sys.version_info >= (3, 4): klass = multiprocessing.process.BaseProcess else: klass = multiprocessing.Process if Collector._collectors: original = multiprocessing.Process._bootstrap class ProcessWithCoverage(multiprocessing.Process): def _bootstrap(self): cov = coverage( data_suffix=True, config_file=os.getenv('COVERAGE_PROCESS_START', True) ) cov.start() try: return original(self) finally: cov.stop() cov.save() if sys.version_info >= (3, 4): klass._bootstrap = ProcessWithCoverage._bootstrap else: multiprocessing.Process = ProcessWithCoverage if os.getenv('FULL_COVERAGE', 'false') == 'true': try: import coverage coverage.process_startup() patch_process_for_coverage() except ImportError: pass
d21547637222d6bb2c3c9d03eae771d033ec47f4
lms/djangoapps/api_manager/management/commands/migrate_orgdata.py
lms/djangoapps/api_manager/management/commands/migrate_orgdata.py
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) migrated_org = Organization.objects.create( name=data['name'], display_name=data['display_name'], contact_name=data['contact_name'], contact_email=data['contact_email'], contact_phone=data['contact_phone'] ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group)
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) name = org.name display_name = data.get('display_name', name) contact_name = data.get('contact_name', None) contact_email = data.get('email', None) if contact_email is None: contact_email = data.get('contact_email', None) contact_phone = data.get('phone', None) if contact_phone is None: contact_phone = data.get('contact_phone', None) migrated_org = Organization.objects.create( name=name, display_name=display_name, contact_name=contact_name, contact_email=contact_email, contact_phone=contact_phone ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group)
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
Python
agpl-3.0
edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) migrated_org = Organization.objects.create( name=data['name'], display_name=data['display_name'], contact_name=data['contact_name'], contact_email=data['contact_email'], contact_phone=data['contact_phone'] ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group) Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) name = org.name display_name = data.get('display_name', name) contact_name = data.get('contact_name', None) contact_email = data.get('email', None) if contact_email is None: contact_email = data.get('contact_email', None) contact_phone = data.get('phone', None) if contact_phone is None: contact_phone = data.get('contact_phone', None) migrated_org = Organization.objects.create( name=name, display_name=display_name, contact_name=contact_name, contact_email=contact_email, contact_phone=contact_phone ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group)
<commit_before>import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) migrated_org = Organization.objects.create( name=data['name'], display_name=data['display_name'], contact_name=data['contact_name'], contact_email=data['contact_email'], contact_phone=data['contact_phone'] ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group) <commit_msg>Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present<commit_after>
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) name = org.name display_name = data.get('display_name', name) contact_name = data.get('contact_name', None) contact_email = data.get('email', None) if contact_email is None: contact_email = data.get('contact_email', None) contact_phone = data.get('phone', None) if contact_phone is None: contact_phone = data.get('contact_phone', None) migrated_org = Organization.objects.create( name=name, display_name=display_name, contact_name=contact_name, contact_email=contact_email, contact_phone=contact_phone ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group)
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) migrated_org = Organization.objects.create( name=data['name'], display_name=data['display_name'], contact_name=data['contact_name'], contact_email=data['contact_email'], contact_phone=data['contact_phone'] ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group) Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not presentimport json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) name = org.name display_name = data.get('display_name', name) contact_name = data.get('contact_name', None) contact_email = data.get('email', None) if contact_email is None: contact_email = data.get('contact_email', None) contact_phone = data.get('phone', None) if contact_phone is None: contact_phone = data.get('contact_phone', None) migrated_org = Organization.objects.create( name=name, display_name=display_name, contact_name=contact_name, contact_email=contact_email, contact_phone=contact_phone ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group)
<commit_before>import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) migrated_org = Organization.objects.create( name=data['name'], display_name=data['display_name'], contact_name=data['contact_name'], contact_email=data['contact_email'], contact_phone=data['contact_phone'] ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group) <commit_msg>Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present<commit_after>import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) name = org.name display_name = data.get('display_name', name) contact_name = data.get('contact_name', None) contact_email = data.get('email', None) if contact_email is None: contact_email = data.get('contact_email', None) contact_phone = data.get('phone', None) if contact_phone is None: contact_phone = data.get('contact_phone', None) migrated_org = Organization.objects.create( name=name, display_name=display_name, contact_name=contact_name, contact_email=contact_email, contact_phone=contact_phone ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group)
721015d5a7ea9745094f06dfcea3625c20555992
inidiff/tests/test_diff.py
inidiff/tests/test_diff.py
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0)
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) def test_number_is_different(self): diffs = inidiff.diff(INI_1, INI_2) first, second = diffs[0] self.assertEqual('number', first[1])
Check number is the field that is different
Check number is the field that is different
Python
mit
kragniz/inidiff
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) Check number is the field that is different
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) def test_number_is_different(self): diffs = inidiff.diff(INI_1, INI_2) first, second = diffs[0] self.assertEqual('number', first[1])
<commit_before>import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) <commit_msg>Check number is the field that is different<commit_after>
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) def test_number_is_different(self): diffs = inidiff.diff(INI_1, INI_2) first, second = diffs[0] self.assertEqual('number', first[1])
import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) Check number is the field that is differentimport unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) def test_number_is_different(self): diffs = inidiff.diff(INI_1, INI_2) first, second = diffs[0] self.assertEqual('number', first[1])
<commit_before>import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) <commit_msg>Check number is the field that is different<commit_after>import unittest import inidiff INI_1 = '''[test] number=10 ''' INI_2 = '''[test] number=20 ''' class TestDiff(unittest.TestCase): """Test diffs diff things.""" def test_no_differences(self): self.assertEqual([], inidiff.diff(INI_1, INI_1)) def test_some_differences(self): self.assertTrue(len(inidiff.diff(INI_1, INI_2)) > 0) def test_number_is_different(self): diffs = inidiff.diff(INI_1, INI_2) first, second = diffs[0] self.assertEqual('number', first[1])
29594c877766c387fe25d2aac09244402cbf41d7
FreeMemory.py
FreeMemory.py
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif "Cached" in line: data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
Fix for bug where we were using SwapCached instead of Cached values in availableMemory Calculation
Fix for bug where we were using SwapCached instead of Cached values in availableMemory Calculation
Python
apache-2.0
inbloom/server-density-plugins
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif "Cached" in line: data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data Fix for bug where we were using SwapCached instead of Cached values in availableMemory Calculation
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
<commit_before>/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif "Cached" in line: data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data <commit_msg>Fix for bug where we were using SwapCached instead of Cached values in availableMemory Calculation<commit_after>
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif "Cached" in line: data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data Fix for bug where we were using SwapCached instead of Cached values in availableMemory Calculation/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
<commit_before>/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif "Cached" in line: data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data <commit_msg>Fix for bug where we were using SwapCached instead of Cached values in availableMemory Calculation<commit_after>/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import re class FreeMemory: def __init__(self, agentConfig, checksLogger, rawConfig): self.agentConfig = agentConfig self.checksLogger = checksLogger self.rawConfig = rawConfig def run(self): data = { } for line in open("/proc/meminfo"): if "MemFree" in line: data['MemFree'] = int(re.findall('\d+', line)[0]) elif "Buffers" in line: data['Buffers'] = int(re.findall('\d+', line)[0]) elif re.match('^Cached', line): data['Cached'] = int(re.findall('\d+', line)[0]) data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached'] return data
ff2b16c5f8c69ccfeb808aeb832a5c6afcecb8ab
sift/models/build.py
sift/models/build.py
import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, text.TermIndicies, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ]
import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, links.EntityVocab, links.NamePartCounts, text.TermVocab, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.MappedEntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ]
Update cli for recently added models
Update cli for recently added models
Python
mit
wikilinks/sift,wikilinks/sift
import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, text.TermIndicies, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ] Update cli for recently added models
import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, links.EntityVocab, links.NamePartCounts, text.TermVocab, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.MappedEntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ]
<commit_before>import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, text.TermIndicies, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ] <commit_msg>Update cli for recently added models<commit_after>
import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, links.EntityVocab, links.NamePartCounts, text.TermVocab, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.MappedEntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ]
import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, text.TermIndicies, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ] Update cli for recently added modelsimport ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, links.EntityVocab, links.NamePartCounts, text.TermVocab, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.MappedEntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ]
<commit_before>import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, text.TermIndicies, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ] <commit_msg>Update cli for recently added models<commit_after>import ujson as json from sift.build import DatasetBuilder from sift.models import links, text, embeddings class BuildDocModel(DatasetBuilder): """ Build a model over a corpus of text documents """ @classmethod def providers(cls): return [ links.EntityCounts, links.EntityNameCounts, links.EntityInlinks, links.EntityVocab, links.NamePartCounts, text.TermVocab, text.TermIdfs, text.TermFrequencies, text.TermDocumentFrequencies, text.EntityMentions, text.MappedEntityMentions, text.EntityMentionTermFrequency, text.TermEntityIndex, embeddings.EntitySkipGramEmbeddings, ]
610bd0fb6f25f790b1ff6e4adb9d87f10233e39e
statirator/core/models.py
statirator/core/models.py
class TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS) self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS) slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug} lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang} return self.__class__.objects.filter(**slug).exclude(**lang)
class TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS) self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS) slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug} lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang} return self.__class__.objects.filter(**slug).exclude(**lang) def get_language(self): "Get the language display for this item's language" attr = 'get_{0}_display'.format(self.LANG_FIELD_FOR_TRANSLATIONS) return getattr(self, attr)()
Add get_language method for TranslationsMixin
Add get_language method for TranslationsMixin
Python
mit
MeirKriheli/statirator,MeirKriheli/statirator,MeirKriheli/statirator
class TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS) self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS) slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug} lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang} return self.__class__.objects.filter(**slug).exclude(**lang) Add get_language method for TranslationsMixin
class TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS) self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS) slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug} lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang} return self.__class__.objects.filter(**slug).exclude(**lang) def get_language(self): "Get the language display for this item's language" attr = 'get_{0}_display'.format(self.LANG_FIELD_FOR_TRANSLATIONS) return getattr(self, attr)()
<commit_before>class TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS) self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS) slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug} lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang} return self.__class__.objects.filter(**slug).exclude(**lang) <commit_msg>Add get_language method for TranslationsMixin<commit_after>
class TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS) self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS) slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug} lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang} return self.__class__.objects.filter(**slug).exclude(**lang) def get_language(self): "Get the language display for this item's language" attr = 'get_{0}_display'.format(self.LANG_FIELD_FOR_TRANSLATIONS) return getattr(self, attr)()
class TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS) self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS) slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug} lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang} return self.__class__.objects.filter(**slug).exclude(**lang) Add get_language method for TranslationsMixinclass TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS) self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS) slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug} lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang} return self.__class__.objects.filter(**slug).exclude(**lang) def get_language(self): "Get the language display for this item's language" attr = 'get_{0}_display'.format(self.LANG_FIELD_FOR_TRANSLATIONS) return getattr(self, attr)()
<commit_before>class TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS) self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS) slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug} lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang} return self.__class__.objects.filter(**slug).exclude(**lang) <commit_msg>Add get_language method for TranslationsMixin<commit_after>class TranslationsMixin(object): "Helper for getting transalations" SLUG_FIELD_FOR_TRANSLATIONS = 'slug' # Overide in models if needed LANG_FIELD_FOR_TRANSLATIONS = 'language' # Overide in models if needed def get_translations(self): "Query set for the translations" self_slug = getattr(self, self.SLUG_FIELD_FOR_TRANSLATIONS) self_lang = getattr(self, self.LANG_FIELD_FOR_TRANSLATIONS) slug = {self.SLUG_FIELD_FOR_TRANSLATIONS + '__exact': self_slug} lang = {self.LANG_FIELD_FOR_TRANSLATIONS + '__exact': self_lang} return self.__class__.objects.filter(**slug).exclude(**lang) def get_language(self): "Get the language display for this item's language" attr = 'get_{0}_display'.format(self.LANG_FIELD_FOR_TRANSLATIONS) return getattr(self, attr)()
0a8f5b342c0174b712ac895e71d56132c313729f
stonemason/util/tempfn.py
stonemason/util/tempfn.py
# -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): """Generate a temporary file name with specified suffix and prefix. >>> from stonemason.util.tempfn import generate_temp_filename >>> generate_temp_filename('/tmp', prefix='hello-', suffix='.tmp') #doctest: +ELLIPSIS '/tmp/hello-....tmp' :param dirname: Base temp directory, default is system temp dir. :type dirname: str :param prefix: Prefix of the temporary file name, default is ``tmp`` :type prefix: str :param suffix: Suffix of the temporary file name, default is emptry string. :type suffix: str :return: Generated temporary file name. :rtype: str :raises: :class:`IOError` """ assert isinstance(suffix, six.string_types) assert isinstance(prefix, six.string_types) if not dirname: dirname = tempfile.gettempdir() for n, temp in enumerate(tempfile._get_candidate_names()): basename = '%s%s%s' % (prefix, temp, suffix) return os.path.join(dirname, basename) raise IOError(errno.EEXIST, 'Exhausted temporary file names.')
# -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six STONEMASON_TEMP_ROOT = 'stonemason' def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): """Generate a temporary file name with specified suffix and prefix. >>> from stonemason.util.tempfn import generate_temp_filename >>> generate_temp_filename('/tmp', prefix='hello-', suffix='.tmp') #doctest: +ELLIPSIS '/tmp/hello-....tmp' :param dirname: Base temp directory, default is system temp dir. :type dirname: str :param prefix: Prefix of the temporary file name, default is ``tmp`` :type prefix: str :param suffix: Suffix of the temporary file name, default is emptry string. :type suffix: str :return: Generated temporary file name. :rtype: str :raises: :class:`IOError` """ assert isinstance(suffix, six.string_types) assert isinstance(prefix, six.string_types) if not dirname: dirname = os.path.join(tempfile.gettempdir(), STONEMASON_TEMP_ROOT) if not os.path.exists(dirname): os.mkdir(dirname) for n, temp in enumerate(tempfile._get_candidate_names()): basename = '%s%s%s' % (prefix, temp, suffix) return os.path.join(dirname, basename) raise IOError(errno.EEXIST, 'Exhausted temporary file names.')
Add root dir for temp files
FEATURE: Add root dir for temp files
Python
mit
Kotaimen/stonemason,Kotaimen/stonemason
# -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): """Generate a temporary file name with specified suffix and prefix. >>> from stonemason.util.tempfn import generate_temp_filename >>> generate_temp_filename('/tmp', prefix='hello-', suffix='.tmp') #doctest: +ELLIPSIS '/tmp/hello-....tmp' :param dirname: Base temp directory, default is system temp dir. :type dirname: str :param prefix: Prefix of the temporary file name, default is ``tmp`` :type prefix: str :param suffix: Suffix of the temporary file name, default is emptry string. :type suffix: str :return: Generated temporary file name. :rtype: str :raises: :class:`IOError` """ assert isinstance(suffix, six.string_types) assert isinstance(prefix, six.string_types) if not dirname: dirname = tempfile.gettempdir() for n, temp in enumerate(tempfile._get_candidate_names()): basename = '%s%s%s' % (prefix, temp, suffix) return os.path.join(dirname, basename) raise IOError(errno.EEXIST, 'Exhausted temporary file names.') FEATURE: Add root dir for temp files
# -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six STONEMASON_TEMP_ROOT = 'stonemason' def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): """Generate a temporary file name with specified suffix and prefix. >>> from stonemason.util.tempfn import generate_temp_filename >>> generate_temp_filename('/tmp', prefix='hello-', suffix='.tmp') #doctest: +ELLIPSIS '/tmp/hello-....tmp' :param dirname: Base temp directory, default is system temp dir. :type dirname: str :param prefix: Prefix of the temporary file name, default is ``tmp`` :type prefix: str :param suffix: Suffix of the temporary file name, default is emptry string. :type suffix: str :return: Generated temporary file name. :rtype: str :raises: :class:`IOError` """ assert isinstance(suffix, six.string_types) assert isinstance(prefix, six.string_types) if not dirname: dirname = os.path.join(tempfile.gettempdir(), STONEMASON_TEMP_ROOT) if not os.path.exists(dirname): os.mkdir(dirname) for n, temp in enumerate(tempfile._get_candidate_names()): basename = '%s%s%s' % (prefix, temp, suffix) return os.path.join(dirname, basename) raise IOError(errno.EEXIST, 'Exhausted temporary file names.')
<commit_before># -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): """Generate a temporary file name with specified suffix and prefix. >>> from stonemason.util.tempfn import generate_temp_filename >>> generate_temp_filename('/tmp', prefix='hello-', suffix='.tmp') #doctest: +ELLIPSIS '/tmp/hello-....tmp' :param dirname: Base temp directory, default is system temp dir. :type dirname: str :param prefix: Prefix of the temporary file name, default is ``tmp`` :type prefix: str :param suffix: Suffix of the temporary file name, default is emptry string. :type suffix: str :return: Generated temporary file name. :rtype: str :raises: :class:`IOError` """ assert isinstance(suffix, six.string_types) assert isinstance(prefix, six.string_types) if not dirname: dirname = tempfile.gettempdir() for n, temp in enumerate(tempfile._get_candidate_names()): basename = '%s%s%s' % (prefix, temp, suffix) return os.path.join(dirname, basename) raise IOError(errno.EEXIST, 'Exhausted temporary file names.') <commit_msg>FEATURE: Add root dir for temp files<commit_after>
# -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six STONEMASON_TEMP_ROOT = 'stonemason' def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): """Generate a temporary file name with specified suffix and prefix. >>> from stonemason.util.tempfn import generate_temp_filename >>> generate_temp_filename('/tmp', prefix='hello-', suffix='.tmp') #doctest: +ELLIPSIS '/tmp/hello-....tmp' :param dirname: Base temp directory, default is system temp dir. :type dirname: str :param prefix: Prefix of the temporary file name, default is ``tmp`` :type prefix: str :param suffix: Suffix of the temporary file name, default is emptry string. :type suffix: str :return: Generated temporary file name. :rtype: str :raises: :class:`IOError` """ assert isinstance(suffix, six.string_types) assert isinstance(prefix, six.string_types) if not dirname: dirname = os.path.join(tempfile.gettempdir(), STONEMASON_TEMP_ROOT) if not os.path.exists(dirname): os.mkdir(dirname) for n, temp in enumerate(tempfile._get_candidate_names()): basename = '%s%s%s' % (prefix, temp, suffix) return os.path.join(dirname, basename) raise IOError(errno.EEXIST, 'Exhausted temporary file names.')
# -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): """Generate a temporary file name with specified suffix and prefix. >>> from stonemason.util.tempfn import generate_temp_filename >>> generate_temp_filename('/tmp', prefix='hello-', suffix='.tmp') #doctest: +ELLIPSIS '/tmp/hello-....tmp' :param dirname: Base temp directory, default is system temp dir. :type dirname: str :param prefix: Prefix of the temporary file name, default is ``tmp`` :type prefix: str :param suffix: Suffix of the temporary file name, default is emptry string. :type suffix: str :return: Generated temporary file name. :rtype: str :raises: :class:`IOError` """ assert isinstance(suffix, six.string_types) assert isinstance(prefix, six.string_types) if not dirname: dirname = tempfile.gettempdir() for n, temp in enumerate(tempfile._get_candidate_names()): basename = '%s%s%s' % (prefix, temp, suffix) return os.path.join(dirname, basename) raise IOError(errno.EEXIST, 'Exhausted temporary file names.') FEATURE: Add root dir for temp files# -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six STONEMASON_TEMP_ROOT = 'stonemason' def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): """Generate a temporary file name with specified suffix and prefix. >>> from stonemason.util.tempfn import generate_temp_filename >>> generate_temp_filename('/tmp', prefix='hello-', suffix='.tmp') #doctest: +ELLIPSIS '/tmp/hello-....tmp' :param dirname: Base temp directory, default is system temp dir. :type dirname: str :param prefix: Prefix of the temporary file name, default is ``tmp`` :type prefix: str :param suffix: Suffix of the temporary file name, default is emptry string. :type suffix: str :return: Generated temporary file name. :rtype: str :raises: :class:`IOError` """ assert isinstance(suffix, six.string_types) assert isinstance(prefix, six.string_types) if not dirname: dirname = os.path.join(tempfile.gettempdir(), STONEMASON_TEMP_ROOT) if not os.path.exists(dirname): os.mkdir(dirname) for n, temp in enumerate(tempfile._get_candidate_names()): basename = '%s%s%s' % (prefix, temp, suffix) return os.path.join(dirname, basename) raise IOError(errno.EEXIST, 'Exhausted temporary file names.')
<commit_before># -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): """Generate a temporary file name with specified suffix and prefix. >>> from stonemason.util.tempfn import generate_temp_filename >>> generate_temp_filename('/tmp', prefix='hello-', suffix='.tmp') #doctest: +ELLIPSIS '/tmp/hello-....tmp' :param dirname: Base temp directory, default is system temp dir. :type dirname: str :param prefix: Prefix of the temporary file name, default is ``tmp`` :type prefix: str :param suffix: Suffix of the temporary file name, default is emptry string. :type suffix: str :return: Generated temporary file name. :rtype: str :raises: :class:`IOError` """ assert isinstance(suffix, six.string_types) assert isinstance(prefix, six.string_types) if not dirname: dirname = tempfile.gettempdir() for n, temp in enumerate(tempfile._get_candidate_names()): basename = '%s%s%s' % (prefix, temp, suffix) return os.path.join(dirname, basename) raise IOError(errno.EEXIST, 'Exhausted temporary file names.') <commit_msg>FEATURE: Add root dir for temp files<commit_after># -*- coding:utf-8 -*- """ stonemason.util.tempfn ~~~~~~~~~~~~~~~~~~~~~~ Generate a temp filename """ __author__ = 'ray' __date__ = '8/30/12' import os import errno import tempfile import six STONEMASON_TEMP_ROOT = 'stonemason' def generate_temp_filename(dirname=None, prefix='tmp', suffix=''): """Generate a temporary file name with specified suffix and prefix. >>> from stonemason.util.tempfn import generate_temp_filename >>> generate_temp_filename('/tmp', prefix='hello-', suffix='.tmp') #doctest: +ELLIPSIS '/tmp/hello-....tmp' :param dirname: Base temp directory, default is system temp dir. :type dirname: str :param prefix: Prefix of the temporary file name, default is ``tmp`` :type prefix: str :param suffix: Suffix of the temporary file name, default is emptry string. :type suffix: str :return: Generated temporary file name. :rtype: str :raises: :class:`IOError` """ assert isinstance(suffix, six.string_types) assert isinstance(prefix, six.string_types) if not dirname: dirname = os.path.join(tempfile.gettempdir(), STONEMASON_TEMP_ROOT) if not os.path.exists(dirname): os.mkdir(dirname) for n, temp in enumerate(tempfile._get_candidate_names()): basename = '%s%s%s' % (prefix, temp, suffix) return os.path.join(dirname, basename) raise IOError(errno.EEXIST, 'Exhausted temporary file names.')
e67bbc3aa791947d24895ba5b0286e27323a4074
plugins/mtg.py
plugins/mtg.py
import urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic the Gathering card given <name> ''' try: card = card_search(inp)[0] except IndexError: return "Card not found." for valid_edition in range(len(card["editions"])): if card["editions"][valid_edition]["multiverse_id"] != 0 : break else: continue results = { "name": card["name"], "types": ", ".join(t.capitalize() for t in card["types"]), "cost": card["cost"].replace('{','').replace('}',''), "text": card["text"].replace('\n',' '), "multiverse_id": card["editions"][valid_edition]["multiverse_id"], } return u"{name} - {types} - {cost} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results) if __name__ == "__main__": print card_search("Black Lotus") print mtg("Black Lotus")
import urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic the Gathering card given <name> ''' try: card = card_search(inp)[0] except IndexError: return "Card not found." for valid_edition in range(len(card["editions"])): if card["editions"][valid_edition]["multiverse_id"] != 0 : break results = { "name": card["name"], "types": ", ".join(t.capitalize() for t in card["types"]), "cost": card["cost"].replace('{','').replace('}',''), "text": card["text"].replace('\n',' ').replace('{T}',u'\u27F3').replace('{S}',u'\u2744'), "multiverse_id": card["editions"][valid_edition]["multiverse_id"], } return u"{name} - {cost} - {types} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results) if __name__ == "__main__": print card_search("Black Lotus") print mtg("Black Lotus")
Replace {T} with a unicode tap symbol approximation and replace {S} with a unicode snowflake, how exiting. More symbol replacements to follow
Replace {T} with a unicode tap symbol approximation and replace {S} with a unicode snowflake, how exiting. More symbol replacements to follow
Python
unlicense
rmmh/skybot,TeamPeggle/ppp-helpdesk,parkrrr/skybot,jmgao/skybot,crisisking/skybot,olslash/skybot,ddwo/nhl-bot
import urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic the Gathering card given <name> ''' try: card = card_search(inp)[0] except IndexError: return "Card not found." for valid_edition in range(len(card["editions"])): if card["editions"][valid_edition]["multiverse_id"] != 0 : break else: continue results = { "name": card["name"], "types": ", ".join(t.capitalize() for t in card["types"]), "cost": card["cost"].replace('{','').replace('}',''), "text": card["text"].replace('\n',' '), "multiverse_id": card["editions"][valid_edition]["multiverse_id"], } return u"{name} - {types} - {cost} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results) if __name__ == "__main__": print card_search("Black Lotus") print mtg("Black Lotus") Replace {T} with a unicode tap symbol approximation and replace {S} with a unicode snowflake, how exiting. More symbol replacements to follow
import urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic the Gathering card given <name> ''' try: card = card_search(inp)[0] except IndexError: return "Card not found." for valid_edition in range(len(card["editions"])): if card["editions"][valid_edition]["multiverse_id"] != 0 : break results = { "name": card["name"], "types": ", ".join(t.capitalize() for t in card["types"]), "cost": card["cost"].replace('{','').replace('}',''), "text": card["text"].replace('\n',' ').replace('{T}',u'\u27F3').replace('{S}',u'\u2744'), "multiverse_id": card["editions"][valid_edition]["multiverse_id"], } return u"{name} - {cost} - {types} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results) if __name__ == "__main__": print card_search("Black Lotus") print mtg("Black Lotus")
<commit_before>import urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic the Gathering card given <name> ''' try: card = card_search(inp)[0] except IndexError: return "Card not found." for valid_edition in range(len(card["editions"])): if card["editions"][valid_edition]["multiverse_id"] != 0 : break else: continue results = { "name": card["name"], "types": ", ".join(t.capitalize() for t in card["types"]), "cost": card["cost"].replace('{','').replace('}',''), "text": card["text"].replace('\n',' '), "multiverse_id": card["editions"][valid_edition]["multiverse_id"], } return u"{name} - {types} - {cost} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results) if __name__ == "__main__": print card_search("Black Lotus") print mtg("Black Lotus") <commit_msg>Replace {T} with a unicode tap symbol approximation and replace {S} with a unicode snowflake, how exiting. More symbol replacements to follow<commit_after>
import urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic the Gathering card given <name> ''' try: card = card_search(inp)[0] except IndexError: return "Card not found." for valid_edition in range(len(card["editions"])): if card["editions"][valid_edition]["multiverse_id"] != 0 : break results = { "name": card["name"], "types": ", ".join(t.capitalize() for t in card["types"]), "cost": card["cost"].replace('{','').replace('}',''), "text": card["text"].replace('\n',' ').replace('{T}',u'\u27F3').replace('{S}',u'\u2744'), "multiverse_id": card["editions"][valid_edition]["multiverse_id"], } return u"{name} - {cost} - {types} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results) if __name__ == "__main__": print card_search("Black Lotus") print mtg("Black Lotus")
import urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic the Gathering card given <name> ''' try: card = card_search(inp)[0] except IndexError: return "Card not found." for valid_edition in range(len(card["editions"])): if card["editions"][valid_edition]["multiverse_id"] != 0 : break else: continue results = { "name": card["name"], "types": ", ".join(t.capitalize() for t in card["types"]), "cost": card["cost"].replace('{','').replace('}',''), "text": card["text"].replace('\n',' '), "multiverse_id": card["editions"][valid_edition]["multiverse_id"], } return u"{name} - {types} - {cost} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results) if __name__ == "__main__": print card_search("Black Lotus") print mtg("Black Lotus") Replace {T} with a unicode tap symbol approximation and replace {S} with a unicode snowflake, how exiting. More symbol replacements to followimport urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic the Gathering card given <name> ''' try: card = card_search(inp)[0] except IndexError: return "Card not found." for valid_edition in range(len(card["editions"])): if card["editions"][valid_edition]["multiverse_id"] != 0 : break results = { "name": card["name"], "types": ", ".join(t.capitalize() for t in card["types"]), "cost": card["cost"].replace('{','').replace('}',''), "text": card["text"].replace('\n',' ').replace('{T}',u'\u27F3').replace('{S}',u'\u2744'), "multiverse_id": card["editions"][valid_edition]["multiverse_id"], } return u"{name} - {cost} - {types} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results) if __name__ == "__main__": print card_search("Black Lotus") print mtg("Black Lotus")
<commit_before>import urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic the Gathering card given <name> ''' try: card = card_search(inp)[0] except IndexError: return "Card not found." for valid_edition in range(len(card["editions"])): if card["editions"][valid_edition]["multiverse_id"] != 0 : break else: continue results = { "name": card["name"], "types": ", ".join(t.capitalize() for t in card["types"]), "cost": card["cost"].replace('{','').replace('}',''), "text": card["text"].replace('\n',' '), "multiverse_id": card["editions"][valid_edition]["multiverse_id"], } return u"{name} - {types} - {cost} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results) if __name__ == "__main__": print card_search("Black Lotus") print mtg("Black Lotus") <commit_msg>Replace {T} with a unicode tap symbol approximation and replace {S} with a unicode snowflake, how exiting. More symbol replacements to follow<commit_after>import urllib from util import hook, http def card_search(query): base_url = "https://api.deckbrew.com" name = urllib.quote_plus(query) search_url = base_url + "/mtg/cards?name=" + name return http.get_json(search_url) @hook.command def mtg(inp, say=None): '''.mtg <name> - Searches for Magic the Gathering card given <name> ''' try: card = card_search(inp)[0] except IndexError: return "Card not found." for valid_edition in range(len(card["editions"])): if card["editions"][valid_edition]["multiverse_id"] != 0 : break results = { "name": card["name"], "types": ", ".join(t.capitalize() for t in card["types"]), "cost": card["cost"].replace('{','').replace('}',''), "text": card["text"].replace('\n',' ').replace('{T}',u'\u27F3').replace('{S}',u'\u2744'), "multiverse_id": card["editions"][valid_edition]["multiverse_id"], } return u"{name} - {cost} - {types} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results) if __name__ == "__main__": print card_search("Black Lotus") print mtg("Black Lotus")
888fd2a46783be37f00412f3b7e5d720722a1afc
test_tinymce/models.py
test_tinymce/models.py
from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMCE 4 rendering in admin inlines """ content = HTMLField(verbose_name='HTML Child Content') parent = models.ForeignKey(TestModel)
from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMCE 4 rendering in admin inlines """ content = HTMLField(verbose_name='HTML Child Content') parent = models.ForeignKey(TestModel, on_delete=models.CASCADE)
Fix tests with Django 2.0
Fix tests with Django 2.0
Python
mit
romanvm/django-tinymce4-lite,romanvm/django-tinymce4-lite,romanvm/django-tinymce4-lite
from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMCE 4 rendering in admin inlines """ content = HTMLField(verbose_name='HTML Child Content') parent = models.ForeignKey(TestModel) Fix tests with Django 2.0
from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMCE 4 rendering in admin inlines """ content = HTMLField(verbose_name='HTML Child Content') parent = models.ForeignKey(TestModel, on_delete=models.CASCADE)
<commit_before>from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMCE 4 rendering in admin inlines """ content = HTMLField(verbose_name='HTML Child Content') parent = models.ForeignKey(TestModel) <commit_msg>Fix tests with Django 2.0<commit_after>
from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMCE 4 rendering in admin inlines """ content = HTMLField(verbose_name='HTML Child Content') parent = models.ForeignKey(TestModel, on_delete=models.CASCADE)
from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMCE 4 rendering in admin inlines """ content = HTMLField(verbose_name='HTML Child Content') parent = models.ForeignKey(TestModel) Fix tests with Django 2.0from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMCE 4 rendering in admin inlines """ content = HTMLField(verbose_name='HTML Child Content') parent = models.ForeignKey(TestModel, on_delete=models.CASCADE)
<commit_before>from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMCE 4 rendering in admin inlines """ content = HTMLField(verbose_name='HTML Child Content') parent = models.ForeignKey(TestModel) <commit_msg>Fix tests with Django 2.0<commit_after>from __future__ import absolute_import from django.db import models from tinymce import HTMLField class TestModel(models.Model): """ A model for testing TinyMCE 4 rendering """ content = HTMLField(verbose_name='HTML Content') class TestChildModel(models.Model): """ A model for testing TinyMCE 4 rendering in admin inlines """ content = HTMLField(verbose_name='HTML Child Content') parent = models.ForeignKey(TestModel, on_delete=models.CASCADE)
8ccaed4590cb89d95b949d71934ee198f1b0574e
ideas/admin.py
ideas/admin.py
from .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatrix Backend" index_title = "Administrator" class IdeaAdmin(admin.ModelAdmin): list_display = ('name', 'votes', 'description', 'register', 'is_active') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() class OutstandingAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'comment', 'register') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() admin_site = MyAdminSite(name='myadmin') admin_site.register(User) admin_site.register(Group) admin_site.register(Idea, IdeaAdmin) admin_site.register(Outstanding, OutstandingAdmin)
from .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.admin import UserAdmin, GroupAdmin from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatrix Backend" index_title = "Administrator" class IdeaAdmin(admin.ModelAdmin): list_display = ('name', 'votes', 'description', 'register', 'is_active') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() class OutstandingAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'comment', 'register') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() admin_site = MyAdminSite(name='myadmin') admin_site.register(User, UserAdmin) admin_site.register(Group, GroupAdmin) admin_site.register(Idea, IdeaAdmin) admin_site.register(Outstanding, OutstandingAdmin)
Add UserAdmin and GroupAdmin to custom AdminSite
Add UserAdmin and GroupAdmin to custom AdminSite
Python
mit
neosergio/vote_hackatrix_backend
from .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatrix Backend" index_title = "Administrator" class IdeaAdmin(admin.ModelAdmin): list_display = ('name', 'votes', 'description', 'register', 'is_active') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() class OutstandingAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'comment', 'register') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() admin_site = MyAdminSite(name='myadmin') admin_site.register(User) admin_site.register(Group) admin_site.register(Idea, IdeaAdmin) admin_site.register(Outstanding, OutstandingAdmin) Add UserAdmin and GroupAdmin to custom AdminSite
from .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.admin import UserAdmin, GroupAdmin from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatrix Backend" index_title = "Administrator" class IdeaAdmin(admin.ModelAdmin): list_display = ('name', 'votes', 'description', 'register', 'is_active') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() class OutstandingAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'comment', 'register') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() admin_site = MyAdminSite(name='myadmin') admin_site.register(User, UserAdmin) admin_site.register(Group, GroupAdmin) admin_site.register(Idea, IdeaAdmin) admin_site.register(Outstanding, OutstandingAdmin)
<commit_before>from .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatrix Backend" index_title = "Administrator" class IdeaAdmin(admin.ModelAdmin): list_display = ('name', 'votes', 'description', 'register', 'is_active') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() class OutstandingAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'comment', 'register') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() admin_site = MyAdminSite(name='myadmin') admin_site.register(User) admin_site.register(Group) admin_site.register(Idea, IdeaAdmin) admin_site.register(Outstanding, OutstandingAdmin) <commit_msg>Add UserAdmin and GroupAdmin to custom AdminSite<commit_after>
from .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.admin import UserAdmin, GroupAdmin from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatrix Backend" index_title = "Administrator" class IdeaAdmin(admin.ModelAdmin): list_display = ('name', 'votes', 'description', 'register', 'is_active') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() class OutstandingAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'comment', 'register') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() admin_site = MyAdminSite(name='myadmin') admin_site.register(User, UserAdmin) admin_site.register(Group, GroupAdmin) admin_site.register(Idea, IdeaAdmin) admin_site.register(Outstanding, OutstandingAdmin)
from .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatrix Backend" index_title = "Administrator" class IdeaAdmin(admin.ModelAdmin): list_display = ('name', 'votes', 'description', 'register', 'is_active') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() class OutstandingAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'comment', 'register') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() admin_site = MyAdminSite(name='myadmin') admin_site.register(User) admin_site.register(Group) admin_site.register(Idea, IdeaAdmin) admin_site.register(Outstanding, OutstandingAdmin) Add UserAdmin and GroupAdmin to custom AdminSitefrom .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.admin import UserAdmin, GroupAdmin from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatrix Backend" index_title = "Administrator" class IdeaAdmin(admin.ModelAdmin): list_display = ('name', 'votes', 'description', 'register', 'is_active') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() class OutstandingAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'comment', 'register') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() admin_site = MyAdminSite(name='myadmin') admin_site.register(User, UserAdmin) admin_site.register(Group, GroupAdmin) admin_site.register(Idea, IdeaAdmin) admin_site.register(Outstanding, OutstandingAdmin)
<commit_before>from .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatrix Backend" index_title = "Administrator" class IdeaAdmin(admin.ModelAdmin): list_display = ('name', 'votes', 'description', 'register', 'is_active') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() class OutstandingAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'comment', 'register') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() admin_site = MyAdminSite(name='myadmin') admin_site.register(User) admin_site.register(Group) admin_site.register(Idea, IdeaAdmin) admin_site.register(Outstanding, OutstandingAdmin) <commit_msg>Add UserAdmin and GroupAdmin to custom AdminSite<commit_after>from .models import Idea, Outstanding from django.contrib import admin from django.contrib.admin import AdminSite from django.contrib.auth.admin import UserAdmin, GroupAdmin from django.contrib.auth.models import User, Group class MyAdminSite(AdminSite): site_header = "Hackatrix Backend" site_title = "Hackatrix Backend" index_title = "Administrator" class IdeaAdmin(admin.ModelAdmin): list_display = ('name', 'votes', 'description', 'register', 'is_active') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() class OutstandingAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'comment', 'register') def save_model(self, request, obj, form, change): if getattr(obj, 'register', None) is None: obj.register = request.user obj.save() admin_site = MyAdminSite(name='myadmin') admin_site.register(User, UserAdmin) admin_site.register(Group, GroupAdmin) admin_site.register(Idea, IdeaAdmin) admin_site.register(Outstanding, OutstandingAdmin)
118ca7981db7443ef3cd6247e699799548cd883a
pydir/utils.py
pydir/utils.py
import os import subprocess import sys def shellcmd(command, echo=True): if echo: print '[cmd]', command if not isinstance(command, str): command = ' '.join(command) stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result def FindBaseNaCl(): """Find the base native_client/ directory.""" nacl = 'native_client' path_list = os.getcwd().split(os.sep) if nacl not in path_list: return None last_index = len(path_list) - path_list[::-1].index(nacl) return os.sep.join(path_list[:last_index])
import os import subprocess import sys def shellcmd(command, echo=True): if not isinstance(command, str): command = ' '.join(command) if echo: print '[cmd]', command stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result def FindBaseNaCl(): """Find the base native_client/ directory.""" nacl = 'native_client' path_list = os.getcwd().split(os.sep) if nacl not in path_list: return None last_index = len(path_list) - path_list[::-1].index(nacl) return os.sep.join(path_list[:last_index])
Change the echoing in shellcmd().
Subzero: Change the echoing in shellcmd(). This makes it much easier to copy/paste the output. BUG= none R=jvoung@chromium.org Review URL: https://codereview.chromium.org/611983003
Python
apache-2.0
google/swiftshader,google/swiftshader,bkaradzic/SwiftShader,bkaradzic/SwiftShader,bkaradzic/SwiftShader,bkaradzic/SwiftShader,google/swiftshader,bkaradzic/SwiftShader
import os import subprocess import sys def shellcmd(command, echo=True): if echo: print '[cmd]', command if not isinstance(command, str): command = ' '.join(command) stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result def FindBaseNaCl(): """Find the base native_client/ directory.""" nacl = 'native_client' path_list = os.getcwd().split(os.sep) if nacl not in path_list: return None last_index = len(path_list) - path_list[::-1].index(nacl) return os.sep.join(path_list[:last_index]) Subzero: Change the echoing in shellcmd(). This makes it much easier to copy/paste the output. BUG= none R=jvoung@chromium.org Review URL: https://codereview.chromium.org/611983003
import os import subprocess import sys def shellcmd(command, echo=True): if not isinstance(command, str): command = ' '.join(command) if echo: print '[cmd]', command stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result def FindBaseNaCl(): """Find the base native_client/ directory.""" nacl = 'native_client' path_list = os.getcwd().split(os.sep) if nacl not in path_list: return None last_index = len(path_list) - path_list[::-1].index(nacl) return os.sep.join(path_list[:last_index])
<commit_before>import os import subprocess import sys def shellcmd(command, echo=True): if echo: print '[cmd]', command if not isinstance(command, str): command = ' '.join(command) stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result def FindBaseNaCl(): """Find the base native_client/ directory.""" nacl = 'native_client' path_list = os.getcwd().split(os.sep) if nacl not in path_list: return None last_index = len(path_list) - path_list[::-1].index(nacl) return os.sep.join(path_list[:last_index]) <commit_msg>Subzero: Change the echoing in shellcmd(). This makes it much easier to copy/paste the output. BUG= none R=jvoung@chromium.org Review URL: https://codereview.chromium.org/611983003<commit_after>
import os import subprocess import sys def shellcmd(command, echo=True): if not isinstance(command, str): command = ' '.join(command) if echo: print '[cmd]', command stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result def FindBaseNaCl(): """Find the base native_client/ directory.""" nacl = 'native_client' path_list = os.getcwd().split(os.sep) if nacl not in path_list: return None last_index = len(path_list) - path_list[::-1].index(nacl) return os.sep.join(path_list[:last_index])
import os import subprocess import sys def shellcmd(command, echo=True): if echo: print '[cmd]', command if not isinstance(command, str): command = ' '.join(command) stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result def FindBaseNaCl(): """Find the base native_client/ directory.""" nacl = 'native_client' path_list = os.getcwd().split(os.sep) if nacl not in path_list: return None last_index = len(path_list) - path_list[::-1].index(nacl) return os.sep.join(path_list[:last_index]) Subzero: Change the echoing in shellcmd(). This makes it much easier to copy/paste the output. BUG= none R=jvoung@chromium.org Review URL: https://codereview.chromium.org/611983003import os import subprocess import sys def shellcmd(command, echo=True): if not isinstance(command, str): command = ' '.join(command) if echo: print '[cmd]', command stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result def FindBaseNaCl(): """Find the base native_client/ directory.""" nacl = 'native_client' path_list = os.getcwd().split(os.sep) if nacl not in path_list: return None last_index = len(path_list) - path_list[::-1].index(nacl) return os.sep.join(path_list[:last_index])
<commit_before>import os import subprocess import sys def shellcmd(command, echo=True): if echo: print '[cmd]', command if not isinstance(command, str): command = ' '.join(command) stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result def FindBaseNaCl(): """Find the base native_client/ directory.""" nacl = 'native_client' path_list = os.getcwd().split(os.sep) if nacl not in path_list: return None last_index = len(path_list) - path_list[::-1].index(nacl) return os.sep.join(path_list[:last_index]) <commit_msg>Subzero: Change the echoing in shellcmd(). This makes it much easier to copy/paste the output. BUG= none R=jvoung@chromium.org Review URL: https://codereview.chromium.org/611983003<commit_after>import os import subprocess import sys def shellcmd(command, echo=True): if not isinstance(command, str): command = ' '.join(command) if echo: print '[cmd]', command stdout_result = subprocess.check_output(command, shell=True) if echo: sys.stdout.write(stdout_result) return stdout_result def FindBaseNaCl(): """Find the base native_client/ directory.""" nacl = 'native_client' path_list = os.getcwd().split(os.sep) if nacl not in path_list: return None last_index = len(path_list) - path_list[::-1].index(nacl) return os.sep.join(path_list[:last_index])
7aaef53e5547abfca8eb64ceb4ac477a14b79536
tensorflow_datasets/core/visualization/__init__.py
tensorflow_datasets/core/visualization/__init__.py
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Visualizer utils.""" from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer from tensorflow_datasets.core.visualization.show_examples import show_examples from tensorflow_datasets.core.visualization.show_examples import show_statistics from tensorflow_datasets.core.visualization.visualizer import Visualizer __all__ = [ "ImageGridVisualizer", "show_examples", "Visualizer", ]
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Visualizer utils.""" from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer from tensorflow_datasets.core.visualization.show_examples import show_examples from tensorflow_datasets.core.visualization.show_examples import show_statistics from tensorflow_datasets.core.visualization.visualizer import Visualizer __all__ = [ "ImageGridVisualizer", "show_examples", "show_statistics", "Visualizer", ]
Add show_statistics to public API
Add show_statistics to public API PiperOrigin-RevId: 322842576
Python
apache-2.0
tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Visualizer utils.""" from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer from tensorflow_datasets.core.visualization.show_examples import show_examples from tensorflow_datasets.core.visualization.show_examples import show_statistics from tensorflow_datasets.core.visualization.visualizer import Visualizer __all__ = [ "ImageGridVisualizer", "show_examples", "Visualizer", ] Add show_statistics to public API PiperOrigin-RevId: 322842576
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Visualizer utils.""" from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer from tensorflow_datasets.core.visualization.show_examples import show_examples from tensorflow_datasets.core.visualization.show_examples import show_statistics from tensorflow_datasets.core.visualization.visualizer import Visualizer __all__ = [ "ImageGridVisualizer", "show_examples", "show_statistics", "Visualizer", ]
<commit_before># coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Visualizer utils.""" from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer from tensorflow_datasets.core.visualization.show_examples import show_examples from tensorflow_datasets.core.visualization.show_examples import show_statistics from tensorflow_datasets.core.visualization.visualizer import Visualizer __all__ = [ "ImageGridVisualizer", "show_examples", "Visualizer", ] <commit_msg>Add show_statistics to public API PiperOrigin-RevId: 322842576<commit_after>
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Visualizer utils.""" from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer from tensorflow_datasets.core.visualization.show_examples import show_examples from tensorflow_datasets.core.visualization.show_examples import show_statistics from tensorflow_datasets.core.visualization.visualizer import Visualizer __all__ = [ "ImageGridVisualizer", "show_examples", "show_statistics", "Visualizer", ]
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Visualizer utils.""" from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer from tensorflow_datasets.core.visualization.show_examples import show_examples from tensorflow_datasets.core.visualization.show_examples import show_statistics from tensorflow_datasets.core.visualization.visualizer import Visualizer __all__ = [ "ImageGridVisualizer", "show_examples", "Visualizer", ] Add show_statistics to public API PiperOrigin-RevId: 322842576# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Visualizer utils.""" from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer from tensorflow_datasets.core.visualization.show_examples import show_examples from tensorflow_datasets.core.visualization.show_examples import show_statistics from tensorflow_datasets.core.visualization.visualizer import Visualizer __all__ = [ "ImageGridVisualizer", "show_examples", "show_statistics", "Visualizer", ]
<commit_before># coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Visualizer utils.""" from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer from tensorflow_datasets.core.visualization.show_examples import show_examples from tensorflow_datasets.core.visualization.show_examples import show_statistics from tensorflow_datasets.core.visualization.visualizer import Visualizer __all__ = [ "ImageGridVisualizer", "show_examples", "Visualizer", ] <commit_msg>Add show_statistics to public API PiperOrigin-RevId: 322842576<commit_after># coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Visualizer utils.""" from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer from tensorflow_datasets.core.visualization.show_examples import show_examples from tensorflow_datasets.core.visualization.show_examples import show_statistics from tensorflow_datasets.core.visualization.visualizer import Visualizer __all__ = [ "ImageGridVisualizer", "show_examples", "show_statistics", "Visualizer", ]
26074fbd65cc2a0d4a0ffd27a57132c0a81ac29c
opentreemap/opentreemap/urls.py
opentreemap/opentreemap/urls.py
from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() from treemap.views import index, settings urlpatterns = patterns( '', url(r'^', include('geocode.urls')), url(r'^admin/', include(admin.site.urls)), url(r'(?P<instance_id>\d+)/', include('treemap.urls')), url(r'(?P<instance_id>\d+)/eco/', include('ecobenefits.urls')), )
from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() from treemap.views import index, settings urlpatterns = patterns( '', url(r'^', include('geocode.urls')), url(r'(?P<instance_id>\d+)/', include('treemap.urls')), url(r'(?P<instance_id>\d+)/eco/', include('ecobenefits.urls')), ) if settings.DEBUG: urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)))
Disable the admin interface in production
Disable the admin interface in production
Python
agpl-3.0
RickMohr/otm-core,RickMohr/otm-core,recklessromeo/otm-core,clever-crow-consulting/otm-core,maurizi/otm-core,maurizi/otm-core,recklessromeo/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,RickMohr/otm-core,maurizi/otm-core,recklessromeo/otm-core,maurizi/otm-core
from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() from treemap.views import index, settings urlpatterns = patterns( '', url(r'^', include('geocode.urls')), url(r'^admin/', include(admin.site.urls)), url(r'(?P<instance_id>\d+)/', include('treemap.urls')), url(r'(?P<instance_id>\d+)/eco/', include('ecobenefits.urls')), ) Disable the admin interface in production
from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() from treemap.views import index, settings urlpatterns = patterns( '', url(r'^', include('geocode.urls')), url(r'(?P<instance_id>\d+)/', include('treemap.urls')), url(r'(?P<instance_id>\d+)/eco/', include('ecobenefits.urls')), ) if settings.DEBUG: urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)))
<commit_before>from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() from treemap.views import index, settings urlpatterns = patterns( '', url(r'^', include('geocode.urls')), url(r'^admin/', include(admin.site.urls)), url(r'(?P<instance_id>\d+)/', include('treemap.urls')), url(r'(?P<instance_id>\d+)/eco/', include('ecobenefits.urls')), ) <commit_msg>Disable the admin interface in production<commit_after>
from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() from treemap.views import index, settings urlpatterns = patterns( '', url(r'^', include('geocode.urls')), url(r'(?P<instance_id>\d+)/', include('treemap.urls')), url(r'(?P<instance_id>\d+)/eco/', include('ecobenefits.urls')), ) if settings.DEBUG: urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)))
from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() from treemap.views import index, settings urlpatterns = patterns( '', url(r'^', include('geocode.urls')), url(r'^admin/', include(admin.site.urls)), url(r'(?P<instance_id>\d+)/', include('treemap.urls')), url(r'(?P<instance_id>\d+)/eco/', include('ecobenefits.urls')), ) Disable the admin interface in productionfrom django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() from treemap.views import index, settings urlpatterns = patterns( '', url(r'^', include('geocode.urls')), url(r'(?P<instance_id>\d+)/', include('treemap.urls')), url(r'(?P<instance_id>\d+)/eco/', include('ecobenefits.urls')), ) if settings.DEBUG: urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)))
<commit_before>from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() from treemap.views import index, settings urlpatterns = patterns( '', url(r'^', include('geocode.urls')), url(r'^admin/', include(admin.site.urls)), url(r'(?P<instance_id>\d+)/', include('treemap.urls')), url(r'(?P<instance_id>\d+)/eco/', include('ecobenefits.urls')), ) <commit_msg>Disable the admin interface in production<commit_after>from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() from treemap.views import index, settings urlpatterns = patterns( '', url(r'^', include('geocode.urls')), url(r'(?P<instance_id>\d+)/', include('treemap.urls')), url(r'(?P<instance_id>\d+)/eco/', include('ecobenefits.urls')), ) if settings.DEBUG: urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)))
802beba31c832a045c38961ef4add2531193a6db
src/prefill.py
src/prefill.py
import pywikibot import sys import requests from app import get_proposed_edits, app def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: get_proposed_edits(p.title(), False, True) count += 1 except: print("ERROR: Something went wrong with this page!") if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(1000000, sys.argv[1]) else: prefill_cache(1000000)
import pywikibot import sys import requests from app import get_proposed_edits, app import threading from time import sleep def worker(title=None): try: get_proposed_edits(title, False, True) except: pass def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: threading.Thread(target=worker, args=[p.title()]).start() except: sleep(60) count += 1 sleep(0.1) if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(5000000, sys.argv[1]) else: prefill_cache(5000000)
Add multithreading with threading module, run until the end
Add multithreading with threading module, run until the end The template has over 3M usages, so 5M should be a safe number.
Python
mit
dissemin/oabot,dissemin/oabot,dissemin/oabot
import pywikibot import sys import requests from app import get_proposed_edits, app def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: get_proposed_edits(p.title(), False, True) count += 1 except: print("ERROR: Something went wrong with this page!") if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(1000000, sys.argv[1]) else: prefill_cache(1000000) Add multithreading with threading module, run until the end The template has over 3M usages, so 5M should be a safe number.
import pywikibot import sys import requests from app import get_proposed_edits, app import threading from time import sleep def worker(title=None): try: get_proposed_edits(title, False, True) except: pass def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: threading.Thread(target=worker, args=[p.title()]).start() except: sleep(60) count += 1 sleep(0.1) if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(5000000, sys.argv[1]) else: prefill_cache(5000000)
<commit_before>import pywikibot import sys import requests from app import get_proposed_edits, app def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: get_proposed_edits(p.title(), False, True) count += 1 except: print("ERROR: Something went wrong with this page!") if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(1000000, sys.argv[1]) else: prefill_cache(1000000) <commit_msg>Add multithreading with threading module, run until the end The template has over 3M usages, so 5M should be a safe number.<commit_after>
import pywikibot import sys import requests from app import get_proposed_edits, app import threading from time import sleep def worker(title=None): try: get_proposed_edits(title, False, True) except: pass def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: threading.Thread(target=worker, args=[p.title()]).start() except: sleep(60) count += 1 sleep(0.1) if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(5000000, sys.argv[1]) else: prefill_cache(5000000)
import pywikibot import sys import requests from app import get_proposed_edits, app def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: get_proposed_edits(p.title(), False, True) count += 1 except: print("ERROR: Something went wrong with this page!") if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(1000000, sys.argv[1]) else: prefill_cache(1000000) Add multithreading with threading module, run until the end The template has over 3M usages, so 5M should be a safe number.import pywikibot import sys import requests from app import get_proposed_edits, app import threading from time import sleep def worker(title=None): try: get_proposed_edits(title, False, True) except: pass def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: threading.Thread(target=worker, args=[p.title()]).start() except: sleep(60) count += 1 sleep(0.1) if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(5000000, sys.argv[1]) else: prefill_cache(5000000)
<commit_before>import pywikibot import sys import requests from app import get_proposed_edits, app def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: get_proposed_edits(p.title(), False, True) count += 1 except: print("ERROR: Something went wrong with this page!") if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(1000000, sys.argv[1]) else: prefill_cache(1000000) <commit_msg>Add multithreading with threading module, run until the end The template has over 3M usages, so 5M should be a safe number.<commit_after>import pywikibot import sys import requests from app import get_proposed_edits, app import threading from time import sleep def worker(title=None): try: get_proposed_edits(title, False, True) except: pass def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: threading.Thread(target=worker, args=[p.title()]).start() except: sleep(60) count += 1 sleep(0.1) if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(5000000, sys.argv[1]) else: prefill_cache(5000000)
c537f40c4c56dc8a52e284bd9c03d09d191e77eb
tests/test_dungeon.py
tests/test_dungeon.py
from game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_dungeon_handle_input_valid(dungeon): dungeon.handle_input('f')
from game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_deck_order(dungeon): """this check ensures that we can plan for the first three rooms having known cards and thus we can check the availability of certain actions or sequences of actions""" cards = dungeon.deck.draw(12) assert str(cards[0]) == "17 of Clubs" assert str(cards[1]) == "11 of Diamonds" assert str(cards[2]) == "8 of Diamonds" assert str(cards[3]) == "7 of Spades" assert str(cards[4]) == "5 of Clubs" assert str(cards[5]) == "11 of Spades" assert str(cards[6]) == "17 of Spades" assert str(cards[7]) == "11 of Diamonds" assert str(cards[8]) == "9 of Spades" assert str(cards[9]) == "Joker" assert str(cards[10]) == "6 of Spades" assert str(cards[11]) == "2 of Diamonds" def test_dungeon_valid_flee_unconditioned(dungeon): dungeon.handle_input('f') assert len(dungeon.room_history) == 2 def test_cannot_flee_twice(dungeon): assert dungeon.room_history[-1].escapable() == True dungeon.handle_input('f') assert dungeon.player.escaped_last_room == True assert dungeon.room_history[-1].escapable() == False dungeon.handle_input('f') assert len(dungeon.room_history) == 2
Add tests for Dungeon class
Add tests for Dungeon class
Python
mit
setphen/Donsol
from game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_dungeon_handle_input_valid(dungeon): dungeon.handle_input('f') Add tests for Dungeon class
from game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_deck_order(dungeon): """this check ensures that we can plan for the first three rooms having known cards and thus we can check the availability of certain actions or sequences of actions""" cards = dungeon.deck.draw(12) assert str(cards[0]) == "17 of Clubs" assert str(cards[1]) == "11 of Diamonds" assert str(cards[2]) == "8 of Diamonds" assert str(cards[3]) == "7 of Spades" assert str(cards[4]) == "5 of Clubs" assert str(cards[5]) == "11 of Spades" assert str(cards[6]) == "17 of Spades" assert str(cards[7]) == "11 of Diamonds" assert str(cards[8]) == "9 of Spades" assert str(cards[9]) == "Joker" assert str(cards[10]) == "6 of Spades" assert str(cards[11]) == "2 of Diamonds" def test_dungeon_valid_flee_unconditioned(dungeon): dungeon.handle_input('f') assert len(dungeon.room_history) == 2 def test_cannot_flee_twice(dungeon): assert dungeon.room_history[-1].escapable() == True dungeon.handle_input('f') assert dungeon.player.escaped_last_room == True assert dungeon.room_history[-1].escapable() == False dungeon.handle_input('f') assert len(dungeon.room_history) == 2
<commit_before>from game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_dungeon_handle_input_valid(dungeon): dungeon.handle_input('f') <commit_msg>Add tests for Dungeon class<commit_after>
from game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_deck_order(dungeon): """this check ensures that we can plan for the first three rooms having known cards and thus we can check the availability of certain actions or sequences of actions""" cards = dungeon.deck.draw(12) assert str(cards[0]) == "17 of Clubs" assert str(cards[1]) == "11 of Diamonds" assert str(cards[2]) == "8 of Diamonds" assert str(cards[3]) == "7 of Spades" assert str(cards[4]) == "5 of Clubs" assert str(cards[5]) == "11 of Spades" assert str(cards[6]) == "17 of Spades" assert str(cards[7]) == "11 of Diamonds" assert str(cards[8]) == "9 of Spades" assert str(cards[9]) == "Joker" assert str(cards[10]) == "6 of Spades" assert str(cards[11]) == "2 of Diamonds" def test_dungeon_valid_flee_unconditioned(dungeon): dungeon.handle_input('f') assert len(dungeon.room_history) == 2 def test_cannot_flee_twice(dungeon): assert dungeon.room_history[-1].escapable() == True dungeon.handle_input('f') assert dungeon.player.escaped_last_room == True assert dungeon.room_history[-1].escapable() == False dungeon.handle_input('f') assert len(dungeon.room_history) == 2
from game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_dungeon_handle_input_valid(dungeon): dungeon.handle_input('f') Add tests for Dungeon classfrom game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_deck_order(dungeon): """this check ensures that we can plan for the first three rooms having known cards and thus we can check the availability of certain actions or sequences of actions""" cards = dungeon.deck.draw(12) assert str(cards[0]) == "17 of Clubs" assert str(cards[1]) == "11 of Diamonds" assert str(cards[2]) == "8 of Diamonds" assert str(cards[3]) == "7 of Spades" assert str(cards[4]) == "5 of Clubs" assert str(cards[5]) == "11 of Spades" assert str(cards[6]) == "17 of Spades" assert str(cards[7]) == "11 of Diamonds" assert str(cards[8]) == "9 of Spades" assert str(cards[9]) == "Joker" assert str(cards[10]) == "6 of Spades" assert str(cards[11]) == "2 of Diamonds" def test_dungeon_valid_flee_unconditioned(dungeon): dungeon.handle_input('f') assert len(dungeon.room_history) == 2 def test_cannot_flee_twice(dungeon): assert dungeon.room_history[-1].escapable() == True dungeon.handle_input('f') assert dungeon.player.escaped_last_room == True assert dungeon.room_history[-1].escapable() == False dungeon.handle_input('f') assert len(dungeon.room_history) == 2
<commit_before>from game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_dungeon_handle_input_valid(dungeon): dungeon.handle_input('f') <commit_msg>Add tests for Dungeon class<commit_after>from game.models import (Dungeon, Deck, Player, make_standard_deck) import pytest @pytest.fixture def dungeon(): return Dungeon(make_standard_deck(), seed=123456789) def test_deck_order(dungeon): """this check ensures that we can plan for the first three rooms having known cards and thus we can check the availability of certain actions or sequences of actions""" cards = dungeon.deck.draw(12) assert str(cards[0]) == "17 of Clubs" assert str(cards[1]) == "11 of Diamonds" assert str(cards[2]) == "8 of Diamonds" assert str(cards[3]) == "7 of Spades" assert str(cards[4]) == "5 of Clubs" assert str(cards[5]) == "11 of Spades" assert str(cards[6]) == "17 of Spades" assert str(cards[7]) == "11 of Diamonds" assert str(cards[8]) == "9 of Spades" assert str(cards[9]) == "Joker" assert str(cards[10]) == "6 of Spades" assert str(cards[11]) == "2 of Diamonds" def test_dungeon_valid_flee_unconditioned(dungeon): dungeon.handle_input('f') assert len(dungeon.room_history) == 2 def test_cannot_flee_twice(dungeon): assert dungeon.room_history[-1].escapable() == True dungeon.handle_input('f') assert dungeon.player.escaped_last_room == True assert dungeon.room_history[-1].escapable() == False dungeon.handle_input('f') assert len(dungeon.room_history) == 2
2dac0f9825b58c5c9af9958d6f0cb0337649cf76
wsgi_general.py
wsgi_general.py
import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' return
import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets and not (len(path) >= 3 and path[-3] == "Docs"): start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' return
Add routing exception for docs
Add routing exception for docs
Python
agpl-3.0
cggh/DQXServer
import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' returnAdd routing exception for docs
import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets and not (len(path) >= 3 and path[-3] == "Docs"): start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' return
<commit_before>import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' return<commit_msg>Add routing exception for docs<commit_after>
import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets and not (len(path) >= 3 and path[-3] == "Docs"): start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' return
import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' returnAdd routing exception for docsimport DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets and not (len(path) >= 3 and path[-3] == "Docs"): start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' return
<commit_before>import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' return<commit_msg>Add routing exception for docs<commit_after>import DQXUtils import DQXDbTools def application(environ, start_response): #For the root we do a relative redirect to index.html, hoping the app has one if environ['PATH_INFO'] == '/': start_response('301 Moved Permanently', [('Location', 'index.html'),]) return with DQXDbTools.DBCursor() as cur: cur.execute('select id from datasetindex') datasets = [d[0] for d in cur.fetchall()] #Redirect to specific dataset path = environ['PATH_INFO'].split('/') if len(path) >= 2 and path[-2] in datasets and not (len(path) >= 3 and path[-3] == "Docs"): start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-2]),]) return if path[-1] in datasets: start_response('301 Moved Permanently', [('Location', '../index.html?dataset='+path[-1]),]) return #Everything else is 404 DQXUtils.LogServer('404:' + environ['PATH_INFO']) start_response('404 Not Found', []) try: with open('static/404.html') as page: yield page.read() except IOError: yield '404 Page Not Found' return
c008171b93371c72a2f2a2698f514d267e312837
tests/testapp/urls.py
tests/testapp/urls.py
from django.conf.urls import url from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ url(r"^admin/", admin.site.urls), url(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), url(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="page_detail"), ]
from django.urls import re_path from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ re_path(r"^admin/", admin.site.urls), re_path(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), re_path(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="page_detail"), ]
Switch from url() to re_path()
Switch from url() to re_path()
Python
bsd-3-clause
matthiask/django-content-editor,matthiask/feincms2-content,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/django-content-editor
from django.conf.urls import url from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ url(r"^admin/", admin.site.urls), url(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), url(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="page_detail"), ] Switch from url() to re_path()
from django.urls import re_path from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ re_path(r"^admin/", admin.site.urls), re_path(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), re_path(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="page_detail"), ]
<commit_before>from django.conf.urls import url from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ url(r"^admin/", admin.site.urls), url(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), url(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="page_detail"), ] <commit_msg>Switch from url() to re_path()<commit_after>
from django.urls import re_path from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ re_path(r"^admin/", admin.site.urls), re_path(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), re_path(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="page_detail"), ]
from django.conf.urls import url from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ url(r"^admin/", admin.site.urls), url(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), url(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="page_detail"), ] Switch from url() to re_path()from django.urls import re_path from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ re_path(r"^admin/", admin.site.urls), re_path(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), re_path(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="page_detail"), ]
<commit_before>from django.conf.urls import url from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ url(r"^admin/", admin.site.urls), url(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), url(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="page_detail"), ] <commit_msg>Switch from url() to re_path()<commit_after>from django.urls import re_path from django.contrib import admin from .views import ArticleView, PageView urlpatterns = [ re_path(r"^admin/", admin.site.urls), re_path(r"^articles/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_detail"), re_path(r"^pages/(?P<pk>\d+)/$", PageView.as_view(), name="page_detail"), ]
eb0362c489f63d94d082ee4700dfdc871f68f916
tests/dal/await_syntax.py
tests/dal/await_syntax.py
from umongo import Document # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db.doc async def test_cursor(cursor): await cursor.count() await cursor.to_list(length=10) cursor.rewind() await cursor.fetch_next _ = cursor.next_object() doc = Doc() await doc.commit() cursor = Doc.find() await test_cursor(cursor) cursor = doc.find() await test_cursor(cursor) await Doc.find_one() await doc.find_one() await Doc.ensure_indexes() await doc.ensure_indexes() await doc.reload() await doc.remove()
from umongo import Document from umongo.dal.motor_asyncio import MotorAsyncIOReference # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db.doc async def test_cursor(cursor): await cursor.count() await cursor.to_list(length=10) cursor.rewind() await cursor.fetch_next _ = cursor.next_object() doc = Doc() await doc.commit() assert doc == await MotorAsyncIOReference(Doc, doc.id).fetch() cursor = Doc.find() await test_cursor(cursor) cursor = doc.find() await test_cursor(cursor) await Doc.find_one() await doc.find_one() await Doc.ensure_indexes() await doc.ensure_indexes() await doc.reload() await doc.remove()
Add test for MotorAsyncIOReference await support
Add test for MotorAsyncIOReference await support
Python
mit
Scille/umongo
from umongo import Document # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db.doc async def test_cursor(cursor): await cursor.count() await cursor.to_list(length=10) cursor.rewind() await cursor.fetch_next _ = cursor.next_object() doc = Doc() await doc.commit() cursor = Doc.find() await test_cursor(cursor) cursor = doc.find() await test_cursor(cursor) await Doc.find_one() await doc.find_one() await Doc.ensure_indexes() await doc.ensure_indexes() await doc.reload() await doc.remove() Add test for MotorAsyncIOReference await support
from umongo import Document from umongo.dal.motor_asyncio import MotorAsyncIOReference # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db.doc async def test_cursor(cursor): await cursor.count() await cursor.to_list(length=10) cursor.rewind() await cursor.fetch_next _ = cursor.next_object() doc = Doc() await doc.commit() assert doc == await MotorAsyncIOReference(Doc, doc.id).fetch() cursor = Doc.find() await test_cursor(cursor) cursor = doc.find() await test_cursor(cursor) await Doc.find_one() await doc.find_one() await Doc.ensure_indexes() await doc.ensure_indexes() await doc.reload() await doc.remove()
<commit_before>from umongo import Document # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db.doc async def test_cursor(cursor): await cursor.count() await cursor.to_list(length=10) cursor.rewind() await cursor.fetch_next _ = cursor.next_object() doc = Doc() await doc.commit() cursor = Doc.find() await test_cursor(cursor) cursor = doc.find() await test_cursor(cursor) await Doc.find_one() await doc.find_one() await Doc.ensure_indexes() await doc.ensure_indexes() await doc.reload() await doc.remove() <commit_msg>Add test for MotorAsyncIOReference await support<commit_after>
from umongo import Document from umongo.dal.motor_asyncio import MotorAsyncIOReference # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db.doc async def test_cursor(cursor): await cursor.count() await cursor.to_list(length=10) cursor.rewind() await cursor.fetch_next _ = cursor.next_object() doc = Doc() await doc.commit() assert doc == await MotorAsyncIOReference(Doc, doc.id).fetch() cursor = Doc.find() await test_cursor(cursor) cursor = doc.find() await test_cursor(cursor) await Doc.find_one() await doc.find_one() await Doc.ensure_indexes() await doc.ensure_indexes() await doc.reload() await doc.remove()
from umongo import Document # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db.doc async def test_cursor(cursor): await cursor.count() await cursor.to_list(length=10) cursor.rewind() await cursor.fetch_next _ = cursor.next_object() doc = Doc() await doc.commit() cursor = Doc.find() await test_cursor(cursor) cursor = doc.find() await test_cursor(cursor) await Doc.find_one() await doc.find_one() await Doc.ensure_indexes() await doc.ensure_indexes() await doc.reload() await doc.remove() Add test for MotorAsyncIOReference await supportfrom umongo import Document from umongo.dal.motor_asyncio import MotorAsyncIOReference # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db.doc async def test_cursor(cursor): await cursor.count() await cursor.to_list(length=10) cursor.rewind() await cursor.fetch_next _ = cursor.next_object() doc = Doc() await doc.commit() assert doc == await MotorAsyncIOReference(Doc, doc.id).fetch() cursor = Doc.find() await test_cursor(cursor) cursor = doc.find() await test_cursor(cursor) await Doc.find_one() await doc.find_one() await Doc.ensure_indexes() await doc.ensure_indexes() await doc.reload() await doc.remove()
<commit_before>from umongo import Document # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db.doc async def test_cursor(cursor): await cursor.count() await cursor.to_list(length=10) cursor.rewind() await cursor.fetch_next _ = cursor.next_object() doc = Doc() await doc.commit() cursor = Doc.find() await test_cursor(cursor) cursor = doc.find() await test_cursor(cursor) await Doc.find_one() await doc.find_one() await Doc.ensure_indexes() await doc.ensure_indexes() await doc.reload() await doc.remove() <commit_msg>Add test for MotorAsyncIOReference await support<commit_after>from umongo import Document from umongo.dal.motor_asyncio import MotorAsyncIOReference # Await syntax related tests are stored in a separate file in order to # catch a SyntaxError when Python doesn't support it async def test_await_syntax(db): class Doc(Document): class Meta: collection = db.doc async def test_cursor(cursor): await cursor.count() await cursor.to_list(length=10) cursor.rewind() await cursor.fetch_next _ = cursor.next_object() doc = Doc() await doc.commit() assert doc == await MotorAsyncIOReference(Doc, doc.id).fetch() cursor = Doc.find() await test_cursor(cursor) cursor = doc.find() await test_cursor(cursor) await Doc.find_one() await doc.find_one() await Doc.ensure_indexes() await doc.ensure_indexes() await doc.reload() await doc.remove()
cd792dd6ab60b1976225c01d5071a925f0f185b7
tests/test_linestyles2.py
tests/test_linestyles2.py
#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName = "linestyles2.png" def constructImage(self): plot = Plot() for i in xrange(6): line = Line() line.xValues = xrange(5) line.yValues = [(i+1) * x for x in line.xValues] line.label = "Line %d" % (i + 1) plot.add(line) plot.addLineColor("red") plot.addLineColor("blue") plot.addLineColor("green") plot.addMarker('') plot.addMarker('x') plot.hasLegend(columns=2) plot.save(self.imageName) ImageComparisonTestCase.register(LineStyles2Test) if __name__ == "__main__": test = LineStyles2Test() test.constructImage()
#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName = "linestyles2.png" def constructImage(self): plot = Plot() for i in xrange(6): line = Line() line.xValues = xrange(5) line.yValues = [(i+1) * x for x in line.xValues] line.label = "Line %d" % (i + 1) plot.add(line) plot.addLineColor("red") plot.addLineColor("blue") plot.addLineColor("green") plot.addMarker('') plot.addMarker('x') plot.hasLegend(columns=2) plot.save(self.imageName) ImageComparisonTestCase.register(LineStyles2Test) if __name__ == "__main__": test = LineStyles2Test("testImageComparison") test.constructImage()
Make linestyles2 test runnable (should probably fix this for other tests)
Make linestyles2 test runnable (should probably fix this for other tests)
Python
bsd-3-clause
alexras/boomslang
#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName = "linestyles2.png" def constructImage(self): plot = Plot() for i in xrange(6): line = Line() line.xValues = xrange(5) line.yValues = [(i+1) * x for x in line.xValues] line.label = "Line %d" % (i + 1) plot.add(line) plot.addLineColor("red") plot.addLineColor("blue") plot.addLineColor("green") plot.addMarker('') plot.addMarker('x') plot.hasLegend(columns=2) plot.save(self.imageName) ImageComparisonTestCase.register(LineStyles2Test) if __name__ == "__main__": test = LineStyles2Test() test.constructImage() Make linestyles2 test runnable (should probably fix this for other tests)
#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName = "linestyles2.png" def constructImage(self): plot = Plot() for i in xrange(6): line = Line() line.xValues = xrange(5) line.yValues = [(i+1) * x for x in line.xValues] line.label = "Line %d" % (i + 1) plot.add(line) plot.addLineColor("red") plot.addLineColor("blue") plot.addLineColor("green") plot.addMarker('') plot.addMarker('x') plot.hasLegend(columns=2) plot.save(self.imageName) ImageComparisonTestCase.register(LineStyles2Test) if __name__ == "__main__": test = LineStyles2Test("testImageComparison") test.constructImage()
<commit_before>#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName = "linestyles2.png" def constructImage(self): plot = Plot() for i in xrange(6): line = Line() line.xValues = xrange(5) line.yValues = [(i+1) * x for x in line.xValues] line.label = "Line %d" % (i + 1) plot.add(line) plot.addLineColor("red") plot.addLineColor("blue") plot.addLineColor("green") plot.addMarker('') plot.addMarker('x') plot.hasLegend(columns=2) plot.save(self.imageName) ImageComparisonTestCase.register(LineStyles2Test) if __name__ == "__main__": test = LineStyles2Test() test.constructImage() <commit_msg>Make linestyles2 test runnable (should probably fix this for other tests)<commit_after>
#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName = "linestyles2.png" def constructImage(self): plot = Plot() for i in xrange(6): line = Line() line.xValues = xrange(5) line.yValues = [(i+1) * x for x in line.xValues] line.label = "Line %d" % (i + 1) plot.add(line) plot.addLineColor("red") plot.addLineColor("blue") plot.addLineColor("green") plot.addMarker('') plot.addMarker('x') plot.hasLegend(columns=2) plot.save(self.imageName) ImageComparisonTestCase.register(LineStyles2Test) if __name__ == "__main__": test = LineStyles2Test("testImageComparison") test.constructImage()
#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName = "linestyles2.png" def constructImage(self): plot = Plot() for i in xrange(6): line = Line() line.xValues = xrange(5) line.yValues = [(i+1) * x for x in line.xValues] line.label = "Line %d" % (i + 1) plot.add(line) plot.addLineColor("red") plot.addLineColor("blue") plot.addLineColor("green") plot.addMarker('') plot.addMarker('x') plot.hasLegend(columns=2) plot.save(self.imageName) ImageComparisonTestCase.register(LineStyles2Test) if __name__ == "__main__": test = LineStyles2Test() test.constructImage() Make linestyles2 test runnable (should probably fix this for other tests)#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName = "linestyles2.png" def constructImage(self): plot = Plot() for i in xrange(6): line = Line() line.xValues = xrange(5) line.yValues = [(i+1) * x for x in line.xValues] line.label = "Line %d" % (i + 1) plot.add(line) plot.addLineColor("red") plot.addLineColor("blue") plot.addLineColor("green") plot.addMarker('') plot.addMarker('x') plot.hasLegend(columns=2) plot.save(self.imageName) ImageComparisonTestCase.register(LineStyles2Test) if __name__ == "__main__": test = LineStyles2Test("testImageComparison") test.constructImage()
<commit_before>#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName = "linestyles2.png" def constructImage(self): plot = Plot() for i in xrange(6): line = Line() line.xValues = xrange(5) line.yValues = [(i+1) * x for x in line.xValues] line.label = "Line %d" % (i + 1) plot.add(line) plot.addLineColor("red") plot.addLineColor("blue") plot.addLineColor("green") plot.addMarker('') plot.addMarker('x') plot.hasLegend(columns=2) plot.save(self.imageName) ImageComparisonTestCase.register(LineStyles2Test) if __name__ == "__main__": test = LineStyles2Test() test.constructImage() <commit_msg>Make linestyles2 test runnable (should probably fix this for other tests)<commit_after>#!/usr/bin/env python from boomslang import Line, Plot from ImageComparisonTestCase import ImageComparisonTestCase import unittest class LineStyles2Test(ImageComparisonTestCase, unittest.TestCase): def __init__(self, testCaseName): super(LineStyles2Test, self).__init__(testCaseName) self.imageName = "linestyles2.png" def constructImage(self): plot = Plot() for i in xrange(6): line = Line() line.xValues = xrange(5) line.yValues = [(i+1) * x for x in line.xValues] line.label = "Line %d" % (i + 1) plot.add(line) plot.addLineColor("red") plot.addLineColor("blue") plot.addLineColor("green") plot.addMarker('') plot.addMarker('x') plot.hasLegend(columns=2) plot.save(self.imageName) ImageComparisonTestCase.register(LineStyles2Test) if __name__ == "__main__": test = LineStyles2Test("testImageComparison") test.constructImage()
fb08d35b8470cb659e9a9f80d58d15c18faeaf9c
testinfra/backend/base.py
testinfra/backend/base.py
# -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # 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 __future__ import unicode_literals import collections import pipes CommandResult = collections.namedtuple('CommandResult', [ 'rc', 'stdout', 'stderr', 'command', ]) class BaseBackend(object): def quote(self, command, *args): return command % tuple(pipes.quote(a) for a in args) @staticmethod def parse_hostspec(hostspec): host = hostspec user = None port = None if "@" in host: user, host = host.split("@", 1) if ":" in host: host, port = host.split(":", 1) return host, user, port def run(self, command, *args): raise NotImplementedError
# -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # 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 __future__ import unicode_literals import collections import pipes CommandResult = collections.namedtuple('CommandResult', [ 'rc', 'stdout', 'stderr', 'command', ]) class BaseBackend(object): def quote(self, command, *args): if args: return command % tuple(pipes.quote(a) for a in args) else: return command @staticmethod def parse_hostspec(hostspec): host = hostspec user = None port = None if "@" in host: user, host = host.split("@", 1) if ":" in host: host, port = host.split(":", 1) return host, user, port def run(self, command, *args): raise NotImplementedError
Fix safe_ssh command without arguments
backend: Fix safe_ssh command without arguments
Python
apache-2.0
philpep/testinfra,Leibniz137/testinfra
# -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # 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 __future__ import unicode_literals import collections import pipes CommandResult = collections.namedtuple('CommandResult', [ 'rc', 'stdout', 'stderr', 'command', ]) class BaseBackend(object): def quote(self, command, *args): return command % tuple(pipes.quote(a) for a in args) @staticmethod def parse_hostspec(hostspec): host = hostspec user = None port = None if "@" in host: user, host = host.split("@", 1) if ":" in host: host, port = host.split(":", 1) return host, user, port def run(self, command, *args): raise NotImplementedError backend: Fix safe_ssh command without arguments
# -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # 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 __future__ import unicode_literals import collections import pipes CommandResult = collections.namedtuple('CommandResult', [ 'rc', 'stdout', 'stderr', 'command', ]) class BaseBackend(object): def quote(self, command, *args): if args: return command % tuple(pipes.quote(a) for a in args) else: return command @staticmethod def parse_hostspec(hostspec): host = hostspec user = None port = None if "@" in host: user, host = host.split("@", 1) if ":" in host: host, port = host.split(":", 1) return host, user, port def run(self, command, *args): raise NotImplementedError
<commit_before># -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # 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 __future__ import unicode_literals import collections import pipes CommandResult = collections.namedtuple('CommandResult', [ 'rc', 'stdout', 'stderr', 'command', ]) class BaseBackend(object): def quote(self, command, *args): return command % tuple(pipes.quote(a) for a in args) @staticmethod def parse_hostspec(hostspec): host = hostspec user = None port = None if "@" in host: user, host = host.split("@", 1) if ":" in host: host, port = host.split(":", 1) return host, user, port def run(self, command, *args): raise NotImplementedError <commit_msg>backend: Fix safe_ssh command without arguments<commit_after>
# -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # 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 __future__ import unicode_literals import collections import pipes CommandResult = collections.namedtuple('CommandResult', [ 'rc', 'stdout', 'stderr', 'command', ]) class BaseBackend(object): def quote(self, command, *args): if args: return command % tuple(pipes.quote(a) for a in args) else: return command @staticmethod def parse_hostspec(hostspec): host = hostspec user = None port = None if "@" in host: user, host = host.split("@", 1) if ":" in host: host, port = host.split(":", 1) return host, user, port def run(self, command, *args): raise NotImplementedError
# -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # 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 __future__ import unicode_literals import collections import pipes CommandResult = collections.namedtuple('CommandResult', [ 'rc', 'stdout', 'stderr', 'command', ]) class BaseBackend(object): def quote(self, command, *args): return command % tuple(pipes.quote(a) for a in args) @staticmethod def parse_hostspec(hostspec): host = hostspec user = None port = None if "@" in host: user, host = host.split("@", 1) if ":" in host: host, port = host.split(":", 1) return host, user, port def run(self, command, *args): raise NotImplementedError backend: Fix safe_ssh command without arguments# -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # 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 __future__ import unicode_literals import collections import pipes CommandResult = collections.namedtuple('CommandResult', [ 'rc', 'stdout', 'stderr', 'command', ]) class BaseBackend(object): def quote(self, command, *args): if args: return command % tuple(pipes.quote(a) for a in args) else: return command @staticmethod def parse_hostspec(hostspec): host = hostspec user = None port = None if "@" in host: user, host = host.split("@", 1) if ":" in host: host, port = host.split(":", 1) return host, user, port def run(self, command, *args): raise NotImplementedError
<commit_before># -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # 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 __future__ import unicode_literals import collections import pipes CommandResult = collections.namedtuple('CommandResult', [ 'rc', 'stdout', 'stderr', 'command', ]) class BaseBackend(object): def quote(self, command, *args): return command % tuple(pipes.quote(a) for a in args) @staticmethod def parse_hostspec(hostspec): host = hostspec user = None port = None if "@" in host: user, host = host.split("@", 1) if ":" in host: host, port = host.split(":", 1) return host, user, port def run(self, command, *args): raise NotImplementedError <commit_msg>backend: Fix safe_ssh command without arguments<commit_after># -*- coding: utf8 -*- # Copyright © 2015 Philippe Pepiot # # 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 __future__ import unicode_literals import collections import pipes CommandResult = collections.namedtuple('CommandResult', [ 'rc', 'stdout', 'stderr', 'command', ]) class BaseBackend(object): def quote(self, command, *args): if args: return command % tuple(pipes.quote(a) for a in args) else: return command @staticmethod def parse_hostspec(hostspec): host = hostspec user = None port = None if "@" in host: user, host = host.split("@", 1) if ":" in host: host, port = host.split(":", 1) return host, user, port def run(self, command, *args): raise NotImplementedError
2f0a12dd4c0c9e344bee6f478c5de99511e77c1a
datastreams/dictstreams.py
datastreams/dictstreams.py
from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(left.items()) joined.update(right.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins
from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(right.items()) joined.update(left.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins
Fix DictStream join precedence (right was overriding left improperly)
Fix DictStream join precedence (right was overriding left improperly)
Python
mit
StuartAxelOwen/datastreams
from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(left.items()) joined.update(right.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins Fix DictStream join precedence (right was overriding left improperly)
from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(right.items()) joined.update(left.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins
<commit_before>from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(left.items()) joined.update(right.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins <commit_msg>Fix DictStream join precedence (right was overriding left improperly)<commit_after>
from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(right.items()) joined.update(left.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins
from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(left.items()) joined.update(right.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins Fix DictStream join precedence (right was overriding left improperly)from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(right.items()) joined.update(left.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins
<commit_before>from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(left.items()) joined.update(right.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins <commit_msg>Fix DictStream join precedence (right was overriding left improperly)<commit_after>from datastreams import DataStream, DataSet class DictStream(DataStream): @staticmethod def Stream(iterable, transform=lambda row: row, predicate=lambda row: True): return DictStream(iterable, transform=transform, predicate=predicate) @staticmethod def Set(iterable): return DictSet(iterable) @staticmethod def getattr(row, name): return row.get(name) @staticmethod def hasattr(row, name): return name in row @staticmethod def setattr(row, name, value): row[name] = value def delete(self, key): transform = lambda row: dict((k, v) for k, v in row.items() if k != key) return self.Stream(self, transform=transform) @staticmethod def join_objects(left, right): joined = {} joined.update(right.items()) joined.update(left.items()) joined['left'] = left joined['right'] = right return joined class DictSet(DictStream, DataSet): pass # TODO implement dict inner/outer joins
273999eeedee551a4490c89928650fbfebeb4a22
tests/_test.py
tests/_test.py
import unittest class TestCase(unittest.TestCase): pass
import random import unittest import autograd.numpy as anp import numpy as np import tensorflow as tf import torch class TestCase(unittest.TestCase): @classmethod def testSetUp(cls): seed = 42 random.seed(seed) anp.random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) tf.random.set_seed(seed)
Fix random seed in unit tests
Fix random seed in unit tests Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com>
Python
bsd-3-clause
pymanopt/pymanopt,pymanopt/pymanopt
import unittest class TestCase(unittest.TestCase): pass Fix random seed in unit tests Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com>
import random import unittest import autograd.numpy as anp import numpy as np import tensorflow as tf import torch class TestCase(unittest.TestCase): @classmethod def testSetUp(cls): seed = 42 random.seed(seed) anp.random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) tf.random.set_seed(seed)
<commit_before>import unittest class TestCase(unittest.TestCase): pass <commit_msg>Fix random seed in unit tests Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com><commit_after>
import random import unittest import autograd.numpy as anp import numpy as np import tensorflow as tf import torch class TestCase(unittest.TestCase): @classmethod def testSetUp(cls): seed = 42 random.seed(seed) anp.random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) tf.random.set_seed(seed)
import unittest class TestCase(unittest.TestCase): pass Fix random seed in unit tests Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com>import random import unittest import autograd.numpy as anp import numpy as np import tensorflow as tf import torch class TestCase(unittest.TestCase): @classmethod def testSetUp(cls): seed = 42 random.seed(seed) anp.random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) tf.random.set_seed(seed)
<commit_before>import unittest class TestCase(unittest.TestCase): pass <commit_msg>Fix random seed in unit tests Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com><commit_after>import random import unittest import autograd.numpy as anp import numpy as np import tensorflow as tf import torch class TestCase(unittest.TestCase): @classmethod def testSetUp(cls): seed = 42 random.seed(seed) anp.random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) tf.random.set_seed(seed)
4392a87f9ebb5c6d2c2623089b3216837d6efb6b
test/418-wof-l10n_name.py
test/418-wof-l10n_name.py
# Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:ko': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0\xeb\x93\x9c' })
# Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:kor': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0\xeb\x93\x9c' }) # San Francisco (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/826/41/85882641.geojson assert_has_feature( 16, 14893, 29234, 'places', { 'id': 85882641, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'San Francisco', 'name:spa': type(None) }) # San Francisco (osm city) # https://whosonfirst.mapzen.com/data/858/826/41/85882641.geojson assert_has_feature( 16, 10482, 25330, 'places', { 'id': 26819236, 'kind': 'city', 'source': "openstreetmap.org", 'name': 'San Francisco', 'name:zho': '\xe8\x88\x8a\xe9\x87\x91\xe5\xb1\xb1\xe5\xb8\x82\xe8\x88\x87\xe7\xb8\xa3' })
Update tests for new l10n behavior
Update tests for new l10n behavior
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
# Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:ko': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0\xeb\x93\x9c' }) Update tests for new l10n behavior
# Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:kor': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0\xeb\x93\x9c' }) # San Francisco (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/826/41/85882641.geojson assert_has_feature( 16, 14893, 29234, 'places', { 'id': 85882641, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'San Francisco', 'name:spa': type(None) }) # San Francisco (osm city) # https://whosonfirst.mapzen.com/data/858/826/41/85882641.geojson assert_has_feature( 16, 10482, 25330, 'places', { 'id': 26819236, 'kind': 'city', 'source': "openstreetmap.org", 'name': 'San Francisco', 'name:zho': '\xe8\x88\x8a\xe9\x87\x91\xe5\xb1\xb1\xe5\xb8\x82\xe8\x88\x87\xe7\xb8\xa3' })
<commit_before># Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:ko': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0\xeb\x93\x9c' }) <commit_msg>Update tests for new l10n behavior<commit_after>
# Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:kor': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0\xeb\x93\x9c' }) # San Francisco (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/826/41/85882641.geojson assert_has_feature( 16, 14893, 29234, 'places', { 'id': 85882641, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'San Francisco', 'name:spa': type(None) }) # San Francisco (osm city) # https://whosonfirst.mapzen.com/data/858/826/41/85882641.geojson assert_has_feature( 16, 10482, 25330, 'places', { 'id': 26819236, 'kind': 'city', 'source': "openstreetmap.org", 'name': 'San Francisco', 'name:zho': '\xe8\x88\x8a\xe9\x87\x91\xe5\xb1\xb1\xe5\xb8\x82\xe8\x88\x87\xe7\xb8\xa3' })
# Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:ko': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0\xeb\x93\x9c' }) Update tests for new l10n behavior# Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:kor': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0\xeb\x93\x9c' }) # San Francisco (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/826/41/85882641.geojson assert_has_feature( 16, 14893, 29234, 'places', { 'id': 85882641, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'San Francisco', 'name:spa': type(None) }) # San Francisco (osm city) # https://whosonfirst.mapzen.com/data/858/826/41/85882641.geojson assert_has_feature( 16, 10482, 25330, 'places', { 'id': 26819236, 'kind': 'city', 'source': "openstreetmap.org", 'name': 'San Francisco', 'name:zho': '\xe8\x88\x8a\xe9\x87\x91\xe5\xb1\xb1\xe5\xb8\x82\xe8\x88\x87\xe7\xb8\xa3' })
<commit_before># Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:ko': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0\xeb\x93\x9c' }) <commit_msg>Update tests for new l10n behavior<commit_after># Hollywood (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/260/37/85826037.geojson assert_has_feature( 16, 11227, 26157, 'places', { 'id': 85826037, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'Hollywood', 'name:kor': '\xed\x97\x90\xeb\xa6\xac\xec\x9a\xb0\xeb\x93\x9c' }) # San Francisco (wof neighbourhood) # https://whosonfirst.mapzen.com/data/858/826/41/85882641.geojson assert_has_feature( 16, 14893, 29234, 'places', { 'id': 85882641, 'kind': 'neighbourhood', 'source': "whosonfirst.mapzen.com", 'name': 'San Francisco', 'name:spa': type(None) }) # San Francisco (osm city) # https://whosonfirst.mapzen.com/data/858/826/41/85882641.geojson assert_has_feature( 16, 10482, 25330, 'places', { 'id': 26819236, 'kind': 'city', 'source': "openstreetmap.org", 'name': 'San Francisco', 'name:zho': '\xe8\x88\x8a\xe9\x87\x91\xe5\xb1\xb1\xe5\xb8\x82\xe8\x88\x87\xe7\xb8\xa3' })
2833a895e8a7d0ba879598222c83bc5a4cd88853
desc/geometry/__init__.py
desc/geometry/__init__.py
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSection", ]
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection from .core import Surface, Curve __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSection", ]
Add geometry ABCs to init
Add geometry ABCs to init
Python
mit
PlasmaControl/DESC,PlasmaControl/DESC
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSection", ] Add geometry ABCs to init
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection from .core import Surface, Curve __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSection", ]
<commit_before>from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSection", ] <commit_msg>Add geometry ABCs to init<commit_after>
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection from .core import Surface, Curve __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSection", ]
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSection", ] Add geometry ABCs to initfrom .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection from .core import Surface, Curve __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSection", ]
<commit_before>from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSection", ] <commit_msg>Add geometry ABCs to init<commit_after>from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection from .core import Surface, Curve __all__ = [ "FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "FourierRZToroidalSurface", "ZernikeRZToroidalSection", ]
700b1681162210e00afc1a7ca22bff5a82522077
tests/DdlTextWrterTest.py
tests/DdlTextWrterTest.py
import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write("test.oddl") # check if file was created try: self.assertTrue(os.path.isfile("test.oddl")) except FileNotFoundError: self.fail("DdlTextWriter did not create the specified file.") def test_full(self): # create document document = DdlDocument() document.add_structure(B"Human", None, [DdlStructure(B"Name", None, [DdlPrimitive(PrimitiveType.string, ["Peter"])]), DdlStructure(B"Age", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) # write document DdlTextWriter(document).write("test.oddl") if __name__ == "__main__": unittest.main()
import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write("test.oddl") # check if file was created try: self.assertTrue(os.path.isfile("test.oddl")) except FileNotFoundError: self.fail("DdlTextWriter did not create the specified file.") def test_full(self): # create document document = DdlDocument() document.add_structure(B"Human", None, [DdlStructure(B"Name", None, [DdlPrimitive(PrimitiveType.string, ["Peter"])]), DdlStructure(B"Age", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) document.add_structure(B"SomethingElse", None, [DdlStructure(B"AnArray", None, [DdlPrimitive(PrimitiveType.int32, range(1, 100))])] ) document.add_structure(B"MoreElse", None, [DdlStructure(B"AnVectorArray", None, [DdlPrimitive(PrimitiveType.int32, [(1, 2), (12, 42), (13, 31)], None, 2)])] ) # write document DdlTextWriter(document).write("test.oddl") if __name__ == "__main__": unittest.main()
Add more structures to test_full() document
Add more structures to test_full() document Signed-off-by: Squareys <0f6a03d4883e012ba4cb2c581a68f35544703cd6@googlemail.com>
Python
mit
Squareys/PyDDL
import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write("test.oddl") # check if file was created try: self.assertTrue(os.path.isfile("test.oddl")) except FileNotFoundError: self.fail("DdlTextWriter did not create the specified file.") def test_full(self): # create document document = DdlDocument() document.add_structure(B"Human", None, [DdlStructure(B"Name", None, [DdlPrimitive(PrimitiveType.string, ["Peter"])]), DdlStructure(B"Age", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) # write document DdlTextWriter(document).write("test.oddl") if __name__ == "__main__": unittest.main() Add more structures to test_full() document Signed-off-by: Squareys <0f6a03d4883e012ba4cb2c581a68f35544703cd6@googlemail.com>
import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write("test.oddl") # check if file was created try: self.assertTrue(os.path.isfile("test.oddl")) except FileNotFoundError: self.fail("DdlTextWriter did not create the specified file.") def test_full(self): # create document document = DdlDocument() document.add_structure(B"Human", None, [DdlStructure(B"Name", None, [DdlPrimitive(PrimitiveType.string, ["Peter"])]), DdlStructure(B"Age", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) document.add_structure(B"SomethingElse", None, [DdlStructure(B"AnArray", None, [DdlPrimitive(PrimitiveType.int32, range(1, 100))])] ) document.add_structure(B"MoreElse", None, [DdlStructure(B"AnVectorArray", None, [DdlPrimitive(PrimitiveType.int32, [(1, 2), (12, 42), (13, 31)], None, 2)])] ) # write document DdlTextWriter(document).write("test.oddl") if __name__ == "__main__": unittest.main()
<commit_before>import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write("test.oddl") # check if file was created try: self.assertTrue(os.path.isfile("test.oddl")) except FileNotFoundError: self.fail("DdlTextWriter did not create the specified file.") def test_full(self): # create document document = DdlDocument() document.add_structure(B"Human", None, [DdlStructure(B"Name", None, [DdlPrimitive(PrimitiveType.string, ["Peter"])]), DdlStructure(B"Age", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) # write document DdlTextWriter(document).write("test.oddl") if __name__ == "__main__": unittest.main() <commit_msg>Add more structures to test_full() document Signed-off-by: Squareys <0f6a03d4883e012ba4cb2c581a68f35544703cd6@googlemail.com><commit_after>
import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write("test.oddl") # check if file was created try: self.assertTrue(os.path.isfile("test.oddl")) except FileNotFoundError: self.fail("DdlTextWriter did not create the specified file.") def test_full(self): # create document document = DdlDocument() document.add_structure(B"Human", None, [DdlStructure(B"Name", None, [DdlPrimitive(PrimitiveType.string, ["Peter"])]), DdlStructure(B"Age", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) document.add_structure(B"SomethingElse", None, [DdlStructure(B"AnArray", None, [DdlPrimitive(PrimitiveType.int32, range(1, 100))])] ) document.add_structure(B"MoreElse", None, [DdlStructure(B"AnVectorArray", None, [DdlPrimitive(PrimitiveType.int32, [(1, 2), (12, 42), (13, 31)], None, 2)])] ) # write document DdlTextWriter(document).write("test.oddl") if __name__ == "__main__": unittest.main()
import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write("test.oddl") # check if file was created try: self.assertTrue(os.path.isfile("test.oddl")) except FileNotFoundError: self.fail("DdlTextWriter did not create the specified file.") def test_full(self): # create document document = DdlDocument() document.add_structure(B"Human", None, [DdlStructure(B"Name", None, [DdlPrimitive(PrimitiveType.string, ["Peter"])]), DdlStructure(B"Age", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) # write document DdlTextWriter(document).write("test.oddl") if __name__ == "__main__": unittest.main() Add more structures to test_full() document Signed-off-by: Squareys <0f6a03d4883e012ba4cb2c581a68f35544703cd6@googlemail.com>import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write("test.oddl") # check if file was created try: self.assertTrue(os.path.isfile("test.oddl")) except FileNotFoundError: self.fail("DdlTextWriter did not create the specified file.") def test_full(self): # create document document = DdlDocument() document.add_structure(B"Human", None, [DdlStructure(B"Name", None, [DdlPrimitive(PrimitiveType.string, ["Peter"])]), DdlStructure(B"Age", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) document.add_structure(B"SomethingElse", None, [DdlStructure(B"AnArray", None, [DdlPrimitive(PrimitiveType.int32, range(1, 100))])] ) document.add_structure(B"MoreElse", None, [DdlStructure(B"AnVectorArray", None, [DdlPrimitive(PrimitiveType.int32, [(1, 2), (12, 42), (13, 31)], None, 2)])] ) # write document DdlTextWriter(document).write("test.oddl") if __name__ == "__main__": unittest.main()
<commit_before>import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write("test.oddl") # check if file was created try: self.assertTrue(os.path.isfile("test.oddl")) except FileNotFoundError: self.fail("DdlTextWriter did not create the specified file.") def test_full(self): # create document document = DdlDocument() document.add_structure(B"Human", None, [DdlStructure(B"Name", None, [DdlPrimitive(PrimitiveType.string, ["Peter"])]), DdlStructure(B"Age", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) # write document DdlTextWriter(document).write("test.oddl") if __name__ == "__main__": unittest.main() <commit_msg>Add more structures to test_full() document Signed-off-by: Squareys <0f6a03d4883e012ba4cb2c581a68f35544703cd6@googlemail.com><commit_after>import os import unittest from pyddl import * from pyddl.enum import * __author__ = "Jonathan Hale" class DdlTextWriterTest(unittest.TestCase): def tearDown(self): try: os.remove("test.oddl") except FileNotFoundError: pass # test_empty failed? def test_empty(self): # create document document = DdlDocument() # write document DdlTextWriter(document).write("test.oddl") # check if file was created try: self.assertTrue(os.path.isfile("test.oddl")) except FileNotFoundError: self.fail("DdlTextWriter did not create the specified file.") def test_full(self): # create document document = DdlDocument() document.add_structure(B"Human", None, [DdlStructure(B"Name", None, [DdlPrimitive(PrimitiveType.string, ["Peter"])]), DdlStructure(B"Age", None, [DdlPrimitive(PrimitiveType.unsigned_int16, [21])])] ) document.add_structure(B"SomethingElse", None, [DdlStructure(B"AnArray", None, [DdlPrimitive(PrimitiveType.int32, range(1, 100))])] ) document.add_structure(B"MoreElse", None, [DdlStructure(B"AnVectorArray", None, [DdlPrimitive(PrimitiveType.int32, [(1, 2), (12, 42), (13, 31)], None, 2)])] ) # write document DdlTextWriter(document).write("test.oddl") if __name__ == "__main__": unittest.main()
435ac02a320582fb8ede698da579d5c4fdd2d600
summary_footnotes.py
summary_footnotes.py
""" Summary Footnotes ------------- Fix handling of footnotes inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def summary_footnotes(instance): if "SUMMARY_FOOTNOTES_MODE" in instance.settings: mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] else: mode = 'link' if type(instance) == Article: summary = BeautifulSoup(instance.summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (instance.settings["SITEURL"], instance.url, link['href']) else: raise Exception("Unknown summary footnote mode: %s" % mode) instance._summary = text_type(summary) def register(): signals.content_object_init.connect(summary_footnotes)
""" Summary Footnotes ------------- Fix handling of footnote links inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def initialized(pelican): from pelican.settings import DEFAULT_CONFIG DEFAULT_CONFIG.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') if pelican: pelican.settings.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') def transform_summary(summary, article_url, site_url, mode): summary = BeautifulSoup(summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (site_url, article_url, link['href']) else: raise Exception("Unknown summary_footnote mode: %s" % mode) return text_type(summary) return None def summary_footnotes(instance): mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] if type(instance) == Article: # Monkeypatch in the rewrite on the summary because when this is run # the content might not be ready yet if it depends on other files # being loaded. instance._orig_get_summary = instance._get_summary def _get_summary(self): summary = self._orig_get_summary() new_summary = transform_summary(summary, self.url, self.settings['SITEURL'], mode) if new_summary is not None: return new_summary else: return summary funcType = type(instance._get_summary) instance._get_summary = funcType(_get_summary, instance, Article) def register(): signals.initialized.connect(initialized) signals.content_object_init.connect(summary_footnotes)
Rewrite summary as late as possible.
Rewrite summary as late as possible. Fixes issue where {filename} links would sometimes not work.
Python
agpl-3.0
dperelman/summary_footnotes
""" Summary Footnotes ------------- Fix handling of footnotes inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def summary_footnotes(instance): if "SUMMARY_FOOTNOTES_MODE" in instance.settings: mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] else: mode = 'link' if type(instance) == Article: summary = BeautifulSoup(instance.summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (instance.settings["SITEURL"], instance.url, link['href']) else: raise Exception("Unknown summary footnote mode: %s" % mode) instance._summary = text_type(summary) def register(): signals.content_object_init.connect(summary_footnotes) Rewrite summary as late as possible. Fixes issue where {filename} links would sometimes not work.
""" Summary Footnotes ------------- Fix handling of footnote links inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def initialized(pelican): from pelican.settings import DEFAULT_CONFIG DEFAULT_CONFIG.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') if pelican: pelican.settings.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') def transform_summary(summary, article_url, site_url, mode): summary = BeautifulSoup(summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (site_url, article_url, link['href']) else: raise Exception("Unknown summary_footnote mode: %s" % mode) return text_type(summary) return None def summary_footnotes(instance): mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] if type(instance) == Article: # Monkeypatch in the rewrite on the summary because when this is run # the content might not be ready yet if it depends on other files # being loaded. instance._orig_get_summary = instance._get_summary def _get_summary(self): summary = self._orig_get_summary() new_summary = transform_summary(summary, self.url, self.settings['SITEURL'], mode) if new_summary is not None: return new_summary else: return summary funcType = type(instance._get_summary) instance._get_summary = funcType(_get_summary, instance, Article) def register(): signals.initialized.connect(initialized) signals.content_object_init.connect(summary_footnotes)
<commit_before>""" Summary Footnotes ------------- Fix handling of footnotes inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def summary_footnotes(instance): if "SUMMARY_FOOTNOTES_MODE" in instance.settings: mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] else: mode = 'link' if type(instance) == Article: summary = BeautifulSoup(instance.summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (instance.settings["SITEURL"], instance.url, link['href']) else: raise Exception("Unknown summary footnote mode: %s" % mode) instance._summary = text_type(summary) def register(): signals.content_object_init.connect(summary_footnotes) <commit_msg>Rewrite summary as late as possible. Fixes issue where {filename} links would sometimes not work.<commit_after>
""" Summary Footnotes ------------- Fix handling of footnote links inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def initialized(pelican): from pelican.settings import DEFAULT_CONFIG DEFAULT_CONFIG.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') if pelican: pelican.settings.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') def transform_summary(summary, article_url, site_url, mode): summary = BeautifulSoup(summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (site_url, article_url, link['href']) else: raise Exception("Unknown summary_footnote mode: %s" % mode) return text_type(summary) return None def summary_footnotes(instance): mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] if type(instance) == Article: # Monkeypatch in the rewrite on the summary because when this is run # the content might not be ready yet if it depends on other files # being loaded. instance._orig_get_summary = instance._get_summary def _get_summary(self): summary = self._orig_get_summary() new_summary = transform_summary(summary, self.url, self.settings['SITEURL'], mode) if new_summary is not None: return new_summary else: return summary funcType = type(instance._get_summary) instance._get_summary = funcType(_get_summary, instance, Article) def register(): signals.initialized.connect(initialized) signals.content_object_init.connect(summary_footnotes)
""" Summary Footnotes ------------- Fix handling of footnotes inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def summary_footnotes(instance): if "SUMMARY_FOOTNOTES_MODE" in instance.settings: mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] else: mode = 'link' if type(instance) == Article: summary = BeautifulSoup(instance.summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (instance.settings["SITEURL"], instance.url, link['href']) else: raise Exception("Unknown summary footnote mode: %s" % mode) instance._summary = text_type(summary) def register(): signals.content_object_init.connect(summary_footnotes) Rewrite summary as late as possible. Fixes issue where {filename} links would sometimes not work.""" Summary Footnotes ------------- Fix handling of footnote links inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def initialized(pelican): from pelican.settings import DEFAULT_CONFIG DEFAULT_CONFIG.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') if pelican: pelican.settings.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') def transform_summary(summary, article_url, site_url, mode): summary = BeautifulSoup(summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (site_url, article_url, link['href']) else: raise Exception("Unknown summary_footnote mode: %s" % mode) return text_type(summary) return None def summary_footnotes(instance): mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] if type(instance) == Article: # Monkeypatch in the rewrite on the summary because when this is run # the content might not be ready yet if it depends on other files # being loaded. instance._orig_get_summary = instance._get_summary def _get_summary(self): summary = self._orig_get_summary() new_summary = transform_summary(summary, self.url, self.settings['SITEURL'], mode) if new_summary is not None: return new_summary else: return summary funcType = type(instance._get_summary) instance._get_summary = funcType(_get_summary, instance, Article) def register(): signals.initialized.connect(initialized) signals.content_object_init.connect(summary_footnotes)
<commit_before>""" Summary Footnotes ------------- Fix handling of footnotes inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def summary_footnotes(instance): if "SUMMARY_FOOTNOTES_MODE" in instance.settings: mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] else: mode = 'link' if type(instance) == Article: summary = BeautifulSoup(instance.summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (instance.settings["SITEURL"], instance.url, link['href']) else: raise Exception("Unknown summary footnote mode: %s" % mode) instance._summary = text_type(summary) def register(): signals.content_object_init.connect(summary_footnotes) <commit_msg>Rewrite summary as late as possible. Fixes issue where {filename} links would sometimes not work.<commit_after>""" Summary Footnotes ------------- Fix handling of footnote links inside article summaries. Option to either remove them or make them link to the article page. """ from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def initialized(pelican): from pelican.settings import DEFAULT_CONFIG DEFAULT_CONFIG.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') if pelican: pelican.settings.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') def transform_summary(summary, article_url, site_url, mode): summary = BeautifulSoup(summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (site_url, article_url, link['href']) else: raise Exception("Unknown summary_footnote mode: %s" % mode) return text_type(summary) return None def summary_footnotes(instance): mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] if type(instance) == Article: # Monkeypatch in the rewrite on the summary because when this is run # the content might not be ready yet if it depends on other files # being loaded. instance._orig_get_summary = instance._get_summary def _get_summary(self): summary = self._orig_get_summary() new_summary = transform_summary(summary, self.url, self.settings['SITEURL'], mode) if new_summary is not None: return new_summary else: return summary funcType = type(instance._get_summary) instance._get_summary = funcType(_get_summary, instance, Article) def register(): signals.initialized.connect(initialized) signals.content_object_init.connect(summary_footnotes)
6fa6203ce412ec1f9f50d07fce0a8c279878a3f1
examples/visual_testing/layout_test.py
examples/visual_testing/layout_test.py
from seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('a[href="?diff1"]') # Verify html tags match previous version self.check_window(name="helloworld", level=1) # Verify html tags + attributes match previous version self.check_window(name="helloworld", level=2) # Verify html tags + attributes + values match previous version self.check_window(name="helloworld", level=3) # Change the page enough for a Level-3 comparison to fail self.click("button") self.check_window(name="helloworld", level=1) self.check_window(name="helloworld", level=2) with self.assertRaises(Exception): self.check_window(name="helloworld", level=3) # Now that we know the exception was raised as expected, # let's print out the comparison results by running in Level-0. self.check_window(name="helloworld", level=0)
from seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('a[href="?diff1"]') # Verify html tags match previous version self.check_window(name="helloworld", level=1) # Verify html tags + attributes match previous version self.check_window(name="helloworld", level=2) # Verify html tags + attributes + values match previous version self.check_window(name="helloworld", level=3) # Change the page enough for a Level-3 comparison to fail self.click("button") self.check_window(name="helloworld", level=1) self.check_window(name="helloworld", level=2) with self.assertRaises(Exception): self.check_window(name="helloworld", level=3) # Now that we know the Exception was raised as expected, # let's print out the comparison results by running in Level-0. # (NOTE: Running with level-0 will print but NOT raise an Exception.) self.check_window(name="helloworld", level=0)
Update comments in the layout test
Update comments in the layout test
Python
mit
mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase
from seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('a[href="?diff1"]') # Verify html tags match previous version self.check_window(name="helloworld", level=1) # Verify html tags + attributes match previous version self.check_window(name="helloworld", level=2) # Verify html tags + attributes + values match previous version self.check_window(name="helloworld", level=3) # Change the page enough for a Level-3 comparison to fail self.click("button") self.check_window(name="helloworld", level=1) self.check_window(name="helloworld", level=2) with self.assertRaises(Exception): self.check_window(name="helloworld", level=3) # Now that we know the exception was raised as expected, # let's print out the comparison results by running in Level-0. self.check_window(name="helloworld", level=0) Update comments in the layout test
from seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('a[href="?diff1"]') # Verify html tags match previous version self.check_window(name="helloworld", level=1) # Verify html tags + attributes match previous version self.check_window(name="helloworld", level=2) # Verify html tags + attributes + values match previous version self.check_window(name="helloworld", level=3) # Change the page enough for a Level-3 comparison to fail self.click("button") self.check_window(name="helloworld", level=1) self.check_window(name="helloworld", level=2) with self.assertRaises(Exception): self.check_window(name="helloworld", level=3) # Now that we know the Exception was raised as expected, # let's print out the comparison results by running in Level-0. # (NOTE: Running with level-0 will print but NOT raise an Exception.) self.check_window(name="helloworld", level=0)
<commit_before>from seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('a[href="?diff1"]') # Verify html tags match previous version self.check_window(name="helloworld", level=1) # Verify html tags + attributes match previous version self.check_window(name="helloworld", level=2) # Verify html tags + attributes + values match previous version self.check_window(name="helloworld", level=3) # Change the page enough for a Level-3 comparison to fail self.click("button") self.check_window(name="helloworld", level=1) self.check_window(name="helloworld", level=2) with self.assertRaises(Exception): self.check_window(name="helloworld", level=3) # Now that we know the exception was raised as expected, # let's print out the comparison results by running in Level-0. self.check_window(name="helloworld", level=0) <commit_msg>Update comments in the layout test<commit_after>
from seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('a[href="?diff1"]') # Verify html tags match previous version self.check_window(name="helloworld", level=1) # Verify html tags + attributes match previous version self.check_window(name="helloworld", level=2) # Verify html tags + attributes + values match previous version self.check_window(name="helloworld", level=3) # Change the page enough for a Level-3 comparison to fail self.click("button") self.check_window(name="helloworld", level=1) self.check_window(name="helloworld", level=2) with self.assertRaises(Exception): self.check_window(name="helloworld", level=3) # Now that we know the Exception was raised as expected, # let's print out the comparison results by running in Level-0. # (NOTE: Running with level-0 will print but NOT raise an Exception.) self.check_window(name="helloworld", level=0)
from seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('a[href="?diff1"]') # Verify html tags match previous version self.check_window(name="helloworld", level=1) # Verify html tags + attributes match previous version self.check_window(name="helloworld", level=2) # Verify html tags + attributes + values match previous version self.check_window(name="helloworld", level=3) # Change the page enough for a Level-3 comparison to fail self.click("button") self.check_window(name="helloworld", level=1) self.check_window(name="helloworld", level=2) with self.assertRaises(Exception): self.check_window(name="helloworld", level=3) # Now that we know the exception was raised as expected, # let's print out the comparison results by running in Level-0. self.check_window(name="helloworld", level=0) Update comments in the layout testfrom seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('a[href="?diff1"]') # Verify html tags match previous version self.check_window(name="helloworld", level=1) # Verify html tags + attributes match previous version self.check_window(name="helloworld", level=2) # Verify html tags + attributes + values match previous version self.check_window(name="helloworld", level=3) # Change the page enough for a Level-3 comparison to fail self.click("button") self.check_window(name="helloworld", level=1) self.check_window(name="helloworld", level=2) with self.assertRaises(Exception): self.check_window(name="helloworld", level=3) # Now that we know the Exception was raised as expected, # let's print out the comparison results by running in Level-0. # (NOTE: Running with level-0 will print but NOT raise an Exception.) self.check_window(name="helloworld", level=0)
<commit_before>from seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('a[href="?diff1"]') # Verify html tags match previous version self.check_window(name="helloworld", level=1) # Verify html tags + attributes match previous version self.check_window(name="helloworld", level=2) # Verify html tags + attributes + values match previous version self.check_window(name="helloworld", level=3) # Change the page enough for a Level-3 comparison to fail self.click("button") self.check_window(name="helloworld", level=1) self.check_window(name="helloworld", level=2) with self.assertRaises(Exception): self.check_window(name="helloworld", level=3) # Now that we know the exception was raised as expected, # let's print out the comparison results by running in Level-0. self.check_window(name="helloworld", level=0) <commit_msg>Update comments in the layout test<commit_after>from seleniumbase import BaseCase class VisualLayoutTest(BaseCase): def test_applitools_helloworld(self): self.open('https://applitools.com/helloworld?diff1') print('Creating baseline in "visual_baseline" folder...') self.check_window(name="helloworld", baseline=True) self.click('a[href="?diff1"]') # Verify html tags match previous version self.check_window(name="helloworld", level=1) # Verify html tags + attributes match previous version self.check_window(name="helloworld", level=2) # Verify html tags + attributes + values match previous version self.check_window(name="helloworld", level=3) # Change the page enough for a Level-3 comparison to fail self.click("button") self.check_window(name="helloworld", level=1) self.check_window(name="helloworld", level=2) with self.assertRaises(Exception): self.check_window(name="helloworld", level=3) # Now that we know the Exception was raised as expected, # let's print out the comparison results by running in Level-0. # (NOTE: Running with level-0 will print but NOT raise an Exception.) self.check_window(name="helloworld", level=0)
8ce2882f365f24bcdb4274f78809afdda602083a
tests/test_meetup_loto.py
tests/test_meetup_loto.py
import tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_participants() self.assertEquals(10, nb_participants) self.assertEquals(0.1, self.loto.current_chances()) def test_meetup_loto_winner(self): winner = self.loto.draw() self.assertTrue(winner >= 1 and winner <= 10) def test_meetup_loto_multiple_draw(self): winners = [] for i in range(11): winner = self.loto.draw() self.assertFalse(winner in winners) winners.append(winner) self.assertEquals(0, winners[-1]) class FakeApi: def get_rsvps(self, meetup_name, event_id): return [{'member': {'id': 1}}, {'member': {'id': 2}}, {'member': {'id': 3}}, {'member': {'id': 4}}, {'member': {'id': 5}}, {'member': {'id': 6}}, {'member': {'id': 7}}, {'member': {'id': 8}}, {'member': {'id': 9}}, {'member': {'id': 10}}]
import tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_participants() self.assertEquals(10, nb_participants) self.assertEquals(0.1, self.loto.current_chances()) def test_meetup_loto_winner(self): winner = self.loto.draw() self.assertTrue(winner >= 1 and winner <= 10) def test_meetup_loto_multiple_draw(self): winners = [] for i in range(11): winner = self.loto.draw() self.assertFalse(winner in winners) winners.append(winner) self.assertEquals(0, winners[-1]) class FakeApi: def get_rsvps(self, meetup_name, event_id): return [{'member': {'id':n}} for n in range(1, 11)]
Use list comprehensions to generate test data
Use list comprehensions to generate test data
Python
mit
ghislainbourgeois/meetup_loto,ghislainbourgeois/meetup_loto,ghislainbourgeois/meetup_loto
import tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_participants() self.assertEquals(10, nb_participants) self.assertEquals(0.1, self.loto.current_chances()) def test_meetup_loto_winner(self): winner = self.loto.draw() self.assertTrue(winner >= 1 and winner <= 10) def test_meetup_loto_multiple_draw(self): winners = [] for i in range(11): winner = self.loto.draw() self.assertFalse(winner in winners) winners.append(winner) self.assertEquals(0, winners[-1]) class FakeApi: def get_rsvps(self, meetup_name, event_id): return [{'member': {'id': 1}}, {'member': {'id': 2}}, {'member': {'id': 3}}, {'member': {'id': 4}}, {'member': {'id': 5}}, {'member': {'id': 6}}, {'member': {'id': 7}}, {'member': {'id': 8}}, {'member': {'id': 9}}, {'member': {'id': 10}}] Use list comprehensions to generate test data
import tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_participants() self.assertEquals(10, nb_participants) self.assertEquals(0.1, self.loto.current_chances()) def test_meetup_loto_winner(self): winner = self.loto.draw() self.assertTrue(winner >= 1 and winner <= 10) def test_meetup_loto_multiple_draw(self): winners = [] for i in range(11): winner = self.loto.draw() self.assertFalse(winner in winners) winners.append(winner) self.assertEquals(0, winners[-1]) class FakeApi: def get_rsvps(self, meetup_name, event_id): return [{'member': {'id':n}} for n in range(1, 11)]
<commit_before>import tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_participants() self.assertEquals(10, nb_participants) self.assertEquals(0.1, self.loto.current_chances()) def test_meetup_loto_winner(self): winner = self.loto.draw() self.assertTrue(winner >= 1 and winner <= 10) def test_meetup_loto_multiple_draw(self): winners = [] for i in range(11): winner = self.loto.draw() self.assertFalse(winner in winners) winners.append(winner) self.assertEquals(0, winners[-1]) class FakeApi: def get_rsvps(self, meetup_name, event_id): return [{'member': {'id': 1}}, {'member': {'id': 2}}, {'member': {'id': 3}}, {'member': {'id': 4}}, {'member': {'id': 5}}, {'member': {'id': 6}}, {'member': {'id': 7}}, {'member': {'id': 8}}, {'member': {'id': 9}}, {'member': {'id': 10}}] <commit_msg>Use list comprehensions to generate test data<commit_after>
import tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_participants() self.assertEquals(10, nb_participants) self.assertEquals(0.1, self.loto.current_chances()) def test_meetup_loto_winner(self): winner = self.loto.draw() self.assertTrue(winner >= 1 and winner <= 10) def test_meetup_loto_multiple_draw(self): winners = [] for i in range(11): winner = self.loto.draw() self.assertFalse(winner in winners) winners.append(winner) self.assertEquals(0, winners[-1]) class FakeApi: def get_rsvps(self, meetup_name, event_id): return [{'member': {'id':n}} for n in range(1, 11)]
import tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_participants() self.assertEquals(10, nb_participants) self.assertEquals(0.1, self.loto.current_chances()) def test_meetup_loto_winner(self): winner = self.loto.draw() self.assertTrue(winner >= 1 and winner <= 10) def test_meetup_loto_multiple_draw(self): winners = [] for i in range(11): winner = self.loto.draw() self.assertFalse(winner in winners) winners.append(winner) self.assertEquals(0, winners[-1]) class FakeApi: def get_rsvps(self, meetup_name, event_id): return [{'member': {'id': 1}}, {'member': {'id': 2}}, {'member': {'id': 3}}, {'member': {'id': 4}}, {'member': {'id': 5}}, {'member': {'id': 6}}, {'member': {'id': 7}}, {'member': {'id': 8}}, {'member': {'id': 9}}, {'member': {'id': 10}}] Use list comprehensions to generate test dataimport tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_participants() self.assertEquals(10, nb_participants) self.assertEquals(0.1, self.loto.current_chances()) def test_meetup_loto_winner(self): winner = self.loto.draw() self.assertTrue(winner >= 1 and winner <= 10) def test_meetup_loto_multiple_draw(self): winners = [] for i in range(11): winner = self.loto.draw() self.assertFalse(winner in winners) winners.append(winner) self.assertEquals(0, winners[-1]) class FakeApi: def get_rsvps(self, meetup_name, event_id): return [{'member': {'id':n}} for n in range(1, 11)]
<commit_before>import tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_participants() self.assertEquals(10, nb_participants) self.assertEquals(0.1, self.loto.current_chances()) def test_meetup_loto_winner(self): winner = self.loto.draw() self.assertTrue(winner >= 1 and winner <= 10) def test_meetup_loto_multiple_draw(self): winners = [] for i in range(11): winner = self.loto.draw() self.assertFalse(winner in winners) winners.append(winner) self.assertEquals(0, winners[-1]) class FakeApi: def get_rsvps(self, meetup_name, event_id): return [{'member': {'id': 1}}, {'member': {'id': 2}}, {'member': {'id': 3}}, {'member': {'id': 4}}, {'member': {'id': 5}}, {'member': {'id': 6}}, {'member': {'id': 7}}, {'member': {'id': 8}}, {'member': {'id': 9}}, {'member': {'id': 10}}] <commit_msg>Use list comprehensions to generate test data<commit_after>import tests.context import unittest from meetup_loto import Loto class TestMeetupLoto(unittest.TestCase): def setUp(self): self.api = FakeApi() self.loto = Loto(self.api, "Docker-Montreal", 240672864) def test_meetup_loto_participants(self): nb_participants = self.loto.number_of_participants() self.assertEquals(10, nb_participants) self.assertEquals(0.1, self.loto.current_chances()) def test_meetup_loto_winner(self): winner = self.loto.draw() self.assertTrue(winner >= 1 and winner <= 10) def test_meetup_loto_multiple_draw(self): winners = [] for i in range(11): winner = self.loto.draw() self.assertFalse(winner in winners) winners.append(winner) self.assertEquals(0, winners[-1]) class FakeApi: def get_rsvps(self, meetup_name, event_id): return [{'member': {'id':n}} for n in range(1, 11)]
275090f49fde702bb0189845afc322ec728907d6
app/models.py
app/models.py
from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): self._spotify = oa_client.refresh_access_token(self._spotify) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count
from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): print("Spotify token expired for {}.".format(self.username)) self._spotify = oa_client.refresh_access_token( self._spotify.get('refresh_token')) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count
Fix token refresh for spotify credentials
Fix token refresh for spotify credentials
Python
mit
DropMuse/DropMuse,DropMuse/DropMuse
from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): self._spotify = oa_client.refresh_access_token(self._spotify) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count Fix token refresh for spotify credentials
from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): print("Spotify token expired for {}.".format(self.username)) self._spotify = oa_client.refresh_access_token( self._spotify.get('refresh_token')) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count
<commit_before>from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): self._spotify = oa_client.refresh_access_token(self._spotify) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count <commit_msg>Fix token refresh for spotify credentials<commit_after>
from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): print("Spotify token expired for {}.".format(self.username)) self._spotify = oa_client.refresh_access_token( self._spotify.get('refresh_token')) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count
from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): self._spotify = oa_client.refresh_access_token(self._spotify) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count Fix token refresh for spotify credentialsfrom flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): print("Spotify token expired for {}.".format(self.username)) self._spotify = oa_client.refresh_access_token( self._spotify.get('refresh_token')) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count
<commit_before>from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): self._spotify = oa_client.refresh_access_token(self._spotify) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count <commit_msg>Fix token refresh for spotify credentials<commit_after>from flask_login import UserMixin import spotify import spotipy import db_utils import application as app class User(UserMixin): ''' User class for Flask-Login ''' def __init__(self, user_id, username=None): self.id = int(user_id) self.username = username self._spotify = None @property def spotify(self): oa_client = spotify.sp_oauth # Fetch credentials from database if not self._spotify: self._spotify = db_utils.spotify_creds_for_user(app.engine, self.id) # No credentials exist for user if self._spotify is None: return None # Refresh tokens if nescessary if oa_client.is_token_expired(self._spotify): print("Spotify token expired for {}.".format(self.username)) self._spotify = oa_client.refresh_access_token( self._spotify.get('refresh_token')) # Save/return new credentials if possible if self._spotify: db_utils.spotify_credentials_upsert(app.engine, self.id, self._spotify) return spotipy.Spotify(auth=self._spotify['access_token']) class Playlist(object): ''' Playlist object representation ''' def __init__(self, playlist_id, title=None, duration=0, count=0): self.id = playlist_id self.title = title self.duration = duration self.count = count
248ed7b2d273fc044652af78388127f2fa31641c
test.py
test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in FROM_HIRA.values(): self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, FROM_HIRA.values(), "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in TO_HIRA: self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, TO_HIRA, "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()
Use TO_HIRAGANA to get lemmas from Hiragana table.
Use TO_HIRAGANA to get lemmas from Hiragana table.
Python
bsd-3-clause
khanson679/romaji-tools
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in FROM_HIRA.values(): self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, FROM_HIRA.values(), "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()Use TO_HIRAGANA to get lemmas from Hiragana table.
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in TO_HIRA: self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, TO_HIRA, "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in FROM_HIRA.values(): self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, FROM_HIRA.values(), "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()<commit_msg>Use TO_HIRAGANA to get lemmas from Hiragana table.<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in TO_HIRA: self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, TO_HIRA, "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in FROM_HIRA.values(): self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, FROM_HIRA.values(), "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()Use TO_HIRAGANA to get lemmas from Hiragana table.#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in TO_HIRA: self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, TO_HIRA, "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in FROM_HIRA.values(): self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, FROM_HIRA.values(), "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()<commit_msg>Use TO_HIRAGANA to get lemmas from Hiragana table.<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from romajitools import * class RTTestCase(unittest.TestCase): def test_lemma_tables(self): # sanity test self.assertEqual(len(LEMMAS), 233) def test_hiragana_table(self): # check that all Hiragana entries have a lemma, and vis versa for lemma in TO_HIRA: self.assertIn(lemma, LEMMAS, "Lemma from Hiragana table not in master table: {}".format(lemma)) for lemma in LEMMAS: self.assertIn(lemma, TO_HIRA, "Hiragana table missing a lemma: {}".format(lemma)) def test_convert_from_hira(self): # sanity test self.assertEqual(to_wapuro("ひらがな"), "hiragana") if __name__ == '__main__': unittest.main()
0662cd31d0c49c85460200093311eea6fa86f09e
mwikiircbot.py
mwikiircbot.py
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return else: Handler(host=host, name=name channels=channels) if __name__ == "__main__": if __name__ == '__main__': main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return else: Handler(host=host, name=name, channels=channels) if __name__ == "__main__": main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
Remove a redundant if and fix a syntax error
Remove a redundant if and fix a syntax error
Python
mit
fenhl/mwikiircbot
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return else: Handler(host=host, name=name channels=channels) if __name__ == "__main__": if __name__ == '__main__': main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else []) Remove a redundant if and fix a syntax error
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return else: Handler(host=host, name=name, channels=channels) if __name__ == "__main__": main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
<commit_before>import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return else: Handler(host=host, name=name channels=channels) if __name__ == "__main__": if __name__ == '__main__': main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else []) <commit_msg>Remove a redundant if and fix a syntax error<commit_after>
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return else: Handler(host=host, name=name, channels=channels) if __name__ == "__main__": main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return else: Handler(host=host, name=name channels=channels) if __name__ == "__main__": if __name__ == '__main__': main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else []) Remove a redundant if and fix a syntax errorimport ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return else: Handler(host=host, name=name, channels=channels) if __name__ == "__main__": main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
<commit_before>import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return else: Handler(host=host, name=name channels=channels) if __name__ == "__main__": if __name__ == '__main__': main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else []) <commit_msg>Remove a redundant if and fix a syntax error<commit_after>import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return else: Handler(host=host, name=name, channels=channels) if __name__ == "__main__": main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
1d4ac6431e91b04a5a11bd7add78c512e3fe68d8
aiodocker/jsonstream.py
aiodocker/jsonstream.py
import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: try: data = await self.response.content.readline() if not data: break except (aiohttp.errors.ClientDisconnectedError, aiohttp.errors.ServerDisconnectedError): break yield self.transform(json.loads(data.decode('utf8'))) async def close(self): await self.response.release() async def json_stream_result(response, transform=None, stream=True): json_stream = JsonStreamResult(response, transform) if stream: return json_stream data = [] async for obj in json_stream.fetch(): data.append(obj) return data
import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: try: data = await self.response.content.readline() if not data: break except (aiohttp.errors.ClientDisconnectedError, aiohttp.errors.ServerDisconnectedError): break yield self.transform(json.loads(data.decode('utf8'))) async def close(self): # response.release() indefinitely hangs because the server is sending # an infinite stream of messages. # (see https://github.com/KeepSafe/aiohttp/issues/739) await self.response.close() async def json_stream_result(response, transform=None, stream=True): json_stream = JsonStreamResult(response, transform) if stream: return json_stream data = [] async for obj in json_stream.fetch(): data.append(obj) return data
Fix indefinite hangs when closing streaming results.
Fix indefinite hangs when closing streaming results. * See https://github.com/KeepSafe/aiohttp/issues/739
Python
mit
paultag/aiodocker,gaopeiliang/aiodocker,barrachri/aiodocker,gaopeiliang/aiodocker,barrachri/aiodocker,gaopeiliang/aiodocker,barrachri/aiodocker
import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: try: data = await self.response.content.readline() if not data: break except (aiohttp.errors.ClientDisconnectedError, aiohttp.errors.ServerDisconnectedError): break yield self.transform(json.loads(data.decode('utf8'))) async def close(self): await self.response.release() async def json_stream_result(response, transform=None, stream=True): json_stream = JsonStreamResult(response, transform) if stream: return json_stream data = [] async for obj in json_stream.fetch(): data.append(obj) return data Fix indefinite hangs when closing streaming results. * See https://github.com/KeepSafe/aiohttp/issues/739
import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: try: data = await self.response.content.readline() if not data: break except (aiohttp.errors.ClientDisconnectedError, aiohttp.errors.ServerDisconnectedError): break yield self.transform(json.loads(data.decode('utf8'))) async def close(self): # response.release() indefinitely hangs because the server is sending # an infinite stream of messages. # (see https://github.com/KeepSafe/aiohttp/issues/739) await self.response.close() async def json_stream_result(response, transform=None, stream=True): json_stream = JsonStreamResult(response, transform) if stream: return json_stream data = [] async for obj in json_stream.fetch(): data.append(obj) return data
<commit_before>import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: try: data = await self.response.content.readline() if not data: break except (aiohttp.errors.ClientDisconnectedError, aiohttp.errors.ServerDisconnectedError): break yield self.transform(json.loads(data.decode('utf8'))) async def close(self): await self.response.release() async def json_stream_result(response, transform=None, stream=True): json_stream = JsonStreamResult(response, transform) if stream: return json_stream data = [] async for obj in json_stream.fetch(): data.append(obj) return data <commit_msg>Fix indefinite hangs when closing streaming results. * See https://github.com/KeepSafe/aiohttp/issues/739<commit_after>
import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: try: data = await self.response.content.readline() if not data: break except (aiohttp.errors.ClientDisconnectedError, aiohttp.errors.ServerDisconnectedError): break yield self.transform(json.loads(data.decode('utf8'))) async def close(self): # response.release() indefinitely hangs because the server is sending # an infinite stream of messages. # (see https://github.com/KeepSafe/aiohttp/issues/739) await self.response.close() async def json_stream_result(response, transform=None, stream=True): json_stream = JsonStreamResult(response, transform) if stream: return json_stream data = [] async for obj in json_stream.fetch(): data.append(obj) return data
import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: try: data = await self.response.content.readline() if not data: break except (aiohttp.errors.ClientDisconnectedError, aiohttp.errors.ServerDisconnectedError): break yield self.transform(json.loads(data.decode('utf8'))) async def close(self): await self.response.release() async def json_stream_result(response, transform=None, stream=True): json_stream = JsonStreamResult(response, transform) if stream: return json_stream data = [] async for obj in json_stream.fetch(): data.append(obj) return data Fix indefinite hangs when closing streaming results. * See https://github.com/KeepSafe/aiohttp/issues/739import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: try: data = await self.response.content.readline() if not data: break except (aiohttp.errors.ClientDisconnectedError, aiohttp.errors.ServerDisconnectedError): break yield self.transform(json.loads(data.decode('utf8'))) async def close(self): # response.release() indefinitely hangs because the server is sending # an infinite stream of messages. # (see https://github.com/KeepSafe/aiohttp/issues/739) await self.response.close() async def json_stream_result(response, transform=None, stream=True): json_stream = JsonStreamResult(response, transform) if stream: return json_stream data = [] async for obj in json_stream.fetch(): data.append(obj) return data
<commit_before>import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: try: data = await self.response.content.readline() if not data: break except (aiohttp.errors.ClientDisconnectedError, aiohttp.errors.ServerDisconnectedError): break yield self.transform(json.loads(data.decode('utf8'))) async def close(self): await self.response.release() async def json_stream_result(response, transform=None, stream=True): json_stream = JsonStreamResult(response, transform) if stream: return json_stream data = [] async for obj in json_stream.fetch(): data.append(obj) return data <commit_msg>Fix indefinite hangs when closing streaming results. * See https://github.com/KeepSafe/aiohttp/issues/739<commit_after>import asyncio import json import logging import aiohttp.errors log = logging.getLogger(__name__) class JsonStreamResult: def __init__(self, response, transform=None): self.response = response self.transform = transform or (lambda x: x) async def fetch(self): while True: try: data = await self.response.content.readline() if not data: break except (aiohttp.errors.ClientDisconnectedError, aiohttp.errors.ServerDisconnectedError): break yield self.transform(json.loads(data.decode('utf8'))) async def close(self): # response.release() indefinitely hangs because the server is sending # an infinite stream of messages. # (see https://github.com/KeepSafe/aiohttp/issues/739) await self.response.close() async def json_stream_result(response, transform=None, stream=True): json_stream = JsonStreamResult(response, transform) if stream: return json_stream data = [] async for obj in json_stream.fetch(): data.append(obj) return data
48267661a046f04ec2274b53919e013fe47bd9fd
enactiveagents/model/perceptionhandler.py
enactiveagents/model/perceptionhandler.py
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""
Document classes in the perception handler module.
Document classes in the perception handler module.
Python
mit
Beskhue/enactive-agents,Beskhue/enactive-agents,Beskhue/enactive-agents
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""Document classes in the perception handler module.
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""
<commit_before>""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""<commit_msg>Document classes in the perception handler module.<commit_after>
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""Document classes in the perception handler module.""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""
<commit_before>""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""<commit_msg>Document classes in the perception handler module.<commit_after>""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""
d50fecebfc9e4e94fc8c0dd0c848030bf5e1ae6c
analytics/middleware.py
analytics/middleware.py
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() visitor_uuid = request.COOKIES.get('visitor_uuid', False) if not visitor_uuid: response.set_cookie('visitor_uuid', str(uuid.uuid4())) params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() if 'visitor_uuid' not in request.session: request.session['visitor_uuid'] = uuid.uuid4().hex visitor_uuid = request.session['visitor_uuid'] params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response
Use session instead of cookie for tracking visitor UUID
Use session instead of cookie for tracking visitor UUID session ID is only recorded after this layer of middleware, hence the need for a new UUID
Python
bsd-2-clause
praekelt/nurseconnect,praekelt/nurseconnect,praekelt/nurseconnect
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() visitor_uuid = request.COOKIES.get('visitor_uuid', False) if not visitor_uuid: response.set_cookie('visitor_uuid', str(uuid.uuid4())) params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response Use session instead of cookie for tracking visitor UUID session ID is only recorded after this layer of middleware, hence the need for a new UUID
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() if 'visitor_uuid' not in request.session: request.session['visitor_uuid'] = uuid.uuid4().hex visitor_uuid = request.session['visitor_uuid'] params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response
<commit_before>import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() visitor_uuid = request.COOKIES.get('visitor_uuid', False) if not visitor_uuid: response.set_cookie('visitor_uuid', str(uuid.uuid4())) params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response <commit_msg>Use session instead of cookie for tracking visitor UUID session ID is only recorded after this layer of middleware, hence the need for a new UUID<commit_after>
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() if 'visitor_uuid' not in request.session: request.session['visitor_uuid'] = uuid.uuid4().hex visitor_uuid = request.session['visitor_uuid'] params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response
import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() visitor_uuid = request.COOKIES.get('visitor_uuid', False) if not visitor_uuid: response.set_cookie('visitor_uuid', str(uuid.uuid4())) params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response Use session instead of cookie for tracking visitor UUID session ID is only recorded after this layer of middleware, hence the need for a new UUIDimport uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() if 'visitor_uuid' not in request.session: request.session['visitor_uuid'] = uuid.uuid4().hex visitor_uuid = request.session['visitor_uuid'] params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response
<commit_before>import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() visitor_uuid = request.COOKIES.get('visitor_uuid', False) if not visitor_uuid: response.set_cookie('visitor_uuid', str(uuid.uuid4())) params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response <commit_msg>Use session instead of cookie for tracking visitor UUID session ID is only recorded after this layer of middleware, hence the need for a new UUID<commit_after>import uuid from django.conf import settings from django.utils import timezone from django.utils.deprecation import MiddlewareMixin from analytics.models import AnalyticsRecord from analytics.utils import ( should_ignore, status_code_invalid, get_tracking_params, ) class AnalyticsMiddleware(MiddlewareMixin): def process_response(self, request, response): if should_ignore(request) or status_code_invalid(response): return response timestamp = timezone.now() if 'visitor_uuid' not in request.session: request.session['visitor_uuid'] = uuid.uuid4().hex visitor_uuid = request.session['visitor_uuid'] params = get_tracking_params( request, response, timestamp, visitor_uuid) AnalyticsRecord.objects.create(**params) return response
6b07caaf86e0fbbf81c7b583ebd93c3ccfbd7c60
api/v2/serializers/details/project_application.py
api/v2/serializers/details/project_application.py
from core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Project.objects.all() def to_representation(self, value): project = Project.objects.get(pk=value.pk) serializer = ProjectSummarySerializer(project, context=self.context) return serializer.data class ApplicationRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Application.objects.all() def to_representation(self, value): application = Application.objects.get(pk=value.pk) serializer = ApplicationSerializer(application, context=self.context) return serializer.data class ProjectApplicationSerializer(serializers.HyperlinkedModelSerializer): project = ProjectRelatedField(queryset=Project.objects.none()) application = ApplicationRelatedField(queryset=Application.objects.none()) url = serializers.HyperlinkedIdentityField( view_name='api:v2:projectapplication-detail', ) class Meta: model = ProjectApplication fields = ( 'id', 'url', 'project', 'application' )
from core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Project.objects.all() def to_representation(self, value): project = Project.objects.get(pk=value.pk) serializer = ProjectSummarySerializer(project, context=self.context) return serializer.data class ApplicationRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Application.objects.all() def to_representation(self, value): application = Application.objects.get(pk=value.pk) serializer = ApplicationSerializer(application, context=self.context) return serializer.data class ProjectApplicationSerializer(serializers.HyperlinkedModelSerializer): project = ProjectRelatedField(queryset=Project.objects.none()) image = ApplicationRelatedField(queryset=Application.objects.none(), source='application') url = serializers.HyperlinkedIdentityField( view_name='api:v2:projectapplication-detail', ) class Meta: model = ProjectApplication fields = ( 'id', 'url', 'project', 'image' )
Rename 'public_fields' Application->Image to avoid confusion with the UI
Rename 'public_fields' Application->Image to avoid confusion with the UI
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
from core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Project.objects.all() def to_representation(self, value): project = Project.objects.get(pk=value.pk) serializer = ProjectSummarySerializer(project, context=self.context) return serializer.data class ApplicationRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Application.objects.all() def to_representation(self, value): application = Application.objects.get(pk=value.pk) serializer = ApplicationSerializer(application, context=self.context) return serializer.data class ProjectApplicationSerializer(serializers.HyperlinkedModelSerializer): project = ProjectRelatedField(queryset=Project.objects.none()) application = ApplicationRelatedField(queryset=Application.objects.none()) url = serializers.HyperlinkedIdentityField( view_name='api:v2:projectapplication-detail', ) class Meta: model = ProjectApplication fields = ( 'id', 'url', 'project', 'application' ) Rename 'public_fields' Application->Image to avoid confusion with the UI
from core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Project.objects.all() def to_representation(self, value): project = Project.objects.get(pk=value.pk) serializer = ProjectSummarySerializer(project, context=self.context) return serializer.data class ApplicationRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Application.objects.all() def to_representation(self, value): application = Application.objects.get(pk=value.pk) serializer = ApplicationSerializer(application, context=self.context) return serializer.data class ProjectApplicationSerializer(serializers.HyperlinkedModelSerializer): project = ProjectRelatedField(queryset=Project.objects.none()) image = ApplicationRelatedField(queryset=Application.objects.none(), source='application') url = serializers.HyperlinkedIdentityField( view_name='api:v2:projectapplication-detail', ) class Meta: model = ProjectApplication fields = ( 'id', 'url', 'project', 'image' )
<commit_before>from core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Project.objects.all() def to_representation(self, value): project = Project.objects.get(pk=value.pk) serializer = ProjectSummarySerializer(project, context=self.context) return serializer.data class ApplicationRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Application.objects.all() def to_representation(self, value): application = Application.objects.get(pk=value.pk) serializer = ApplicationSerializer(application, context=self.context) return serializer.data class ProjectApplicationSerializer(serializers.HyperlinkedModelSerializer): project = ProjectRelatedField(queryset=Project.objects.none()) application = ApplicationRelatedField(queryset=Application.objects.none()) url = serializers.HyperlinkedIdentityField( view_name='api:v2:projectapplication-detail', ) class Meta: model = ProjectApplication fields = ( 'id', 'url', 'project', 'application' ) <commit_msg>Rename 'public_fields' Application->Image to avoid confusion with the UI<commit_after>
from core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Project.objects.all() def to_representation(self, value): project = Project.objects.get(pk=value.pk) serializer = ProjectSummarySerializer(project, context=self.context) return serializer.data class ApplicationRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Application.objects.all() def to_representation(self, value): application = Application.objects.get(pk=value.pk) serializer = ApplicationSerializer(application, context=self.context) return serializer.data class ProjectApplicationSerializer(serializers.HyperlinkedModelSerializer): project = ProjectRelatedField(queryset=Project.objects.none()) image = ApplicationRelatedField(queryset=Application.objects.none(), source='application') url = serializers.HyperlinkedIdentityField( view_name='api:v2:projectapplication-detail', ) class Meta: model = ProjectApplication fields = ( 'id', 'url', 'project', 'image' )
from core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Project.objects.all() def to_representation(self, value): project = Project.objects.get(pk=value.pk) serializer = ProjectSummarySerializer(project, context=self.context) return serializer.data class ApplicationRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Application.objects.all() def to_representation(self, value): application = Application.objects.get(pk=value.pk) serializer = ApplicationSerializer(application, context=self.context) return serializer.data class ProjectApplicationSerializer(serializers.HyperlinkedModelSerializer): project = ProjectRelatedField(queryset=Project.objects.none()) application = ApplicationRelatedField(queryset=Application.objects.none()) url = serializers.HyperlinkedIdentityField( view_name='api:v2:projectapplication-detail', ) class Meta: model = ProjectApplication fields = ( 'id', 'url', 'project', 'application' ) Rename 'public_fields' Application->Image to avoid confusion with the UIfrom core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Project.objects.all() def to_representation(self, value): project = Project.objects.get(pk=value.pk) serializer = ProjectSummarySerializer(project, context=self.context) return serializer.data class ApplicationRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Application.objects.all() def to_representation(self, value): application = Application.objects.get(pk=value.pk) serializer = ApplicationSerializer(application, context=self.context) return serializer.data class ProjectApplicationSerializer(serializers.HyperlinkedModelSerializer): project = ProjectRelatedField(queryset=Project.objects.none()) image = ApplicationRelatedField(queryset=Application.objects.none(), source='application') url = serializers.HyperlinkedIdentityField( view_name='api:v2:projectapplication-detail', ) class Meta: model = ProjectApplication fields = ( 'id', 'url', 'project', 'image' )
<commit_before>from core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Project.objects.all() def to_representation(self, value): project = Project.objects.get(pk=value.pk) serializer = ProjectSummarySerializer(project, context=self.context) return serializer.data class ApplicationRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Application.objects.all() def to_representation(self, value): application = Application.objects.get(pk=value.pk) serializer = ApplicationSerializer(application, context=self.context) return serializer.data class ProjectApplicationSerializer(serializers.HyperlinkedModelSerializer): project = ProjectRelatedField(queryset=Project.objects.none()) application = ApplicationRelatedField(queryset=Application.objects.none()) url = serializers.HyperlinkedIdentityField( view_name='api:v2:projectapplication-detail', ) class Meta: model = ProjectApplication fields = ( 'id', 'url', 'project', 'application' ) <commit_msg>Rename 'public_fields' Application->Image to avoid confusion with the UI<commit_after>from core.models import ProjectApplication, Project, Application from rest_framework import serializers from api.v2.serializers.summaries import ProjectSummarySerializer from .application import ApplicationSerializer class ProjectRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Project.objects.all() def to_representation(self, value): project = Project.objects.get(pk=value.pk) serializer = ProjectSummarySerializer(project, context=self.context) return serializer.data class ApplicationRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Application.objects.all() def to_representation(self, value): application = Application.objects.get(pk=value.pk) serializer = ApplicationSerializer(application, context=self.context) return serializer.data class ProjectApplicationSerializer(serializers.HyperlinkedModelSerializer): project = ProjectRelatedField(queryset=Project.objects.none()) image = ApplicationRelatedField(queryset=Application.objects.none(), source='application') url = serializers.HyperlinkedIdentityField( view_name='api:v2:projectapplication-detail', ) class Meta: model = ProjectApplication fields = ( 'id', 'url', 'project', 'image' )
07c36f71850c5b9a2fc7a56e2b3cedeb833f83ab
oxyio/settings/__init__.py
oxyio/settings/__init__.py
# oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name): from importlib import import_module settings_module = import_module(name) self.apply_attrs(settings_module) def apply_attrs(self, module): for key in [name for name in dir(module) if name.isupper()]: setattr(self, key, getattr(module, key)) sys.modules[__name__] = OxyioSettings()
# oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name): # The sys.modules hack below breaks the import from importlib import import_module settings_module = import_module(name) self.apply_attrs(settings_module) def apply_attrs(self, module): for key in [name for name in dir(module) if name.isupper()]: setattr(self, key, getattr(module, key)) sys.modules[__name__] = OxyioSettings()
Add comment about import in function.
Add comment about import in function.
Python
mit
oxyio/oxyio,oxyio/oxyio,oxyio/oxyio,oxyio/oxyio
# oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name): from importlib import import_module settings_module = import_module(name) self.apply_attrs(settings_module) def apply_attrs(self, module): for key in [name for name in dir(module) if name.isupper()]: setattr(self, key, getattr(module, key)) sys.modules[__name__] = OxyioSettings() Add comment about import in function.
# oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name): # The sys.modules hack below breaks the import from importlib import import_module settings_module = import_module(name) self.apply_attrs(settings_module) def apply_attrs(self, module): for key in [name for name in dir(module) if name.isupper()]: setattr(self, key, getattr(module, key)) sys.modules[__name__] = OxyioSettings()
<commit_before># oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name): from importlib import import_module settings_module = import_module(name) self.apply_attrs(settings_module) def apply_attrs(self, module): for key in [name for name in dir(module) if name.isupper()]: setattr(self, key, getattr(module, key)) sys.modules[__name__] = OxyioSettings() <commit_msg>Add comment about import in function.<commit_after>
# oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name): # The sys.modules hack below breaks the import from importlib import import_module settings_module = import_module(name) self.apply_attrs(settings_module) def apply_attrs(self, module): for key in [name for name in dir(module) if name.isupper()]: setattr(self, key, getattr(module, key)) sys.modules[__name__] = OxyioSettings()
# oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name): from importlib import import_module settings_module = import_module(name) self.apply_attrs(settings_module) def apply_attrs(self, module): for key in [name for name in dir(module) if name.isupper()]: setattr(self, key, getattr(module, key)) sys.modules[__name__] = OxyioSettings() Add comment about import in function.# oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name): # The sys.modules hack below breaks the import from importlib import import_module settings_module = import_module(name) self.apply_attrs(settings_module) def apply_attrs(self, module): for key in [name for name in dir(module) if name.isupper()]: setattr(self, key, getattr(module, key)) sys.modules[__name__] = OxyioSettings()
<commit_before># oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name): from importlib import import_module settings_module = import_module(name) self.apply_attrs(settings_module) def apply_attrs(self, module): for key in [name for name in dir(module) if name.isupper()]: setattr(self, key, getattr(module, key)) sys.modules[__name__] = OxyioSettings() <commit_msg>Add comment about import in function.<commit_after># oxy.io # File: oxyio/settings/__init__.py # Desc: settings classmodule allowing for defaults + modules applied at runtime import sys from . import defaults class OxyioSettings(object): def __init__(self): # Apply the defaults to this self.apply_attrs(defaults) def load_module(self, name): # The sys.modules hack below breaks the import from importlib import import_module settings_module = import_module(name) self.apply_attrs(settings_module) def apply_attrs(self, module): for key in [name for name in dir(module) if name.isupper()]: setattr(self, key, getattr(module, key)) sys.modules[__name__] = OxyioSettings()
4d3ba43ae00833ca19c5945285050af342b00046
abelfunctions/__init__.py
abelfunctions/__init__.py
""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .riemann_surface import RiemannSurface from .riemanntheta import RiemannTheta
""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .puiseux import puiseux from .riemann_surface import RiemannSurface from .riemanntheta import RiemannTheta
Include puiseux.puiseux in global namespace
Include puiseux.puiseux in global namespace Because it's useful, we include puiseux.puiseux() in the project __init__.py.
Python
mit
abelfunctions/abelfunctions,cswiercz/abelfunctions,abelfunctions/abelfunctions,cswiercz/abelfunctions,cswiercz/abelfunctions,abelfunctions/abelfunctions
""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .riemann_surface import RiemannSurface from .riemanntheta import RiemannTheta Include puiseux.puiseux in global namespace Because it's useful, we include puiseux.puiseux() in the project __init__.py.
""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .puiseux import puiseux from .riemann_surface import RiemannSurface from .riemanntheta import RiemannTheta
<commit_before>""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .riemann_surface import RiemannSurface from .riemanntheta import RiemannTheta <commit_msg>Include puiseux.puiseux in global namespace Because it's useful, we include puiseux.puiseux() in the project __init__.py.<commit_after>
""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .puiseux import puiseux from .riemann_surface import RiemannSurface from .riemanntheta import RiemannTheta
""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .riemann_surface import RiemannSurface from .riemanntheta import RiemannTheta Include puiseux.puiseux in global namespace Because it's useful, we include puiseux.puiseux() in the project __init__.py.""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .puiseux import puiseux from .riemann_surface import RiemannSurface from .riemanntheta import RiemannTheta
<commit_before>""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .riemann_surface import RiemannSurface from .riemanntheta import RiemannTheta <commit_msg>Include puiseux.puiseux in global namespace Because it's useful, we include puiseux.puiseux() in the project __init__.py.<commit_after>""" abelfunctions is a Python library for computing with Abelian functions, algebraic curves, and solving integrable Partial Differential Equations. The code is available as a git repository at https://github.com/cswiercz/abelfunctions """ from .abelmap import AbelMap, Jacobian from .puiseux import puiseux from .riemann_surface import RiemannSurface from .riemanntheta import RiemannTheta
968247875e0be421205a924a8d1325c0c9aeb2c6
zebra/forms.py
zebra/forms.py
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.error_class([message]) class CardForm(MonospaceForm): last_4_digits = forms.CharField(required=True, min_length=4, max_length=4, widget=forms.HiddenInput() ) stripe_token = forms.CharField(required=True, widget=forms.HiddenInput()) class StripePaymentForm(CardForm): card_number = forms.CharField(required=False, max_length=20, widget=NoNameTextInput()) card_cvv = forms.CharField(required=False, max_length=4, widget=NoNameTextInput()) card_expiry_month = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=MONTHS.iteritems()) card_expiry_year = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=options.ZEBRA_CARD_YEARS_CHOICES)
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.error_class([message]) class CardForm(MonospaceForm): last_4_digits = forms.CharField(required=True, min_length=4, max_length=4, widget=forms.HiddenInput() ) stripe_token = forms.CharField(required=True, widget=forms.HiddenInput()) class StripePaymentForm(CardForm): def __init__(self, *args, **kwargs): super(StripePaymentForm, self).__init__(*args, **kwargs) self.fields['card_cvv'].label = "Card CVV" self.fields['card_cvv'].help_text = "Card Verification Code; see rear of card." months = [ (m[0], u'%02d - %s' % (m[0], unicode(m[1]))) for m in sorted(MONTHS.iteritems()) ] self.fields['card_expiry_month'].choices = months card_number = forms.CharField(required=False, max_length=20, widget=NoNameTextInput()) card_cvv = forms.CharField(required=False, max_length=4, widget=NoNameTextInput()) card_expiry_month = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=MONTHS.iteritems()) card_expiry_year = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=options.ZEBRA_CARD_YEARS_CHOICES)
Improve end-user labels, values, help text.
Improve end-user labels, values, help text.
Python
mit
amjoconn/django-zebra,GoodCloud/django-zebra,blag/django-zebra,blag/django-zebra,gumob/django-stripe,gumob/django-stripe,amjoconn/django-zebra,gumob/django-stripe,blag/django-zebra,amjoconn/django-zebra,GoodCloud/django-zebra
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.error_class([message]) class CardForm(MonospaceForm): last_4_digits = forms.CharField(required=True, min_length=4, max_length=4, widget=forms.HiddenInput() ) stripe_token = forms.CharField(required=True, widget=forms.HiddenInput()) class StripePaymentForm(CardForm): card_number = forms.CharField(required=False, max_length=20, widget=NoNameTextInput()) card_cvv = forms.CharField(required=False, max_length=4, widget=NoNameTextInput()) card_expiry_month = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=MONTHS.iteritems()) card_expiry_year = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=options.ZEBRA_CARD_YEARS_CHOICES) Improve end-user labels, values, help text.
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.error_class([message]) class CardForm(MonospaceForm): last_4_digits = forms.CharField(required=True, min_length=4, max_length=4, widget=forms.HiddenInput() ) stripe_token = forms.CharField(required=True, widget=forms.HiddenInput()) class StripePaymentForm(CardForm): def __init__(self, *args, **kwargs): super(StripePaymentForm, self).__init__(*args, **kwargs) self.fields['card_cvv'].label = "Card CVV" self.fields['card_cvv'].help_text = "Card Verification Code; see rear of card." months = [ (m[0], u'%02d - %s' % (m[0], unicode(m[1]))) for m in sorted(MONTHS.iteritems()) ] self.fields['card_expiry_month'].choices = months card_number = forms.CharField(required=False, max_length=20, widget=NoNameTextInput()) card_cvv = forms.CharField(required=False, max_length=4, widget=NoNameTextInput()) card_expiry_month = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=MONTHS.iteritems()) card_expiry_year = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=options.ZEBRA_CARD_YEARS_CHOICES)
<commit_before>from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.error_class([message]) class CardForm(MonospaceForm): last_4_digits = forms.CharField(required=True, min_length=4, max_length=4, widget=forms.HiddenInput() ) stripe_token = forms.CharField(required=True, widget=forms.HiddenInput()) class StripePaymentForm(CardForm): card_number = forms.CharField(required=False, max_length=20, widget=NoNameTextInput()) card_cvv = forms.CharField(required=False, max_length=4, widget=NoNameTextInput()) card_expiry_month = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=MONTHS.iteritems()) card_expiry_year = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=options.ZEBRA_CARD_YEARS_CHOICES) <commit_msg>Improve end-user labels, values, help text.<commit_after>
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.error_class([message]) class CardForm(MonospaceForm): last_4_digits = forms.CharField(required=True, min_length=4, max_length=4, widget=forms.HiddenInput() ) stripe_token = forms.CharField(required=True, widget=forms.HiddenInput()) class StripePaymentForm(CardForm): def __init__(self, *args, **kwargs): super(StripePaymentForm, self).__init__(*args, **kwargs) self.fields['card_cvv'].label = "Card CVV" self.fields['card_cvv'].help_text = "Card Verification Code; see rear of card." months = [ (m[0], u'%02d - %s' % (m[0], unicode(m[1]))) for m in sorted(MONTHS.iteritems()) ] self.fields['card_expiry_month'].choices = months card_number = forms.CharField(required=False, max_length=20, widget=NoNameTextInput()) card_cvv = forms.CharField(required=False, max_length=4, widget=NoNameTextInput()) card_expiry_month = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=MONTHS.iteritems()) card_expiry_year = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=options.ZEBRA_CARD_YEARS_CHOICES)
from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.error_class([message]) class CardForm(MonospaceForm): last_4_digits = forms.CharField(required=True, min_length=4, max_length=4, widget=forms.HiddenInput() ) stripe_token = forms.CharField(required=True, widget=forms.HiddenInput()) class StripePaymentForm(CardForm): card_number = forms.CharField(required=False, max_length=20, widget=NoNameTextInput()) card_cvv = forms.CharField(required=False, max_length=4, widget=NoNameTextInput()) card_expiry_month = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=MONTHS.iteritems()) card_expiry_year = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=options.ZEBRA_CARD_YEARS_CHOICES) Improve end-user labels, values, help text.from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.error_class([message]) class CardForm(MonospaceForm): last_4_digits = forms.CharField(required=True, min_length=4, max_length=4, widget=forms.HiddenInput() ) stripe_token = forms.CharField(required=True, widget=forms.HiddenInput()) class StripePaymentForm(CardForm): def __init__(self, *args, **kwargs): super(StripePaymentForm, self).__init__(*args, **kwargs) self.fields['card_cvv'].label = "Card CVV" self.fields['card_cvv'].help_text = "Card Verification Code; see rear of card." months = [ (m[0], u'%02d - %s' % (m[0], unicode(m[1]))) for m in sorted(MONTHS.iteritems()) ] self.fields['card_expiry_month'].choices = months card_number = forms.CharField(required=False, max_length=20, widget=NoNameTextInput()) card_cvv = forms.CharField(required=False, max_length=4, widget=NoNameTextInput()) card_expiry_month = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=MONTHS.iteritems()) card_expiry_year = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=options.ZEBRA_CARD_YEARS_CHOICES)
<commit_before>from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.error_class([message]) class CardForm(MonospaceForm): last_4_digits = forms.CharField(required=True, min_length=4, max_length=4, widget=forms.HiddenInput() ) stripe_token = forms.CharField(required=True, widget=forms.HiddenInput()) class StripePaymentForm(CardForm): card_number = forms.CharField(required=False, max_length=20, widget=NoNameTextInput()) card_cvv = forms.CharField(required=False, max_length=4, widget=NoNameTextInput()) card_expiry_month = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=MONTHS.iteritems()) card_expiry_year = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=options.ZEBRA_CARD_YEARS_CHOICES) <commit_msg>Improve end-user labels, values, help text.<commit_after>from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.utils.dates import MONTHS from zebra.conf import options from zebra.widgets import NoNameSelect, NoNameTextInput class MonospaceForm(forms.Form): def addError(self, message): self._errors[NON_FIELD_ERRORS] = self.error_class([message]) class CardForm(MonospaceForm): last_4_digits = forms.CharField(required=True, min_length=4, max_length=4, widget=forms.HiddenInput() ) stripe_token = forms.CharField(required=True, widget=forms.HiddenInput()) class StripePaymentForm(CardForm): def __init__(self, *args, **kwargs): super(StripePaymentForm, self).__init__(*args, **kwargs) self.fields['card_cvv'].label = "Card CVV" self.fields['card_cvv'].help_text = "Card Verification Code; see rear of card." months = [ (m[0], u'%02d - %s' % (m[0], unicode(m[1]))) for m in sorted(MONTHS.iteritems()) ] self.fields['card_expiry_month'].choices = months card_number = forms.CharField(required=False, max_length=20, widget=NoNameTextInput()) card_cvv = forms.CharField(required=False, max_length=4, widget=NoNameTextInput()) card_expiry_month = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=MONTHS.iteritems()) card_expiry_year = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=options.ZEBRA_CARD_YEARS_CHOICES)
b30ba90aec5b7e6e4fa875ce7fb24b0135d9b0ef
tools/skp/page_sets/skia_googlespreadsheet_desktop.py
tools/skp/page_sets/skia_googlespreadsheet_desktop.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_googlespreadsheet_desktop.json' def RunNavigateSteps(self, action_runner): action_runner.Navigate(self.url) action_runner.Wait(15) class SkiaGooglespreadsheetDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaGooglespreadsheetDesktopPageSet, self).__init__( archive_data_file='data/skia_googlespreadsheet_desktop.json') urls_list = [ # Why: from Tom W's list. ('https://docs.google.com/spreadsheets/d/' '1YnmSPu-p-1nj-lkWd8q_GRgzjiWzg_6A-HvFYqVoVxI/edit#gid=0'), ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self))
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_googlespreadsheet_desktop.json' class SkiaGooglespreadsheetDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaGooglespreadsheetDesktopPageSet, self).__init__( archive_data_file='data/skia_googlespreadsheet_desktop.json') urls_list = [ # Why: from Tom W's list. ('https://docs.google.com/spreadsheets/d/' '1YnmSPu-p-1nj-lkWd8q_GRgzjiWzg_6A-HvFYqVoVxI/edit#gid=0'), ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self))
Fix spreadsheets page set for RecreateSKPs bot
Fix spreadsheets page set for RecreateSKPs bot NoTry: true Bug: skia:9380 Change-Id: Iab05b1baab58032a8053242fd2a8b6e8799c35cc Reviewed-on: https://skia-review.googlesource.com/c/skia/+/238037 Reviewed-by: Eric Boren <0e499112533c8544f0505ea0d08394fb5ad7d8fa@google.com> Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com>
Python
bsd-3-clause
HalCanary/skia-hc,google/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,google/skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,google/skia,aosp-mirror/platform_external_skia,google/skia,HalCanary/skia-hc,HalCanary/skia-hc,HalCanary/skia-hc,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,HalCanary/skia-hc,google/skia,aosp-mirror/platform_external_skia
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_googlespreadsheet_desktop.json' def RunNavigateSteps(self, action_runner): action_runner.Navigate(self.url) action_runner.Wait(15) class SkiaGooglespreadsheetDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaGooglespreadsheetDesktopPageSet, self).__init__( archive_data_file='data/skia_googlespreadsheet_desktop.json') urls_list = [ # Why: from Tom W's list. ('https://docs.google.com/spreadsheets/d/' '1YnmSPu-p-1nj-lkWd8q_GRgzjiWzg_6A-HvFYqVoVxI/edit#gid=0'), ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self)) Fix spreadsheets page set for RecreateSKPs bot NoTry: true Bug: skia:9380 Change-Id: Iab05b1baab58032a8053242fd2a8b6e8799c35cc Reviewed-on: https://skia-review.googlesource.com/c/skia/+/238037 Reviewed-by: Eric Boren <0e499112533c8544f0505ea0d08394fb5ad7d8fa@google.com> Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com>
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_googlespreadsheet_desktop.json' class SkiaGooglespreadsheetDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaGooglespreadsheetDesktopPageSet, self).__init__( archive_data_file='data/skia_googlespreadsheet_desktop.json') urls_list = [ # Why: from Tom W's list. ('https://docs.google.com/spreadsheets/d/' '1YnmSPu-p-1nj-lkWd8q_GRgzjiWzg_6A-HvFYqVoVxI/edit#gid=0'), ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self))
<commit_before># Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_googlespreadsheet_desktop.json' def RunNavigateSteps(self, action_runner): action_runner.Navigate(self.url) action_runner.Wait(15) class SkiaGooglespreadsheetDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaGooglespreadsheetDesktopPageSet, self).__init__( archive_data_file='data/skia_googlespreadsheet_desktop.json') urls_list = [ # Why: from Tom W's list. ('https://docs.google.com/spreadsheets/d/' '1YnmSPu-p-1nj-lkWd8q_GRgzjiWzg_6A-HvFYqVoVxI/edit#gid=0'), ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self)) <commit_msg>Fix spreadsheets page set for RecreateSKPs bot NoTry: true Bug: skia:9380 Change-Id: Iab05b1baab58032a8053242fd2a8b6e8799c35cc Reviewed-on: https://skia-review.googlesource.com/c/skia/+/238037 Reviewed-by: Eric Boren <0e499112533c8544f0505ea0d08394fb5ad7d8fa@google.com> Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com><commit_after>
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_googlespreadsheet_desktop.json' class SkiaGooglespreadsheetDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaGooglespreadsheetDesktopPageSet, self).__init__( archive_data_file='data/skia_googlespreadsheet_desktop.json') urls_list = [ # Why: from Tom W's list. ('https://docs.google.com/spreadsheets/d/' '1YnmSPu-p-1nj-lkWd8q_GRgzjiWzg_6A-HvFYqVoVxI/edit#gid=0'), ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self))
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_googlespreadsheet_desktop.json' def RunNavigateSteps(self, action_runner): action_runner.Navigate(self.url) action_runner.Wait(15) class SkiaGooglespreadsheetDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaGooglespreadsheetDesktopPageSet, self).__init__( archive_data_file='data/skia_googlespreadsheet_desktop.json') urls_list = [ # Why: from Tom W's list. ('https://docs.google.com/spreadsheets/d/' '1YnmSPu-p-1nj-lkWd8q_GRgzjiWzg_6A-HvFYqVoVxI/edit#gid=0'), ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self)) Fix spreadsheets page set for RecreateSKPs bot NoTry: true Bug: skia:9380 Change-Id: Iab05b1baab58032a8053242fd2a8b6e8799c35cc Reviewed-on: https://skia-review.googlesource.com/c/skia/+/238037 Reviewed-by: Eric Boren <0e499112533c8544f0505ea0d08394fb5ad7d8fa@google.com> Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com># Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_googlespreadsheet_desktop.json' class SkiaGooglespreadsheetDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaGooglespreadsheetDesktopPageSet, self).__init__( archive_data_file='data/skia_googlespreadsheet_desktop.json') urls_list = [ # Why: from Tom W's list. ('https://docs.google.com/spreadsheets/d/' '1YnmSPu-p-1nj-lkWd8q_GRgzjiWzg_6A-HvFYqVoVxI/edit#gid=0'), ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self))
<commit_before># Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_googlespreadsheet_desktop.json' def RunNavigateSteps(self, action_runner): action_runner.Navigate(self.url) action_runner.Wait(15) class SkiaGooglespreadsheetDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaGooglespreadsheetDesktopPageSet, self).__init__( archive_data_file='data/skia_googlespreadsheet_desktop.json') urls_list = [ # Why: from Tom W's list. ('https://docs.google.com/spreadsheets/d/' '1YnmSPu-p-1nj-lkWd8q_GRgzjiWzg_6A-HvFYqVoVxI/edit#gid=0'), ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self)) <commit_msg>Fix spreadsheets page set for RecreateSKPs bot NoTry: true Bug: skia:9380 Change-Id: Iab05b1baab58032a8053242fd2a8b6e8799c35cc Reviewed-on: https://skia-review.googlesource.com/c/skia/+/238037 Reviewed-by: Eric Boren <0e499112533c8544f0505ea0d08394fb5ad7d8fa@google.com> Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com><commit_after># Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry import story from telemetry.page import page as page_module from telemetry.page import shared_page_state class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, name=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) self.archive_data_file = 'data/skia_googlespreadsheet_desktop.json' class SkiaGooglespreadsheetDesktopPageSet(story.StorySet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaGooglespreadsheetDesktopPageSet, self).__init__( archive_data_file='data/skia_googlespreadsheet_desktop.json') urls_list = [ # Why: from Tom W's list. ('https://docs.google.com/spreadsheets/d/' '1YnmSPu-p-1nj-lkWd8q_GRgzjiWzg_6A-HvFYqVoVxI/edit#gid=0'), ] for url in urls_list: self.AddStory(SkiaBuildbotDesktopPage(url, self))
3cd3aa7b5f6a04a6d25d0f919c7dc38aa6c2a499
raven/contrib/django/__init__.py
raven/contrib/django/__init__.py
""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from .client import *
""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from raven.contrib.django.client import *
Switch to absolute import for Python 2.5 (fixes GH-64)
Switch to absolute import for Python 2.5 (fixes GH-64)
Python
bsd-3-clause
ewdurbin/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,akalipetis/raven-python,recht/raven-python,arthurlogilab/raven-python,dirtycoder/opbeat_python,someonehan/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,hzy/raven-python,dbravender/raven-python,danriti/raven-python,percipient/raven-python,Photonomie/raven-python,percipient/raven-python,ewdurbin/raven-python,patrys/opbeat_python,jmagnusson/raven-python,akheron/raven-python,jmp0xf/raven-python,recht/raven-python,arthurlogilab/raven-python,patrys/opbeat_python,inspirehep/raven-python,Photonomie/raven-python,jmagnusson/raven-python,inspirehep/raven-python,daikeren/opbeat_python,beniwohli/apm-agent-python,arthurlogilab/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,daikeren/opbeat_python,lepture/raven-python,inspirehep/raven-python,danriti/raven-python,getsentry/raven-python,collective/mr.poe,icereval/raven-python,nikolas/raven-python,smarkets/raven-python,jbarbuto/raven-python,johansteffner/raven-python,hzy/raven-python,tarkatronic/opbeat_python,percipient/raven-python,alex/raven,hzy/raven-python,nikolas/raven-python,johansteffner/raven-python,lepture/raven-python,ronaldevers/raven-python,icereval/raven-python,jmp0xf/raven-python,lopter/raven-python-old,patrys/opbeat_python,daikeren/opbeat_python,jbarbuto/raven-python,smarkets/raven-python,danriti/raven-python,dbravender/raven-python,icereval/raven-python,akheron/raven-python,someonehan/raven-python,smarkets/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,arthurlogilab/raven-python,beniwohli/apm-agent-python,nikolas/raven-python,lepture/raven-python,tarkatronic/opbeat_python,beniwohli/apm-agent-python,getsentry/raven-python,johansteffner/raven-python,akalipetis/raven-python,openlabs/raven,ticosax/opbeat_python,jmagnusson/raven-python,nikolas/raven-python,ronaldevers/raven-python,akalipetis/raven-python,ronaldevers/raven-python,tarkatronic/opbeat_python,jmp0xf/raven-python,dbravender/raven-python,getsentry/raven-python,smarkets/raven-python,inspirehep/raven-python,Photonomie/raven-python,ticosax/opbeat_python,someonehan/raven-python,ewdurbin/raven-python,ticosax/opbeat_python,patrys/opbeat_python,beniwohli/apm-agent-python,icereval/raven-python,recht/raven-python,jbarbuto/raven-python,akheron/raven-python,dirtycoder/opbeat_python,jbarbuto/raven-python,dirtycoder/opbeat_python
""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from .client import * Switch to absolute import for Python 2.5 (fixes GH-64)
""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from raven.contrib.django.client import *
<commit_before>""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from .client import * <commit_msg>Switch to absolute import for Python 2.5 (fixes GH-64)<commit_after>
""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from raven.contrib.django.client import *
""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from .client import * Switch to absolute import for Python 2.5 (fixes GH-64)""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from raven.contrib.django.client import *
<commit_before>""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from .client import * <commit_msg>Switch to absolute import for Python 2.5 (fixes GH-64)<commit_after>""" raven.contrib.django ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from raven.contrib.django.client import *
4418f448e3c7d8a3b12e5e45038fd5a0ef6b6d07
ectyper/subprocess_util.py
ectyper/subprocess_util.py
#!/usr/bin/env python import logging import subprocess import timeit LOG = logging.getLogger(__name__) def run_subprocess(cmd, input_data=None, un=False): """ Run cmd command on subprocess Args: cmd (str): cmd command Returns: stdout (str): The stdout of cmd """ start_time = timeit.default_timer() comp_proc = subprocess.run( cmd, shell=False, input = input_data, check=False, universal_newlines=un, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if comp_proc.returncode == 0: elapsed_time = timeit.default_timer() - start_time LOG.debug("Subprocess {} finished successfully in {:0.3f} sec.".format(cmd, elapsed_time)) return comp_proc else: LOG.error("Error in subprocess. The following command failed: {}".format(cmd)) LOG.error("Subprocess failed with error: ".format(comp_proc.stderr)) LOG.critical("ectyper has stopped") exit("subprocess failure")
#!/usr/bin/env python import logging import subprocess import timeit LOG = logging.getLogger(__name__) def run_subprocess(cmd, input_data=None, un=False): """ Run cmd command on subprocess Args: cmd (str): cmd command Returns: stdout (str): The stdout of cmd """ start_time = timeit.default_timer() comp_proc = subprocess.run( cmd, shell=False, input = input_data, check=False, universal_newlines=un, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if comp_proc.returncode == 0: elapsed_time = timeit.default_timer() - start_time LOG.debug("Subprocess {} finished successfully in {:0.3f} sec.".format(cmd, elapsed_time)) return comp_proc else: LOG.error("Error in subprocess. The following command failed: {}".format(cmd)) LOG.error("Subprocess failed with error: {}".format(comp_proc.stderr)) LOG.critical("ectyper has stopped") exit("subprocess failure")
Include error message in debug.
Include error message in debug.
Python
apache-2.0
phac-nml/ecoli_serotyping
#!/usr/bin/env python import logging import subprocess import timeit LOG = logging.getLogger(__name__) def run_subprocess(cmd, input_data=None, un=False): """ Run cmd command on subprocess Args: cmd (str): cmd command Returns: stdout (str): The stdout of cmd """ start_time = timeit.default_timer() comp_proc = subprocess.run( cmd, shell=False, input = input_data, check=False, universal_newlines=un, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if comp_proc.returncode == 0: elapsed_time = timeit.default_timer() - start_time LOG.debug("Subprocess {} finished successfully in {:0.3f} sec.".format(cmd, elapsed_time)) return comp_proc else: LOG.error("Error in subprocess. The following command failed: {}".format(cmd)) LOG.error("Subprocess failed with error: ".format(comp_proc.stderr)) LOG.critical("ectyper has stopped") exit("subprocess failure") Include error message in debug.
#!/usr/bin/env python import logging import subprocess import timeit LOG = logging.getLogger(__name__) def run_subprocess(cmd, input_data=None, un=False): """ Run cmd command on subprocess Args: cmd (str): cmd command Returns: stdout (str): The stdout of cmd """ start_time = timeit.default_timer() comp_proc = subprocess.run( cmd, shell=False, input = input_data, check=False, universal_newlines=un, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if comp_proc.returncode == 0: elapsed_time = timeit.default_timer() - start_time LOG.debug("Subprocess {} finished successfully in {:0.3f} sec.".format(cmd, elapsed_time)) return comp_proc else: LOG.error("Error in subprocess. The following command failed: {}".format(cmd)) LOG.error("Subprocess failed with error: {}".format(comp_proc.stderr)) LOG.critical("ectyper has stopped") exit("subprocess failure")
<commit_before>#!/usr/bin/env python import logging import subprocess import timeit LOG = logging.getLogger(__name__) def run_subprocess(cmd, input_data=None, un=False): """ Run cmd command on subprocess Args: cmd (str): cmd command Returns: stdout (str): The stdout of cmd """ start_time = timeit.default_timer() comp_proc = subprocess.run( cmd, shell=False, input = input_data, check=False, universal_newlines=un, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if comp_proc.returncode == 0: elapsed_time = timeit.default_timer() - start_time LOG.debug("Subprocess {} finished successfully in {:0.3f} sec.".format(cmd, elapsed_time)) return comp_proc else: LOG.error("Error in subprocess. The following command failed: {}".format(cmd)) LOG.error("Subprocess failed with error: ".format(comp_proc.stderr)) LOG.critical("ectyper has stopped") exit("subprocess failure") <commit_msg>Include error message in debug.<commit_after>
#!/usr/bin/env python import logging import subprocess import timeit LOG = logging.getLogger(__name__) def run_subprocess(cmd, input_data=None, un=False): """ Run cmd command on subprocess Args: cmd (str): cmd command Returns: stdout (str): The stdout of cmd """ start_time = timeit.default_timer() comp_proc = subprocess.run( cmd, shell=False, input = input_data, check=False, universal_newlines=un, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if comp_proc.returncode == 0: elapsed_time = timeit.default_timer() - start_time LOG.debug("Subprocess {} finished successfully in {:0.3f} sec.".format(cmd, elapsed_time)) return comp_proc else: LOG.error("Error in subprocess. The following command failed: {}".format(cmd)) LOG.error("Subprocess failed with error: {}".format(comp_proc.stderr)) LOG.critical("ectyper has stopped") exit("subprocess failure")
#!/usr/bin/env python import logging import subprocess import timeit LOG = logging.getLogger(__name__) def run_subprocess(cmd, input_data=None, un=False): """ Run cmd command on subprocess Args: cmd (str): cmd command Returns: stdout (str): The stdout of cmd """ start_time = timeit.default_timer() comp_proc = subprocess.run( cmd, shell=False, input = input_data, check=False, universal_newlines=un, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if comp_proc.returncode == 0: elapsed_time = timeit.default_timer() - start_time LOG.debug("Subprocess {} finished successfully in {:0.3f} sec.".format(cmd, elapsed_time)) return comp_proc else: LOG.error("Error in subprocess. The following command failed: {}".format(cmd)) LOG.error("Subprocess failed with error: ".format(comp_proc.stderr)) LOG.critical("ectyper has stopped") exit("subprocess failure") Include error message in debug.#!/usr/bin/env python import logging import subprocess import timeit LOG = logging.getLogger(__name__) def run_subprocess(cmd, input_data=None, un=False): """ Run cmd command on subprocess Args: cmd (str): cmd command Returns: stdout (str): The stdout of cmd """ start_time = timeit.default_timer() comp_proc = subprocess.run( cmd, shell=False, input = input_data, check=False, universal_newlines=un, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if comp_proc.returncode == 0: elapsed_time = timeit.default_timer() - start_time LOG.debug("Subprocess {} finished successfully in {:0.3f} sec.".format(cmd, elapsed_time)) return comp_proc else: LOG.error("Error in subprocess. The following command failed: {}".format(cmd)) LOG.error("Subprocess failed with error: {}".format(comp_proc.stderr)) LOG.critical("ectyper has stopped") exit("subprocess failure")
<commit_before>#!/usr/bin/env python import logging import subprocess import timeit LOG = logging.getLogger(__name__) def run_subprocess(cmd, input_data=None, un=False): """ Run cmd command on subprocess Args: cmd (str): cmd command Returns: stdout (str): The stdout of cmd """ start_time = timeit.default_timer() comp_proc = subprocess.run( cmd, shell=False, input = input_data, check=False, universal_newlines=un, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if comp_proc.returncode == 0: elapsed_time = timeit.default_timer() - start_time LOG.debug("Subprocess {} finished successfully in {:0.3f} sec.".format(cmd, elapsed_time)) return comp_proc else: LOG.error("Error in subprocess. The following command failed: {}".format(cmd)) LOG.error("Subprocess failed with error: ".format(comp_proc.stderr)) LOG.critical("ectyper has stopped") exit("subprocess failure") <commit_msg>Include error message in debug.<commit_after>#!/usr/bin/env python import logging import subprocess import timeit LOG = logging.getLogger(__name__) def run_subprocess(cmd, input_data=None, un=False): """ Run cmd command on subprocess Args: cmd (str): cmd command Returns: stdout (str): The stdout of cmd """ start_time = timeit.default_timer() comp_proc = subprocess.run( cmd, shell=False, input = input_data, check=False, universal_newlines=un, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) if comp_proc.returncode == 0: elapsed_time = timeit.default_timer() - start_time LOG.debug("Subprocess {} finished successfully in {:0.3f} sec.".format(cmd, elapsed_time)) return comp_proc else: LOG.error("Error in subprocess. The following command failed: {}".format(cmd)) LOG.error("Subprocess failed with error: {}".format(comp_proc.stderr)) LOG.critical("ectyper has stopped") exit("subprocess failure")
8f96c4e1852edb1ec2c35733611e86b4d89abf1a
legislators/urls.py
legislators/urls.py
from . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>(.*))/$', views.legislator_detail, name='legislator_detail') ]
from . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator, name="find_legislator"), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>(.*))/$', views.legislator_detail, name='legislator_detail') ]
Add name to legislator detail page
Add name to legislator detail page
Python
mit
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
from . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>(.*))/$', views.legislator_detail, name='legislator_detail') ] Add name to legislator detail page
from . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator, name="find_legislator"), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>(.*))/$', views.legislator_detail, name='legislator_detail') ]
<commit_before>from . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>(.*))/$', views.legislator_detail, name='legislator_detail') ] <commit_msg>Add name to legislator detail page<commit_after>
from . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator, name="find_legislator"), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>(.*))/$', views.legislator_detail, name='legislator_detail') ]
from . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>(.*))/$', views.legislator_detail, name='legislator_detail') ] Add name to legislator detail pagefrom . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator, name="find_legislator"), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>(.*))/$', views.legislator_detail, name='legislator_detail') ]
<commit_before>from . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>(.*))/$', views.legislator_detail, name='legislator_detail') ] <commit_msg>Add name to legislator detail page<commit_after>from . import views from django.conf.urls import url urlpatterns = [ url(r'^find_legislator/', views.find_legislator, name="find_legislator"), url(r'^get_latlon/', views.get_latlon, name="get_latlon"), url(r'^latest_latlon/', views.latest_latlon, name="latest_latlon"), url(r'^detail/(?P<legislator_id>(.*))/$', views.legislator_detail, name='legislator_detail') ]
8d86d70739cbd4640faf17ca28686c3b04d5ec9c
migrations/versions/0336_broadcast_msg_content_2.py
migrations/versions/0336_broadcast_msg_content_2.py
""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): session = Session(bind=op.get_bind()) broadcast_messages = session.query(BroadcastMessage).filter(BroadcastMessage.content == None) for broadcast_message in broadcast_messages: broadcast_message.content = broadcast_message.template._as_utils_template_with_personalisation( broadcast_message.personalisation ).content_with_placeholders_filled_in session.commit() op.alter_column('broadcast_message', 'content', nullable=False) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True)
""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from notifications_utils.template import BroadcastMessageTemplate from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): conn = op.get_bind() results = conn.execute(sa.text(""" UPDATE broadcast_message SET content = templates_history.content FROM templates_history WHERE broadcast_message.content is NULL and broadcast_message.template_id = templates_history.id and broadcast_message.template_version = templates_history.version ; """)) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True)
Rewrite previous migration in raw SQL
Rewrite previous migration in raw SQL We shouldn’t import models into migrations because if the model changes later down the line then the migration can’t be re-run at a later date (for example to rebuild a database from scratch). We don’t need to encode the content before storing it (we’ll always do that before rendering/sending) so we don’t need to use `BroadcastMessageTemplate`. And given that no past broadcasts will have personalisation, we don’t need to replace the personalisation in the template before rendering it. So we can just copy the raw content from the templates table.
Python
mit
alphagov/notifications-api,alphagov/notifications-api
""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): session = Session(bind=op.get_bind()) broadcast_messages = session.query(BroadcastMessage).filter(BroadcastMessage.content == None) for broadcast_message in broadcast_messages: broadcast_message.content = broadcast_message.template._as_utils_template_with_personalisation( broadcast_message.personalisation ).content_with_placeholders_filled_in session.commit() op.alter_column('broadcast_message', 'content', nullable=False) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True) Rewrite previous migration in raw SQL We shouldn’t import models into migrations because if the model changes later down the line then the migration can’t be re-run at a later date (for example to rebuild a database from scratch). We don’t need to encode the content before storing it (we’ll always do that before rendering/sending) so we don’t need to use `BroadcastMessageTemplate`. And given that no past broadcasts will have personalisation, we don’t need to replace the personalisation in the template before rendering it. So we can just copy the raw content from the templates table.
""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from notifications_utils.template import BroadcastMessageTemplate from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): conn = op.get_bind() results = conn.execute(sa.text(""" UPDATE broadcast_message SET content = templates_history.content FROM templates_history WHERE broadcast_message.content is NULL and broadcast_message.template_id = templates_history.id and broadcast_message.template_version = templates_history.version ; """)) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True)
<commit_before>""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): session = Session(bind=op.get_bind()) broadcast_messages = session.query(BroadcastMessage).filter(BroadcastMessage.content == None) for broadcast_message in broadcast_messages: broadcast_message.content = broadcast_message.template._as_utils_template_with_personalisation( broadcast_message.personalisation ).content_with_placeholders_filled_in session.commit() op.alter_column('broadcast_message', 'content', nullable=False) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True) <commit_msg>Rewrite previous migration in raw SQL We shouldn’t import models into migrations because if the model changes later down the line then the migration can’t be re-run at a later date (for example to rebuild a database from scratch). We don’t need to encode the content before storing it (we’ll always do that before rendering/sending) so we don’t need to use `BroadcastMessageTemplate`. And given that no past broadcasts will have personalisation, we don’t need to replace the personalisation in the template before rendering it. So we can just copy the raw content from the templates table.<commit_after>
""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from notifications_utils.template import BroadcastMessageTemplate from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): conn = op.get_bind() results = conn.execute(sa.text(""" UPDATE broadcast_message SET content = templates_history.content FROM templates_history WHERE broadcast_message.content is NULL and broadcast_message.template_id = templates_history.id and broadcast_message.template_version = templates_history.version ; """)) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True)
""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): session = Session(bind=op.get_bind()) broadcast_messages = session.query(BroadcastMessage).filter(BroadcastMessage.content == None) for broadcast_message in broadcast_messages: broadcast_message.content = broadcast_message.template._as_utils_template_with_personalisation( broadcast_message.personalisation ).content_with_placeholders_filled_in session.commit() op.alter_column('broadcast_message', 'content', nullable=False) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True) Rewrite previous migration in raw SQL We shouldn’t import models into migrations because if the model changes later down the line then the migration can’t be re-run at a later date (for example to rebuild a database from scratch). We don’t need to encode the content before storing it (we’ll always do that before rendering/sending) so we don’t need to use `BroadcastMessageTemplate`. And given that no past broadcasts will have personalisation, we don’t need to replace the personalisation in the template before rendering it. So we can just copy the raw content from the templates table.""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from notifications_utils.template import BroadcastMessageTemplate from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): conn = op.get_bind() results = conn.execute(sa.text(""" UPDATE broadcast_message SET content = templates_history.content FROM templates_history WHERE broadcast_message.content is NULL and broadcast_message.template_id = templates_history.id and broadcast_message.template_version = templates_history.version ; """)) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True)
<commit_before>""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): session = Session(bind=op.get_bind()) broadcast_messages = session.query(BroadcastMessage).filter(BroadcastMessage.content == None) for broadcast_message in broadcast_messages: broadcast_message.content = broadcast_message.template._as_utils_template_with_personalisation( broadcast_message.personalisation ).content_with_placeholders_filled_in session.commit() op.alter_column('broadcast_message', 'content', nullable=False) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True) <commit_msg>Rewrite previous migration in raw SQL We shouldn’t import models into migrations because if the model changes later down the line then the migration can’t be re-run at a later date (for example to rebuild a database from scratch). We don’t need to encode the content before storing it (we’ll always do that before rendering/sending) so we don’t need to use `BroadcastMessageTemplate`. And given that no past broadcasts will have personalisation, we don’t need to replace the personalisation in the template before rendering it. So we can just copy the raw content from the templates table.<commit_after>""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from notifications_utils.template import BroadcastMessageTemplate from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): conn = op.get_bind() results = conn.execute(sa.text(""" UPDATE broadcast_message SET content = templates_history.content FROM templates_history WHERE broadcast_message.content is NULL and broadcast_message.template_id = templates_history.id and broadcast_message.template_version = templates_history.version ; """)) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True)
0529c91443fa2948514a21933de00f4c146c9764
data_api/snapshot_scheduler/src/test_snapshot_scheduler.py
data_api/snapshot_scheduler/src/test_snapshot_scheduler.py
# -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def test_writes_message_to_sqs(sns_client, topic_arn): private_bucket_name = "private_bucket_name" es_index = "es_index" patched_os_environ = { 'TOPIC_ARN': topic_arn, 'TARGET_BUCKET_NAME': private_bucket_name, 'ES_INDEX': es_index } with patch.dict(os.environ, patched_os_environ, clear=True): snapshot_scheduler.main( event=None, _ctxt=None, sns_client=sns_client ) messages = sns_client.list_messages() assert len(messages) == 1 assert messages[0][':message'] == { 'time': '2011-06-21T00:00:00', 'private_bucket_name': private_bucket_name, 'es_index': es_index }
# -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def test_writes_message_to_sqs(sns_client, topic_arn): private_bucket_name = "private_bucket_name" es_index = "es_index" patched_os_environ = { 'TOPIC_ARN': topic_arn, 'PRIVATE_BUCKET_NAME': private_bucket_name, 'ES_INDEX': es_index } with patch.dict(os.environ, patched_os_environ, clear=True): snapshot_scheduler.main(sns_client=sns_client) messages = sns_client.list_messages() assert len(messages) == 1 assert messages[0][':message'] == { 'time': '2011-06-21T00:00:00', 'private_bucket_name': private_bucket_name, 'es_index': es_index }
Use the correctly named env vars
snapshot_scheduler: Use the correctly named env vars
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
# -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def test_writes_message_to_sqs(sns_client, topic_arn): private_bucket_name = "private_bucket_name" es_index = "es_index" patched_os_environ = { 'TOPIC_ARN': topic_arn, 'TARGET_BUCKET_NAME': private_bucket_name, 'ES_INDEX': es_index } with patch.dict(os.environ, patched_os_environ, clear=True): snapshot_scheduler.main( event=None, _ctxt=None, sns_client=sns_client ) messages = sns_client.list_messages() assert len(messages) == 1 assert messages[0][':message'] == { 'time': '2011-06-21T00:00:00', 'private_bucket_name': private_bucket_name, 'es_index': es_index } snapshot_scheduler: Use the correctly named env vars
# -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def test_writes_message_to_sqs(sns_client, topic_arn): private_bucket_name = "private_bucket_name" es_index = "es_index" patched_os_environ = { 'TOPIC_ARN': topic_arn, 'PRIVATE_BUCKET_NAME': private_bucket_name, 'ES_INDEX': es_index } with patch.dict(os.environ, patched_os_environ, clear=True): snapshot_scheduler.main(sns_client=sns_client) messages = sns_client.list_messages() assert len(messages) == 1 assert messages[0][':message'] == { 'time': '2011-06-21T00:00:00', 'private_bucket_name': private_bucket_name, 'es_index': es_index }
<commit_before># -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def test_writes_message_to_sqs(sns_client, topic_arn): private_bucket_name = "private_bucket_name" es_index = "es_index" patched_os_environ = { 'TOPIC_ARN': topic_arn, 'TARGET_BUCKET_NAME': private_bucket_name, 'ES_INDEX': es_index } with patch.dict(os.environ, patched_os_environ, clear=True): snapshot_scheduler.main( event=None, _ctxt=None, sns_client=sns_client ) messages = sns_client.list_messages() assert len(messages) == 1 assert messages[0][':message'] == { 'time': '2011-06-21T00:00:00', 'private_bucket_name': private_bucket_name, 'es_index': es_index } <commit_msg>snapshot_scheduler: Use the correctly named env vars<commit_after>
# -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def test_writes_message_to_sqs(sns_client, topic_arn): private_bucket_name = "private_bucket_name" es_index = "es_index" patched_os_environ = { 'TOPIC_ARN': topic_arn, 'PRIVATE_BUCKET_NAME': private_bucket_name, 'ES_INDEX': es_index } with patch.dict(os.environ, patched_os_environ, clear=True): snapshot_scheduler.main(sns_client=sns_client) messages = sns_client.list_messages() assert len(messages) == 1 assert messages[0][':message'] == { 'time': '2011-06-21T00:00:00', 'private_bucket_name': private_bucket_name, 'es_index': es_index }
# -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def test_writes_message_to_sqs(sns_client, topic_arn): private_bucket_name = "private_bucket_name" es_index = "es_index" patched_os_environ = { 'TOPIC_ARN': topic_arn, 'TARGET_BUCKET_NAME': private_bucket_name, 'ES_INDEX': es_index } with patch.dict(os.environ, patched_os_environ, clear=True): snapshot_scheduler.main( event=None, _ctxt=None, sns_client=sns_client ) messages = sns_client.list_messages() assert len(messages) == 1 assert messages[0][':message'] == { 'time': '2011-06-21T00:00:00', 'private_bucket_name': private_bucket_name, 'es_index': es_index } snapshot_scheduler: Use the correctly named env vars# -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def test_writes_message_to_sqs(sns_client, topic_arn): private_bucket_name = "private_bucket_name" es_index = "es_index" patched_os_environ = { 'TOPIC_ARN': topic_arn, 'PRIVATE_BUCKET_NAME': private_bucket_name, 'ES_INDEX': es_index } with patch.dict(os.environ, patched_os_environ, clear=True): snapshot_scheduler.main(sns_client=sns_client) messages = sns_client.list_messages() assert len(messages) == 1 assert messages[0][':message'] == { 'time': '2011-06-21T00:00:00', 'private_bucket_name': private_bucket_name, 'es_index': es_index }
<commit_before># -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def test_writes_message_to_sqs(sns_client, topic_arn): private_bucket_name = "private_bucket_name" es_index = "es_index" patched_os_environ = { 'TOPIC_ARN': topic_arn, 'TARGET_BUCKET_NAME': private_bucket_name, 'ES_INDEX': es_index } with patch.dict(os.environ, patched_os_environ, clear=True): snapshot_scheduler.main( event=None, _ctxt=None, sns_client=sns_client ) messages = sns_client.list_messages() assert len(messages) == 1 assert messages[0][':message'] == { 'time': '2011-06-21T00:00:00', 'private_bucket_name': private_bucket_name, 'es_index': es_index } <commit_msg>snapshot_scheduler: Use the correctly named env vars<commit_after># -*- encoding: utf-8 -*- import datetime as dt import os import mock from unittest.mock import patch import snapshot_scheduler class patched_datetime(dt.datetime): @classmethod def utcnow(cls): return dt.datetime(2011, 6, 21, 0, 0, 0, 0) @mock.patch('datetime.datetime', patched_datetime) def test_writes_message_to_sqs(sns_client, topic_arn): private_bucket_name = "private_bucket_name" es_index = "es_index" patched_os_environ = { 'TOPIC_ARN': topic_arn, 'PRIVATE_BUCKET_NAME': private_bucket_name, 'ES_INDEX': es_index } with patch.dict(os.environ, patched_os_environ, clear=True): snapshot_scheduler.main(sns_client=sns_client) messages = sns_client.list_messages() assert len(messages) == 1 assert messages[0][':message'] == { 'time': '2011-06-21T00:00:00', 'private_bucket_name': private_bucket_name, 'es_index': es_index }
82fa5d8997aac1e975a8a499773f772b77824a57
ztag/test/updater_test.py
ztag/test/updater_test.py
import unittest import StringIO from ztag.stream import Updater, UpdateRow class UpdaterTestCase(unittest.TestCase): FREQUENCY = 1.0 def setUp(self): pass def test_updater(self): """ Check that the updater runs as expected. """ output = StringIO.StringIO() updater = Updater(output=output, frequency=self.FREQUENCY) skipped = 0 handled = 0 expected = [UpdateRow.get_csv_labels()] for i in range(0, 100000): skipped += 1 handled += 2 row = UpdateRow( skipped=skipped, handled=handled, time=float(i) / 100.0, prev=updater.prev) if not updater.prev or (row.time - updater.prev.time) >= updater.frequency: expected.append(row.get_csv()) updater.put_update(row) self.assertEquals("\n".join(expected) + "\n", output.getvalue()) updater.close()
import unittest import StringIO from ztag.stream import Updater, UpdateRow class UpdaterTestCase(unittest.TestCase): FREQUENCY = 1.0 def setUp(self): pass def test_updater(self): """ Check that the updater runs as expected. """ output = StringIO.StringIO() updater = Updater(output=output, frequency=self.FREQUENCY) skipped = 0 handled = 0 expected = [UpdateRow.get_csv_labels()] for i in range(0, 100000): skipped += 1 handled += 2 row = UpdateRow( skipped=skipped, handled=handled, updated_at=float(i) / 100.0, prev=updater.prev) if not updater.prev or (row.time - updater.prev.time) >= updater.frequency: expected.append(row.get_csv()) updater.put_update(row) self.assertEquals("\n".join(expected) + "\n", output.getvalue()) updater.close()
Fix test - s/time/updated_at/ named param
Fix test - s/time/updated_at/ named param
Python
apache-2.0
zmap/ztag
import unittest import StringIO from ztag.stream import Updater, UpdateRow class UpdaterTestCase(unittest.TestCase): FREQUENCY = 1.0 def setUp(self): pass def test_updater(self): """ Check that the updater runs as expected. """ output = StringIO.StringIO() updater = Updater(output=output, frequency=self.FREQUENCY) skipped = 0 handled = 0 expected = [UpdateRow.get_csv_labels()] for i in range(0, 100000): skipped += 1 handled += 2 row = UpdateRow( skipped=skipped, handled=handled, time=float(i) / 100.0, prev=updater.prev) if not updater.prev or (row.time - updater.prev.time) >= updater.frequency: expected.append(row.get_csv()) updater.put_update(row) self.assertEquals("\n".join(expected) + "\n", output.getvalue()) updater.close() Fix test - s/time/updated_at/ named param
import unittest import StringIO from ztag.stream import Updater, UpdateRow class UpdaterTestCase(unittest.TestCase): FREQUENCY = 1.0 def setUp(self): pass def test_updater(self): """ Check that the updater runs as expected. """ output = StringIO.StringIO() updater = Updater(output=output, frequency=self.FREQUENCY) skipped = 0 handled = 0 expected = [UpdateRow.get_csv_labels()] for i in range(0, 100000): skipped += 1 handled += 2 row = UpdateRow( skipped=skipped, handled=handled, updated_at=float(i) / 100.0, prev=updater.prev) if not updater.prev or (row.time - updater.prev.time) >= updater.frequency: expected.append(row.get_csv()) updater.put_update(row) self.assertEquals("\n".join(expected) + "\n", output.getvalue()) updater.close()
<commit_before>import unittest import StringIO from ztag.stream import Updater, UpdateRow class UpdaterTestCase(unittest.TestCase): FREQUENCY = 1.0 def setUp(self): pass def test_updater(self): """ Check that the updater runs as expected. """ output = StringIO.StringIO() updater = Updater(output=output, frequency=self.FREQUENCY) skipped = 0 handled = 0 expected = [UpdateRow.get_csv_labels()] for i in range(0, 100000): skipped += 1 handled += 2 row = UpdateRow( skipped=skipped, handled=handled, time=float(i) / 100.0, prev=updater.prev) if not updater.prev or (row.time - updater.prev.time) >= updater.frequency: expected.append(row.get_csv()) updater.put_update(row) self.assertEquals("\n".join(expected) + "\n", output.getvalue()) updater.close() <commit_msg>Fix test - s/time/updated_at/ named param<commit_after>
import unittest import StringIO from ztag.stream import Updater, UpdateRow class UpdaterTestCase(unittest.TestCase): FREQUENCY = 1.0 def setUp(self): pass def test_updater(self): """ Check that the updater runs as expected. """ output = StringIO.StringIO() updater = Updater(output=output, frequency=self.FREQUENCY) skipped = 0 handled = 0 expected = [UpdateRow.get_csv_labels()] for i in range(0, 100000): skipped += 1 handled += 2 row = UpdateRow( skipped=skipped, handled=handled, updated_at=float(i) / 100.0, prev=updater.prev) if not updater.prev or (row.time - updater.prev.time) >= updater.frequency: expected.append(row.get_csv()) updater.put_update(row) self.assertEquals("\n".join(expected) + "\n", output.getvalue()) updater.close()
import unittest import StringIO from ztag.stream import Updater, UpdateRow class UpdaterTestCase(unittest.TestCase): FREQUENCY = 1.0 def setUp(self): pass def test_updater(self): """ Check that the updater runs as expected. """ output = StringIO.StringIO() updater = Updater(output=output, frequency=self.FREQUENCY) skipped = 0 handled = 0 expected = [UpdateRow.get_csv_labels()] for i in range(0, 100000): skipped += 1 handled += 2 row = UpdateRow( skipped=skipped, handled=handled, time=float(i) / 100.0, prev=updater.prev) if not updater.prev or (row.time - updater.prev.time) >= updater.frequency: expected.append(row.get_csv()) updater.put_update(row) self.assertEquals("\n".join(expected) + "\n", output.getvalue()) updater.close() Fix test - s/time/updated_at/ named paramimport unittest import StringIO from ztag.stream import Updater, UpdateRow class UpdaterTestCase(unittest.TestCase): FREQUENCY = 1.0 def setUp(self): pass def test_updater(self): """ Check that the updater runs as expected. """ output = StringIO.StringIO() updater = Updater(output=output, frequency=self.FREQUENCY) skipped = 0 handled = 0 expected = [UpdateRow.get_csv_labels()] for i in range(0, 100000): skipped += 1 handled += 2 row = UpdateRow( skipped=skipped, handled=handled, updated_at=float(i) / 100.0, prev=updater.prev) if not updater.prev or (row.time - updater.prev.time) >= updater.frequency: expected.append(row.get_csv()) updater.put_update(row) self.assertEquals("\n".join(expected) + "\n", output.getvalue()) updater.close()
<commit_before>import unittest import StringIO from ztag.stream import Updater, UpdateRow class UpdaterTestCase(unittest.TestCase): FREQUENCY = 1.0 def setUp(self): pass def test_updater(self): """ Check that the updater runs as expected. """ output = StringIO.StringIO() updater = Updater(output=output, frequency=self.FREQUENCY) skipped = 0 handled = 0 expected = [UpdateRow.get_csv_labels()] for i in range(0, 100000): skipped += 1 handled += 2 row = UpdateRow( skipped=skipped, handled=handled, time=float(i) / 100.0, prev=updater.prev) if not updater.prev or (row.time - updater.prev.time) >= updater.frequency: expected.append(row.get_csv()) updater.put_update(row) self.assertEquals("\n".join(expected) + "\n", output.getvalue()) updater.close() <commit_msg>Fix test - s/time/updated_at/ named param<commit_after>import unittest import StringIO from ztag.stream import Updater, UpdateRow class UpdaterTestCase(unittest.TestCase): FREQUENCY = 1.0 def setUp(self): pass def test_updater(self): """ Check that the updater runs as expected. """ output = StringIO.StringIO() updater = Updater(output=output, frequency=self.FREQUENCY) skipped = 0 handled = 0 expected = [UpdateRow.get_csv_labels()] for i in range(0, 100000): skipped += 1 handled += 2 row = UpdateRow( skipped=skipped, handled=handled, updated_at=float(i) / 100.0, prev=updater.prev) if not updater.prev or (row.time - updater.prev.time) >= updater.frequency: expected.append(row.get_csv()) updater.put_update(row) self.assertEquals("\n".join(expected) + "\n", output.getvalue()) updater.close()
31567cb5663affebfa5fa6e3c3a07e9ad5e61aa3
admin/common_auth/forms.py
admin/common_auth/forms.py
from __future__ import absolute_import from django import forms from django.db.models import Q from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(Q(name__startswith='collections_') | Q(name__startswith='reviews_') | Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_')), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
from __future__ import absolute_import from django import forms from django.db.models import Q from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(Q(name__startswith='collections_') | Q(name__startswith='reviews_') | Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_') | Q(name__startswith='draft_registration_')), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
Exclude DraftRegistration Groups from admin form
Exclude DraftRegistration Groups from admin form
Python
apache-2.0
mfraezz/osf.io,Johnetordoff/osf.io,adlius/osf.io,adlius/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,felliott/osf.io,baylee-d/osf.io,mfraezz/osf.io,aaxelb/osf.io,adlius/osf.io,brianjgeiger/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,baylee-d/osf.io,aaxelb/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,cslzchen/osf.io,mfraezz/osf.io,cslzchen/osf.io,felliott/osf.io,baylee-d/osf.io,adlius/osf.io,felliott/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,Johnetordoff/osf.io
from __future__ import absolute_import from django import forms from django.db.models import Q from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(Q(name__startswith='collections_') | Q(name__startswith='reviews_') | Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_')), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret'] Exclude DraftRegistration Groups from admin form
from __future__ import absolute_import from django import forms from django.db.models import Q from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(Q(name__startswith='collections_') | Q(name__startswith='reviews_') | Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_') | Q(name__startswith='draft_registration_')), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
<commit_before>from __future__ import absolute_import from django import forms from django.db.models import Q from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(Q(name__startswith='collections_') | Q(name__startswith='reviews_') | Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_')), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret'] <commit_msg>Exclude DraftRegistration Groups from admin form<commit_after>
from __future__ import absolute_import from django import forms from django.db.models import Q from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(Q(name__startswith='collections_') | Q(name__startswith='reviews_') | Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_') | Q(name__startswith='draft_registration_')), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
from __future__ import absolute_import from django import forms from django.db.models import Q from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(Q(name__startswith='collections_') | Q(name__startswith='reviews_') | Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_')), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret'] Exclude DraftRegistration Groups from admin formfrom __future__ import absolute_import from django import forms from django.db.models import Q from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(Q(name__startswith='collections_') | Q(name__startswith='reviews_') | Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_') | Q(name__startswith='draft_registration_')), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
<commit_before>from __future__ import absolute_import from django import forms from django.db.models import Q from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(Q(name__startswith='collections_') | Q(name__startswith='reviews_') | Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_')), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret'] <commit_msg>Exclude DraftRegistration Groups from admin form<commit_after>from __future__ import absolute_import from django import forms from django.db.models import Q from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(Q(name__startswith='collections_') | Q(name__startswith='reviews_') | Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_') | Q(name__startswith='draft_registration_')), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
ae4ad35270a5daaa58b4988820da9d342d8e4751
examples/basic_example.py
examples/basic_example.py
# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot('Charlie') # Get a response to the input text 'How are you?' response = chatbot.get_response('How are you?') print(response)
# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot( 'Charlie', trainer='chatterbot.trainers.ListTrainer' ) chatbot.train([ "Hi, can I help you?", "Sure, I'd to book a flight to Iceland.", "Your flight has been booked." ]) # Get a response to the input text 'How are you?' response = chatbot.get_response('I would like to book a flight.') print(response)
Add training to basic example
Add training to basic example
Python
bsd-3-clause
vkosuri/ChatterBot,gunthercox/ChatterBot
# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot('Charlie') # Get a response to the input text 'How are you?' response = chatbot.get_response('How are you?') print(response) Add training to basic example
# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot( 'Charlie', trainer='chatterbot.trainers.ListTrainer' ) chatbot.train([ "Hi, can I help you?", "Sure, I'd to book a flight to Iceland.", "Your flight has been booked." ]) # Get a response to the input text 'How are you?' response = chatbot.get_response('I would like to book a flight.') print(response)
<commit_before># -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot('Charlie') # Get a response to the input text 'How are you?' response = chatbot.get_response('How are you?') print(response) <commit_msg>Add training to basic example<commit_after>
# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot( 'Charlie', trainer='chatterbot.trainers.ListTrainer' ) chatbot.train([ "Hi, can I help you?", "Sure, I'd to book a flight to Iceland.", "Your flight has been booked." ]) # Get a response to the input text 'How are you?' response = chatbot.get_response('I would like to book a flight.') print(response)
# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot('Charlie') # Get a response to the input text 'How are you?' response = chatbot.get_response('How are you?') print(response) Add training to basic example# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot( 'Charlie', trainer='chatterbot.trainers.ListTrainer' ) chatbot.train([ "Hi, can I help you?", "Sure, I'd to book a flight to Iceland.", "Your flight has been booked." ]) # Get a response to the input text 'How are you?' response = chatbot.get_response('I would like to book a flight.') print(response)
<commit_before># -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot('Charlie') # Get a response to the input text 'How are you?' response = chatbot.get_response('How are you?') print(response) <commit_msg>Add training to basic example<commit_after># -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot( 'Charlie', trainer='chatterbot.trainers.ListTrainer' ) chatbot.train([ "Hi, can I help you?", "Sure, I'd to book a flight to Iceland.", "Your flight has been booked." ]) # Get a response to the input text 'How are you?' response = chatbot.get_response('I would like to book a flight.') print(response)
93f2ed85d32efd88f38b3b123bc99e6afe120ae3
apps/payment/appconfig.py
apps/payment/appconfig.py
from django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentPrice, PaymentTransaction reversion.register(PaymentPrice) reversion.register(PaymentTransaction)
from django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentTransaction reversion.register(PaymentTransaction)
Fix registering for already registered model
Fix registering for already registered model
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
from django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentPrice, PaymentTransaction reversion.register(PaymentPrice) reversion.register(PaymentTransaction) Fix registering for already registered model
from django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentTransaction reversion.register(PaymentTransaction)
<commit_before>from django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentPrice, PaymentTransaction reversion.register(PaymentPrice) reversion.register(PaymentTransaction) <commit_msg>Fix registering for already registered model<commit_after>
from django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentTransaction reversion.register(PaymentTransaction)
from django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentPrice, PaymentTransaction reversion.register(PaymentPrice) reversion.register(PaymentTransaction) Fix registering for already registered modelfrom django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentTransaction reversion.register(PaymentTransaction)
<commit_before>from django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentPrice, PaymentTransaction reversion.register(PaymentPrice) reversion.register(PaymentTransaction) <commit_msg>Fix registering for already registered model<commit_after>from django.apps import AppConfig class PaymentConfig(AppConfig): name = 'apps.payment' verbose_name = 'Payment' def ready(self): super(PaymentConfig, self).ready() from reversion import revisions as reversion from apps.payment.models import PaymentTransaction reversion.register(PaymentTransaction)
bab2056ea9e47eec1d0bd15f86ff9cf08f8dbafc
tweets/tasks.py
tweets/tasks.py
from datetime import timedelta from django.conf import settings from django.core.management import call_command from celery.task import periodic_task @periodic_task(run_every=timedelta(minutes=settings.TWEET_INTERVAL_MINUTES)) def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False)
from django.core.management import call_command from celery import shared_task @shared_task() def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False)
Use shared_task instead of deprecated periodic_task
Use shared_task instead of deprecated periodic_task
Python
mit
gwhigs/tweeter,gwhigs/tweeter,gwhigs/tweeter,gwhigs/tweeter
from datetime import timedelta from django.conf import settings from django.core.management import call_command from celery.task import periodic_task @periodic_task(run_every=timedelta(minutes=settings.TWEET_INTERVAL_MINUTES)) def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False) Use shared_task instead of deprecated periodic_task
from django.core.management import call_command from celery import shared_task @shared_task() def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False)
<commit_before>from datetime import timedelta from django.conf import settings from django.core.management import call_command from celery.task import periodic_task @periodic_task(run_every=timedelta(minutes=settings.TWEET_INTERVAL_MINUTES)) def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False) <commit_msg>Use shared_task instead of deprecated periodic_task<commit_after>
from django.core.management import call_command from celery import shared_task @shared_task() def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False)
from datetime import timedelta from django.conf import settings from django.core.management import call_command from celery.task import periodic_task @periodic_task(run_every=timedelta(minutes=settings.TWEET_INTERVAL_MINUTES)) def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False) Use shared_task instead of deprecated periodic_taskfrom django.core.management import call_command from celery import shared_task @shared_task() def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False)
<commit_before>from datetime import timedelta from django.conf import settings from django.core.management import call_command from celery.task import periodic_task @periodic_task(run_every=timedelta(minutes=settings.TWEET_INTERVAL_MINUTES)) def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False) <commit_msg>Use shared_task instead of deprecated periodic_task<commit_after>from django.core.management import call_command from celery import shared_task @shared_task() def tweet_next_task(): call_command('tweet_next', verbose=True, interactive=False)
556545432af2b6d7d2c04e97fb86be308069d03a
plugins/backtothefuture.py
plugins/backtothefuture.py
"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt = p.parse(datestr)[0] return 'http://www.itsbacktothefutureday.com/images/{year}/{month}/{day}.jpg'.format(year=dt.tm_year, month=dt.tm_mon, day=dt.tm_mday) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0])
"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import time import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt, result = p.parse(datestr) if result == 0: return "I'm not eating that bogus date." if not isinstance(dt, time.struct_time): if len(dt) != 9: return 'Could not extrapolate date values from parsed date. Your date smells bogus.' dt = time.struct_time(dt) year, month, day = dt.tm_year, dt.tm_mon, dt.tm_mday return 'http://www.itsbacktothefutureday.com/images/{year}/{month:02d}/{day:02d}.jpg'.format(year=year, month=month, day=day) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0])
Fix some bugs with date parsing, as well as zero pad month and day in URL
Fix some bugs with date parsing, as well as zero pad month and day in URL
Python
mit
akatrevorjay/slask,kesre/slask,joshshadowfax/slask
"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt = p.parse(datestr)[0] return 'http://www.itsbacktothefutureday.com/images/{year}/{month}/{day}.jpg'.format(year=dt.tm_year, month=dt.tm_mon, day=dt.tm_mday) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0]) Fix some bugs with date parsing, as well as zero pad month and day in URL
"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import time import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt, result = p.parse(datestr) if result == 0: return "I'm not eating that bogus date." if not isinstance(dt, time.struct_time): if len(dt) != 9: return 'Could not extrapolate date values from parsed date. Your date smells bogus.' dt = time.struct_time(dt) year, month, day = dt.tm_year, dt.tm_mon, dt.tm_mday return 'http://www.itsbacktothefutureday.com/images/{year}/{month:02d}/{day:02d}.jpg'.format(year=year, month=month, day=day) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0])
<commit_before>"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt = p.parse(datestr)[0] return 'http://www.itsbacktothefutureday.com/images/{year}/{month}/{day}.jpg'.format(year=dt.tm_year, month=dt.tm_mon, day=dt.tm_mday) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0]) <commit_msg>Fix some bugs with date parsing, as well as zero pad month and day in URL<commit_after>
"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import time import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt, result = p.parse(datestr) if result == 0: return "I'm not eating that bogus date." if not isinstance(dt, time.struct_time): if len(dt) != 9: return 'Could not extrapolate date values from parsed date. Your date smells bogus.' dt = time.struct_time(dt) year, month, day = dt.tm_year, dt.tm_mon, dt.tm_mday return 'http://www.itsbacktothefutureday.com/images/{year}/{month:02d}/{day:02d}.jpg'.format(year=year, month=month, day=day) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0])
"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt = p.parse(datestr)[0] return 'http://www.itsbacktothefutureday.com/images/{year}/{month}/{day}.jpg'.format(year=dt.tm_year, month=dt.tm_mon, day=dt.tm_mday) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0]) Fix some bugs with date parsing, as well as zero pad month and day in URL"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import time import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt, result = p.parse(datestr) if result == 0: return "I'm not eating that bogus date." if not isinstance(dt, time.struct_time): if len(dt) != 9: return 'Could not extrapolate date values from parsed date. Your date smells bogus.' dt = time.struct_time(dt) year, month, day = dt.tm_year, dt.tm_mon, dt.tm_mday return 'http://www.itsbacktothefutureday.com/images/{year}/{month:02d}/{day:02d}.jpg'.format(year=year, month=month, day=day) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0])
<commit_before>"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt = p.parse(datestr)[0] return 'http://www.itsbacktothefutureday.com/images/{year}/{month}/{day}.jpg'.format(year=dt.tm_year, month=dt.tm_mon, day=dt.tm_mday) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0]) <commit_msg>Fix some bugs with date parsing, as well as zero pad month and day in URL<commit_after>"""!backtothefuture <date> returns the delorean dashboard with the specified <date>""" import re import time import parsedatetime p = parsedatetime.Calendar() def backtothefutureday(datestr): dt, result = p.parse(datestr) if result == 0: return "I'm not eating that bogus date." if not isinstance(dt, time.struct_time): if len(dt) != 9: return 'Could not extrapolate date values from parsed date. Your date smells bogus.' dt = time.struct_time(dt) year, month, day = dt.tm_year, dt.tm_mon, dt.tm_mday return 'http://www.itsbacktothefutureday.com/images/{year}/{month:02d}/{day:02d}.jpg'.format(year=year, month=month, day=day) def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!backtothefuture (.*)", text) if match: return backtothefutureday(match[0])
1560bf7112652cbbc06d6d58031cd268d293ee13
atmo/users/factories.py
atmo/users/factories.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/. import factory from django.contrib.auth.models import User, Group class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = User @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group)
# 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/. import factory from django.contrib.auth.models import User, Group from django.contrib.auth.hashers import make_password class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' class Meta: model = User @factory.post_generation def password(self, create, extracted, **kwargs): if not create: return return make_password('password') @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group)
Fix incompatibility with recent factory_boy postgeneration.
Fix incompatibility with recent factory_boy postgeneration.
Python
mpl-2.0
mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service
# 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/. import factory from django.contrib.auth.models import User, Group class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = User @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group) Fix incompatibility with recent factory_boy postgeneration.
# 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/. import factory from django.contrib.auth.models import User, Group from django.contrib.auth.hashers import make_password class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' class Meta: model = User @factory.post_generation def password(self, create, extracted, **kwargs): if not create: return return make_password('password') @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group)
<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/. import factory from django.contrib.auth.models import User, Group class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = User @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group) <commit_msg>Fix incompatibility with recent factory_boy postgeneration.<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/. import factory from django.contrib.auth.models import User, Group from django.contrib.auth.hashers import make_password class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' class Meta: model = User @factory.post_generation def password(self, create, extracted, **kwargs): if not create: return return make_password('password') @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group)
# 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/. import factory from django.contrib.auth.models import User, Group class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = User @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group) Fix incompatibility with recent factory_boy postgeneration.# 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/. import factory from django.contrib.auth.models import User, Group from django.contrib.auth.hashers import make_password class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' class Meta: model = User @factory.post_generation def password(self, create, extracted, **kwargs): if not create: return return make_password('password') @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group)
<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/. import factory from django.contrib.auth.models import User, Group class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = User @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group) <commit_msg>Fix incompatibility with recent factory_boy postgeneration.<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/. import factory from django.contrib.auth.models import User, Group from django.contrib.auth.hashers import make_password class GroupFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: "Group #%s" % n) class Meta: model = Group class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user%s' % n) first_name = factory.Sequence(lambda n: "user %03d" % n) email = 'test@example.com' class Meta: model = User @factory.post_generation def password(self, create, extracted, **kwargs): if not create: return return make_password('password') @factory.post_generation def groups(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for group in extracted: self.groups.add(group)
0018ee9534ebf5b695971b936dd56cf45a6b4769
tests/packages/CommandCasing/plugin.py
tests/packages/CommandCasing/plugin.py
from sublime_plugin import ApplicationCommand class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): print("not_PascalCaseCommand") class not_PASCALcase_command(ApplicationCommand): def run(self): print("not_PASCALcase_command") class NotPascalCase_command(ApplicationCommand): def run(self): print("NotPascalCase_command") # Maybe this should pass: # A name like HTTPDownloadCommand is translated to "http_download" by ST class NotPASCALCaseCommand(ApplicationCommand): def run(self): print("PASCALCaseCommand") class PascalCaseCommand(ApplicationCommand): def run(self): print("PascalCaseCommand")
from sublime_plugin import ApplicationCommand # The print calls show what sublime_plugin.Command.name # translates the class names to. class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): print("not__pascal_case") class not_PASCALcase_command(ApplicationCommand): def run(self): print("not__pASCALcase") class NotPascalCase_command(ApplicationCommand): def run(self): print("not_pascal_case") class NotPASCALCaseCommand(ApplicationCommand): def run(self): print("not_pASCALCase") class PascalCaseCommand(ApplicationCommand): def run(self): print("pascal_case")
Clarify on command class casing
Clarify on command class casing
Python
mit
packagecontrol/package_reviewer,packagecontrol/st_package_reviewer
from sublime_plugin import ApplicationCommand class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): print("not_PascalCaseCommand") class not_PASCALcase_command(ApplicationCommand): def run(self): print("not_PASCALcase_command") class NotPascalCase_command(ApplicationCommand): def run(self): print("NotPascalCase_command") # Maybe this should pass: # A name like HTTPDownloadCommand is translated to "http_download" by ST class NotPASCALCaseCommand(ApplicationCommand): def run(self): print("PASCALCaseCommand") class PascalCaseCommand(ApplicationCommand): def run(self): print("PascalCaseCommand") Clarify on command class casing
from sublime_plugin import ApplicationCommand # The print calls show what sublime_plugin.Command.name # translates the class names to. class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): print("not__pascal_case") class not_PASCALcase_command(ApplicationCommand): def run(self): print("not__pASCALcase") class NotPascalCase_command(ApplicationCommand): def run(self): print("not_pascal_case") class NotPASCALCaseCommand(ApplicationCommand): def run(self): print("not_pASCALCase") class PascalCaseCommand(ApplicationCommand): def run(self): print("pascal_case")
<commit_before>from sublime_plugin import ApplicationCommand class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): print("not_PascalCaseCommand") class not_PASCALcase_command(ApplicationCommand): def run(self): print("not_PASCALcase_command") class NotPascalCase_command(ApplicationCommand): def run(self): print("NotPascalCase_command") # Maybe this should pass: # A name like HTTPDownloadCommand is translated to "http_download" by ST class NotPASCALCaseCommand(ApplicationCommand): def run(self): print("PASCALCaseCommand") class PascalCaseCommand(ApplicationCommand): def run(self): print("PascalCaseCommand") <commit_msg>Clarify on command class casing<commit_after>
from sublime_plugin import ApplicationCommand # The print calls show what sublime_plugin.Command.name # translates the class names to. class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): print("not__pascal_case") class not_PASCALcase_command(ApplicationCommand): def run(self): print("not__pASCALcase") class NotPascalCase_command(ApplicationCommand): def run(self): print("not_pascal_case") class NotPASCALCaseCommand(ApplicationCommand): def run(self): print("not_pASCALCase") class PascalCaseCommand(ApplicationCommand): def run(self): print("pascal_case")
from sublime_plugin import ApplicationCommand class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): print("not_PascalCaseCommand") class not_PASCALcase_command(ApplicationCommand): def run(self): print("not_PASCALcase_command") class NotPascalCase_command(ApplicationCommand): def run(self): print("NotPascalCase_command") # Maybe this should pass: # A name like HTTPDownloadCommand is translated to "http_download" by ST class NotPASCALCaseCommand(ApplicationCommand): def run(self): print("PASCALCaseCommand") class PascalCaseCommand(ApplicationCommand): def run(self): print("PascalCaseCommand") Clarify on command class casingfrom sublime_plugin import ApplicationCommand # The print calls show what sublime_plugin.Command.name # translates the class names to. class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): print("not__pascal_case") class not_PASCALcase_command(ApplicationCommand): def run(self): print("not__pASCALcase") class NotPascalCase_command(ApplicationCommand): def run(self): print("not_pascal_case") class NotPASCALCaseCommand(ApplicationCommand): def run(self): print("not_pASCALCase") class PascalCaseCommand(ApplicationCommand): def run(self): print("pascal_case")
<commit_before>from sublime_plugin import ApplicationCommand class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): print("not_PascalCaseCommand") class not_PASCALcase_command(ApplicationCommand): def run(self): print("not_PASCALcase_command") class NotPascalCase_command(ApplicationCommand): def run(self): print("NotPascalCase_command") # Maybe this should pass: # A name like HTTPDownloadCommand is translated to "http_download" by ST class NotPASCALCaseCommand(ApplicationCommand): def run(self): print("PASCALCaseCommand") class PascalCaseCommand(ApplicationCommand): def run(self): print("PascalCaseCommand") <commit_msg>Clarify on command class casing<commit_after>from sublime_plugin import ApplicationCommand # The print calls show what sublime_plugin.Command.name # translates the class names to. class not_pascal_case_command(ApplicationCommand): def run(self): print("not_pascal_case") class not_PascalCaseCommand(ApplicationCommand): def run(self): print("not__pascal_case") class not_PASCALcase_command(ApplicationCommand): def run(self): print("not__pASCALcase") class NotPascalCase_command(ApplicationCommand): def run(self): print("not_pascal_case") class NotPASCALCaseCommand(ApplicationCommand): def run(self): print("not_pASCALCase") class PascalCaseCommand(ApplicationCommand): def run(self): print("pascal_case")
a48e2a2f9f367994ab131201db2f07eee5788642
interleaving/interleaving_method.py
interleaving/interleaving_method.py
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, a, b): ''' a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, *lists): ''' *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError()
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError()
Add a length argument for InterleavingMethod.interleave and multileave
Add a length argument for InterleavingMethod.interleave and multileave
Python
mit
mpkato/interleaving
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, a, b): ''' a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, *lists): ''' *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError() Add a length argument for InterleavingMethod.interleave and multileave
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError()
<commit_before>class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, a, b): ''' a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, *lists): ''' *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError() <commit_msg>Add a length argument for InterleavingMethod.interleave and multileave<commit_after>
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError()
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, a, b): ''' a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, *lists): ''' *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError() Add a length argument for InterleavingMethod.interleave and multileaveclass InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError()
<commit_before>class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, a, b): ''' a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, *lists): ''' *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError() <commit_msg>Add a length argument for InterleavingMethod.interleave and multileave<commit_after>class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError()
e7a124628ce06d423425e3012d1b19b25562bdef
Discord/cogs/duelyst.py
Discord/cogs/duelyst.py
from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst(bot)) class Duelyst(commands.Cog): def __init__(self, bot): self.bot = bot async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True, case_insensitive = True) async def duelyst(self, ctx): '''Duelyst''' await ctx.send_help(ctx.command) @duelyst.group(case_insensitive = True) async def card(self, ctx, *, name: str): '''Details of a specific card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"cardName": name} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) @card.command() async def card_random(self, ctx): '''Details of a random card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"random": 1} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data)
from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst()) class Duelyst(commands.Cog): async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True, case_insensitive = True) async def duelyst(self, ctx): '''Duelyst''' await ctx.send_help(ctx.command) @duelyst.group(case_insensitive = True) async def card(self, ctx, *, name: str): '''Details of a specific card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"cardName": name} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) @card.command() async def card_random(self, ctx): '''Details of a random card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"random": 1} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data)
Remove unused bot attribute from Duelyst cog
[Discord] Remove unused bot attribute from Duelyst cog
Python
mit
Harmon758/Harmonbot,Harmon758/Harmonbot
from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst(bot)) class Duelyst(commands.Cog): def __init__(self, bot): self.bot = bot async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True, case_insensitive = True) async def duelyst(self, ctx): '''Duelyst''' await ctx.send_help(ctx.command) @duelyst.group(case_insensitive = True) async def card(self, ctx, *, name: str): '''Details of a specific card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"cardName": name} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) @card.command() async def card_random(self, ctx): '''Details of a random card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"random": 1} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) [Discord] Remove unused bot attribute from Duelyst cog
from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst()) class Duelyst(commands.Cog): async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True, case_insensitive = True) async def duelyst(self, ctx): '''Duelyst''' await ctx.send_help(ctx.command) @duelyst.group(case_insensitive = True) async def card(self, ctx, *, name: str): '''Details of a specific card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"cardName": name} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) @card.command() async def card_random(self, ctx): '''Details of a random card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"random": 1} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data)
<commit_before> from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst(bot)) class Duelyst(commands.Cog): def __init__(self, bot): self.bot = bot async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True, case_insensitive = True) async def duelyst(self, ctx): '''Duelyst''' await ctx.send_help(ctx.command) @duelyst.group(case_insensitive = True) async def card(self, ctx, *, name: str): '''Details of a specific card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"cardName": name} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) @card.command() async def card_random(self, ctx): '''Details of a random card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"random": 1} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) <commit_msg>[Discord] Remove unused bot attribute from Duelyst cog<commit_after>
from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst()) class Duelyst(commands.Cog): async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True, case_insensitive = True) async def duelyst(self, ctx): '''Duelyst''' await ctx.send_help(ctx.command) @duelyst.group(case_insensitive = True) async def card(self, ctx, *, name: str): '''Details of a specific card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"cardName": name} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) @card.command() async def card_random(self, ctx): '''Details of a random card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"random": 1} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data)
from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst(bot)) class Duelyst(commands.Cog): def __init__(self, bot): self.bot = bot async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True, case_insensitive = True) async def duelyst(self, ctx): '''Duelyst''' await ctx.send_help(ctx.command) @duelyst.group(case_insensitive = True) async def card(self, ctx, *, name: str): '''Details of a specific card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"cardName": name} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) @card.command() async def card_random(self, ctx): '''Details of a random card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"random": 1} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) [Discord] Remove unused bot attribute from Duelyst cog from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst()) class Duelyst(commands.Cog): async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True, case_insensitive = True) async def duelyst(self, ctx): '''Duelyst''' await ctx.send_help(ctx.command) @duelyst.group(case_insensitive = True) async def card(self, ctx, *, name: str): '''Details of a specific card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"cardName": name} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) @card.command() async def card_random(self, ctx): '''Details of a random card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"random": 1} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data)
<commit_before> from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst(bot)) class Duelyst(commands.Cog): def __init__(self, bot): self.bot = bot async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True, case_insensitive = True) async def duelyst(self, ctx): '''Duelyst''' await ctx.send_help(ctx.command) @duelyst.group(case_insensitive = True) async def card(self, ctx, *, name: str): '''Details of a specific card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"cardName": name} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) @card.command() async def card_random(self, ctx): '''Details of a random card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"random": 1} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) <commit_msg>[Discord] Remove unused bot attribute from Duelyst cog<commit_after> from discord.ext import commands from utilities import checks def setup(bot): bot.add_cog(Duelyst()) class Duelyst(commands.Cog): async def cog_check(self, ctx): return await checks.not_forbidden().predicate(ctx) @commands.group(invoke_without_command = True, case_insensitive = True) async def duelyst(self, ctx): '''Duelyst''' await ctx.send_help(ctx.command) @duelyst.group(case_insensitive = True) async def card(self, ctx, *, name: str): '''Details of a specific card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"cardName": name} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data) @card.command() async def card_random(self, ctx): '''Details of a random card''' url = "https://duelyststats.info/scripts/carddata/get.php" params = {"random": 1} async with ctx.bot.aiohttp_session.get(url, params = params) as resp: data = await resp.text() await ctx.embed_reply(data)
f66f8b84a4092cce1f9f7e4e29a4fc483c51602f
whistleblower/tasks.py
whistleblower/tasks.py
import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_suspicions_dataset(): command = ['python', 'rosie/rosie.py', 'run', 'chamber_of_deputies', 'data', '--years=2017,2016'] subprocess.run(command, check=True) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish()
import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish()
Remove task for updating data
Remove task for updating data Not sure if this is the best method to have it. Since for now is not needed, droping it from the codebase.
Python
unlicense
datasciencebr/whistleblower
import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_suspicions_dataset(): command = ['python', 'rosie/rosie.py', 'run', 'chamber_of_deputies', 'data', '--years=2017,2016'] subprocess.run(command, check=True) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish() Remove task for updating data Not sure if this is the best method to have it. Since for now is not needed, droping it from the codebase.
import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish()
<commit_before>import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_suspicions_dataset(): command = ['python', 'rosie/rosie.py', 'run', 'chamber_of_deputies', 'data', '--years=2017,2016'] subprocess.run(command, check=True) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish() <commit_msg>Remove task for updating data Not sure if this is the best method to have it. Since for now is not needed, droping it from the codebase.<commit_after>
import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish()
import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_suspicions_dataset(): command = ['python', 'rosie/rosie.py', 'run', 'chamber_of_deputies', 'data', '--years=2017,2016'] subprocess.run(command, check=True) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish() Remove task for updating data Not sure if this is the best method to have it. Since for now is not needed, droping it from the codebase.import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish()
<commit_before>import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_suspicions_dataset(): command = ['python', 'rosie/rosie.py', 'run', 'chamber_of_deputies', 'data', '--years=2017,2016'] subprocess.run(command, check=True) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish() <commit_msg>Remove task for updating data Not sure if this is the best method to have it. Since for now is not needed, droping it from the codebase.<commit_after>import json import logging import os import subprocess from celery import Celery from celery.schedules import crontab from .targets.facebook_messenger import Post as MessengerPost from .targets.twitter import Post as TwitterPost import whistleblower.queue HOUR = 3600 ENABLED_TARGETS = [ TwitterPost, MessengerPost, ] RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//') app = Celery('tasks', broker=RABBITMQ_URL) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(4 * HOUR, process_queue.s()) @app.task def update_queue(): whistleblower.queue.Queue().update() @app.task def process_queue(): whistleblower.queue.Queue().process() @app.task def publish_reimbursement(reimbursement): for target in ENABLED_TARGETS: target(reimbursement).publish()
b16409f5c0771d3d4440b5152971e9659fa23eb9
application.py
application.py
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) if __name__ == '__main__': manager.run()
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) manager.add_command("runserver", Server(port=5003)) if __name__ == '__main__': manager.run()
Update to run on port 5003
Update to run on port 5003 For development we will want to run multiple apps, so they should each bind to a different port number.
Python
mit
alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) if __name__ == '__main__': manager.run() Update to run on port 5003 For development we will want to run multiple apps, so they should each bind to a different port number.
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) manager.add_command("runserver", Server(port=5003)) if __name__ == '__main__': manager.run()
<commit_before>#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) if __name__ == '__main__': manager.run() <commit_msg>Update to run on port 5003 For development we will want to run multiple apps, so they should each bind to a different port number.<commit_after>
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) manager.add_command("runserver", Server(port=5003)) if __name__ == '__main__': manager.run()
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) if __name__ == '__main__': manager.run() Update to run on port 5003 For development we will want to run multiple apps, so they should each bind to a different port number.#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) manager.add_command("runserver", Server(port=5003)) if __name__ == '__main__': manager.run()
<commit_before>#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) if __name__ == '__main__': manager.run() <commit_msg>Update to run on port 5003 For development we will want to run multiple apps, so they should each bind to a different port number.<commit_after>#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) manager.add_command("runserver", Server(port=5003)) if __name__ == '__main__': manager.run()
96104472462e78853969ab5bef87592fe479e4b9
bin/server.py
bin/server.py
""" Simple server scripts that spawns the Jupyter notebook server process. """ import subprocess subprocess.call([ 'jupyter', 'notebook', '--no-browser', '--ip=0.0.0.0', '--port=5000', '--notebook-dir=../workspace' ])
""" Simple server scripts that spawns the Jupyter notebook server process. """ import os import subprocess # Check if code runs in SourceLair and change current directory to project # root directory, if so. if (os.environ.get('SL_ENV') == '1'): os.chdir('/mnt/project') # Try to import jupyter. If this fails, install dependencies. try: import jupyter except ImportError: print 'Could not find jupyter. Installing dependencies...' subprocess.call(['pip', 'install', '-r', 'requirements.txt']) subprocess.call([ 'jupyter', 'notebook', '--no-browser', '--ip=0.0.0.0', '--port=5000', '--notebook-dir=workspace' ])
Add automatic installation of dependencies if not found.
Add automatic installation of dependencies if not found.
Python
mit
parisk/jupyter-starter
""" Simple server scripts that spawns the Jupyter notebook server process. """ import subprocess subprocess.call([ 'jupyter', 'notebook', '--no-browser', '--ip=0.0.0.0', '--port=5000', '--notebook-dir=../workspace' ]) Add automatic installation of dependencies if not found.
""" Simple server scripts that spawns the Jupyter notebook server process. """ import os import subprocess # Check if code runs in SourceLair and change current directory to project # root directory, if so. if (os.environ.get('SL_ENV') == '1'): os.chdir('/mnt/project') # Try to import jupyter. If this fails, install dependencies. try: import jupyter except ImportError: print 'Could not find jupyter. Installing dependencies...' subprocess.call(['pip', 'install', '-r', 'requirements.txt']) subprocess.call([ 'jupyter', 'notebook', '--no-browser', '--ip=0.0.0.0', '--port=5000', '--notebook-dir=workspace' ])
<commit_before>""" Simple server scripts that spawns the Jupyter notebook server process. """ import subprocess subprocess.call([ 'jupyter', 'notebook', '--no-browser', '--ip=0.0.0.0', '--port=5000', '--notebook-dir=../workspace' ]) <commit_msg>Add automatic installation of dependencies if not found.<commit_after>
""" Simple server scripts that spawns the Jupyter notebook server process. """ import os import subprocess # Check if code runs in SourceLair and change current directory to project # root directory, if so. if (os.environ.get('SL_ENV') == '1'): os.chdir('/mnt/project') # Try to import jupyter. If this fails, install dependencies. try: import jupyter except ImportError: print 'Could not find jupyter. Installing dependencies...' subprocess.call(['pip', 'install', '-r', 'requirements.txt']) subprocess.call([ 'jupyter', 'notebook', '--no-browser', '--ip=0.0.0.0', '--port=5000', '--notebook-dir=workspace' ])
""" Simple server scripts that spawns the Jupyter notebook server process. """ import subprocess subprocess.call([ 'jupyter', 'notebook', '--no-browser', '--ip=0.0.0.0', '--port=5000', '--notebook-dir=../workspace' ]) Add automatic installation of dependencies if not found.""" Simple server scripts that spawns the Jupyter notebook server process. """ import os import subprocess # Check if code runs in SourceLair and change current directory to project # root directory, if so. if (os.environ.get('SL_ENV') == '1'): os.chdir('/mnt/project') # Try to import jupyter. If this fails, install dependencies. try: import jupyter except ImportError: print 'Could not find jupyter. Installing dependencies...' subprocess.call(['pip', 'install', '-r', 'requirements.txt']) subprocess.call([ 'jupyter', 'notebook', '--no-browser', '--ip=0.0.0.0', '--port=5000', '--notebook-dir=workspace' ])
<commit_before>""" Simple server scripts that spawns the Jupyter notebook server process. """ import subprocess subprocess.call([ 'jupyter', 'notebook', '--no-browser', '--ip=0.0.0.0', '--port=5000', '--notebook-dir=../workspace' ]) <commit_msg>Add automatic installation of dependencies if not found.<commit_after>""" Simple server scripts that spawns the Jupyter notebook server process. """ import os import subprocess # Check if code runs in SourceLair and change current directory to project # root directory, if so. if (os.environ.get('SL_ENV') == '1'): os.chdir('/mnt/project') # Try to import jupyter. If this fails, install dependencies. try: import jupyter except ImportError: print 'Could not find jupyter. Installing dependencies...' subprocess.call(['pip', 'install', '-r', 'requirements.txt']) subprocess.call([ 'jupyter', 'notebook', '--no-browser', '--ip=0.0.0.0', '--port=5000', '--notebook-dir=workspace' ])
4ac0458e114809c82b42bc0f058aa382fd4f9daf
src/fabfile.py
src/fabfile.py
import os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics import tasks import master import askmaster import buildvars import project from deploy import switch_revision_update_instance from lifecycle import start, stop, restart, stop_if_running_for, update_dns import masterless import fixtures import vault
import os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics import tasks import master import askmaster import buildvars import project from deploy import switch_revision_update_instance from lifecycle import start, stop, restart, stop_if_running_for, update_dns import masterless import vault
Remove import of dead module
Remove import of dead module
Python
mit
elifesciences/builder,elifesciences/builder
import os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics import tasks import master import askmaster import buildvars import project from deploy import switch_revision_update_instance from lifecycle import start, stop, restart, stop_if_running_for, update_dns import masterless import fixtures import vault Remove import of dead module
import os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics import tasks import master import askmaster import buildvars import project from deploy import switch_revision_update_instance from lifecycle import start, stop, restart, stop_if_running_for, update_dns import masterless import vault
<commit_before>import os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics import tasks import master import askmaster import buildvars import project from deploy import switch_revision_update_instance from lifecycle import start, stop, restart, stop_if_running_for, update_dns import masterless import fixtures import vault <commit_msg>Remove import of dead module<commit_after>
import os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics import tasks import master import askmaster import buildvars import project from deploy import switch_revision_update_instance from lifecycle import start, stop, restart, stop_if_running_for, update_dns import masterless import vault
import os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics import tasks import master import askmaster import buildvars import project from deploy import switch_revision_update_instance from lifecycle import start, stop, restart, stop_if_running_for, update_dns import masterless import fixtures import vault Remove import of dead moduleimport os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics import tasks import master import askmaster import buildvars import project from deploy import switch_revision_update_instance from lifecycle import start, stop, restart, stop_if_running_for, update_dns import masterless import vault
<commit_before>import os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics import tasks import master import askmaster import buildvars import project from deploy import switch_revision_update_instance from lifecycle import start, stop, restart, stop_if_running_for, update_dns import masterless import fixtures import vault <commit_msg>Remove import of dead module<commit_after>import os # pylint: disable=unused-wildcard-import,unused-import,wildcard-import SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/ # once called 'THIS_DIR', now deprecated as confusing. PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/ from cfn import * import aws import metrics import tasks import master import askmaster import buildvars import project from deploy import switch_revision_update_instance from lifecycle import start, stop, restart, stop_if_running_for, update_dns import masterless import vault
04a738253bbd0018784ce6ad81480b38a61b006f
etc/bin/xcode_bots/testflight/before_integration.py
etc/bin/xcode_bots/testflight/before_integration.py
# This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script"
# This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script"
Use the correct Info.plist in the new version of FeedbackDemo
Use the correct Info.plist in the new version of FeedbackDemo
Python
bsd-3-clause
Jawbone/apptentive-ios,ALHariPrasad/apptentive-ios,apptentive/apptentive-ios,hibu/apptentive-ios,sahara108/apptentive-ios,Jawbone/apptentive-ios,hibu/apptentive-ios,apptentive/apptentive-ios,sahara108/apptentive-ios,apptentive/apptentive-ios,hibu/apptentive-ios,ALHariPrasad/apptentive-ios
# This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script" Use the correct Info.plist in the new version of FeedbackDemo
# This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script"
<commit_before># This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script" <commit_msg>Use the correct Info.plist in the new version of FeedbackDemo<commit_after>
# This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script"
# This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script" Use the correct Info.plist in the new version of FeedbackDemo# This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script"
<commit_before># This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script" <commit_msg>Use the correct Info.plist in the new version of FeedbackDemo<commit_after># This script should be copied into the Run Script trigger of an Xcode Bot # Utilizes `cavejohnson` for Xcode Bot scripting # https://github.com/drewcrawford/CaveJohnson #!/bin/bash PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script"
cd9cb42c16d443a26c7054e27c3ebc254142fbfb
python/ligscore/__init__.py
python/ligscore/__init__.py
import saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.SGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ') lib = libs[lib] script = """ module load imp lib=`python -c "import IMP.atom; print IMP.atom.get_data_path('%s')"` ligand_score %s %s "$lib" > score.list 2> score.log """ % (lib, mol2, pdb) r = self.runnercls(script) r.set_sge_options('-l arch=linux-x64') return r def get_web_service(config_file): db = saliweb.backend.Database(Job) config = saliweb.backend.Config(config_file) return saliweb.backend.WebService(config, db)
import saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.WyntonSGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ') lib = libs[lib] script = """ module load Sali module load imp lib=`python -c "import IMP.atom; print IMP.atom.get_data_path('%s')"` ligand_score %s %s "$lib" > score.list 2> score.log """ % (lib, mol2, pdb) r = self.runnercls(script) r.set_sge_options('-l arch=lx-amd64') return r def get_web_service(config_file): db = saliweb.backend.Database(Job) config = saliweb.backend.Config(config_file) return saliweb.backend.WebService(config, db)
Switch to new Wynton cluster
Switch to new Wynton cluster
Python
lgpl-2.1
salilab/ligscore,salilab/ligscore
import saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.SGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ') lib = libs[lib] script = """ module load imp lib=`python -c "import IMP.atom; print IMP.atom.get_data_path('%s')"` ligand_score %s %s "$lib" > score.list 2> score.log """ % (lib, mol2, pdb) r = self.runnercls(script) r.set_sge_options('-l arch=linux-x64') return r def get_web_service(config_file): db = saliweb.backend.Database(Job) config = saliweb.backend.Config(config_file) return saliweb.backend.WebService(config, db) Switch to new Wynton cluster
import saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.WyntonSGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ') lib = libs[lib] script = """ module load Sali module load imp lib=`python -c "import IMP.atom; print IMP.atom.get_data_path('%s')"` ligand_score %s %s "$lib" > score.list 2> score.log """ % (lib, mol2, pdb) r = self.runnercls(script) r.set_sge_options('-l arch=lx-amd64') return r def get_web_service(config_file): db = saliweb.backend.Database(Job) config = saliweb.backend.Config(config_file) return saliweb.backend.WebService(config, db)
<commit_before>import saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.SGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ') lib = libs[lib] script = """ module load imp lib=`python -c "import IMP.atom; print IMP.atom.get_data_path('%s')"` ligand_score %s %s "$lib" > score.list 2> score.log """ % (lib, mol2, pdb) r = self.runnercls(script) r.set_sge_options('-l arch=linux-x64') return r def get_web_service(config_file): db = saliweb.backend.Database(Job) config = saliweb.backend.Config(config_file) return saliweb.backend.WebService(config, db) <commit_msg>Switch to new Wynton cluster<commit_after>
import saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.WyntonSGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ') lib = libs[lib] script = """ module load Sali module load imp lib=`python -c "import IMP.atom; print IMP.atom.get_data_path('%s')"` ligand_score %s %s "$lib" > score.list 2> score.log """ % (lib, mol2, pdb) r = self.runnercls(script) r.set_sge_options('-l arch=lx-amd64') return r def get_web_service(config_file): db = saliweb.backend.Database(Job) config = saliweb.backend.Config(config_file) return saliweb.backend.WebService(config, db)
import saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.SGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ') lib = libs[lib] script = """ module load imp lib=`python -c "import IMP.atom; print IMP.atom.get_data_path('%s')"` ligand_score %s %s "$lib" > score.list 2> score.log """ % (lib, mol2, pdb) r = self.runnercls(script) r.set_sge_options('-l arch=linux-x64') return r def get_web_service(config_file): db = saliweb.backend.Database(Job) config = saliweb.backend.Config(config_file) return saliweb.backend.WebService(config, db) Switch to new Wynton clusterimport saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.WyntonSGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ') lib = libs[lib] script = """ module load Sali module load imp lib=`python -c "import IMP.atom; print IMP.atom.get_data_path('%s')"` ligand_score %s %s "$lib" > score.list 2> score.log """ % (lib, mol2, pdb) r = self.runnercls(script) r.set_sge_options('-l arch=lx-amd64') return r def get_web_service(config_file): db = saliweb.backend.Database(Job) config = saliweb.backend.Config(config_file) return saliweb.backend.WebService(config, db)
<commit_before>import saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.SGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ') lib = libs[lib] script = """ module load imp lib=`python -c "import IMP.atom; print IMP.atom.get_data_path('%s')"` ligand_score %s %s "$lib" > score.list 2> score.log """ % (lib, mol2, pdb) r = self.runnercls(script) r.set_sge_options('-l arch=linux-x64') return r def get_web_service(config_file): db = saliweb.backend.Database(Job) config = saliweb.backend.Config(config_file) return saliweb.backend.WebService(config, db) <commit_msg>Switch to new Wynton cluster<commit_after>import saliweb.backend class Job(saliweb.backend.Job): runnercls = saliweb.backend.WyntonSGERunner def run(self): libs = {'PoseScore': 'protein_ligand_pose_score.lib', 'RankScore': 'protein_ligand_rank_score.lib'} pdb, mol2, lib = open('input.txt').readline().strip().split(' ') lib = libs[lib] script = """ module load Sali module load imp lib=`python -c "import IMP.atom; print IMP.atom.get_data_path('%s')"` ligand_score %s %s "$lib" > score.list 2> score.log """ % (lib, mol2, pdb) r = self.runnercls(script) r.set_sge_options('-l arch=lx-amd64') return r def get_web_service(config_file): db = saliweb.backend.Database(Job) config = saliweb.backend.Config(config_file) return saliweb.backend.WebService(config, db)
f6748408ecbbd1550b47a5975bdff135229acd11
tests/test_itunes.py
tests/test_itunes.py
""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_parse_value(self): self.assertEquals(parse_value("10"), 10) self.assertEquals(parse_value("1.0"), 1.0) self.assertTrue(parse_value("true")) self.assertFalse(parse_value("false")) self.assertIsNone(parse_value("")) self.assertIsNone(parse_value("missing value"))
""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_parse_value(self): self.assertEquals(parse_value("10"), 10) self.assertEquals(parse_value("1.0"), 1.0) self.assertTrue(parse_value("true")) self.assertFalse(parse_value("false")) self.assertIsNone(parse_value("")) self.assertIsNone(parse_value('""')) self.assertIsNone(parse_value("missing value"))
Add test case for `parse_value`
Add test case for `parse_value` The new test case handles the string '""' as input.
Python
mit
adanoff/iTunesTUI
""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_parse_value(self): self.assertEquals(parse_value("10"), 10) self.assertEquals(parse_value("1.0"), 1.0) self.assertTrue(parse_value("true")) self.assertFalse(parse_value("false")) self.assertIsNone(parse_value("")) self.assertIsNone(parse_value("missing value")) Add test case for `parse_value` The new test case handles the string '""' as input.
""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_parse_value(self): self.assertEquals(parse_value("10"), 10) self.assertEquals(parse_value("1.0"), 1.0) self.assertTrue(parse_value("true")) self.assertFalse(parse_value("false")) self.assertIsNone(parse_value("")) self.assertIsNone(parse_value('""')) self.assertIsNone(parse_value("missing value"))
<commit_before>""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_parse_value(self): self.assertEquals(parse_value("10"), 10) self.assertEquals(parse_value("1.0"), 1.0) self.assertTrue(parse_value("true")) self.assertFalse(parse_value("false")) self.assertIsNone(parse_value("")) self.assertIsNone(parse_value("missing value")) <commit_msg>Add test case for `parse_value` The new test case handles the string '""' as input.<commit_after>
""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_parse_value(self): self.assertEquals(parse_value("10"), 10) self.assertEquals(parse_value("1.0"), 1.0) self.assertTrue(parse_value("true")) self.assertFalse(parse_value("false")) self.assertIsNone(parse_value("")) self.assertIsNone(parse_value('""')) self.assertIsNone(parse_value("missing value"))
""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_parse_value(self): self.assertEquals(parse_value("10"), 10) self.assertEquals(parse_value("1.0"), 1.0) self.assertTrue(parse_value("true")) self.assertFalse(parse_value("false")) self.assertIsNone(parse_value("")) self.assertIsNone(parse_value("missing value")) Add test case for `parse_value` The new test case handles the string '""' as input.""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_parse_value(self): self.assertEquals(parse_value("10"), 10) self.assertEquals(parse_value("1.0"), 1.0) self.assertTrue(parse_value("true")) self.assertFalse(parse_value("false")) self.assertIsNone(parse_value("")) self.assertIsNone(parse_value('""')) self.assertIsNone(parse_value("missing value"))
<commit_before>""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_parse_value(self): self.assertEquals(parse_value("10"), 10) self.assertEquals(parse_value("1.0"), 1.0) self.assertTrue(parse_value("true")) self.assertFalse(parse_value("false")) self.assertIsNone(parse_value("")) self.assertIsNone(parse_value("missing value")) <commit_msg>Add test case for `parse_value` The new test case handles the string '""' as input.<commit_after>""" test_itunes.py Copyright © 2015 Alex Danoff. All Rights Reserved. 2015-08-02 This file tests the functionality provided by the itunes module. """ import unittest from itunes.itunes import parse_value class ITunesTests(unittest.TestCase): """ Test cases for iTunes functionality. """ def test_parse_value(self): self.assertEquals(parse_value("10"), 10) self.assertEquals(parse_value("1.0"), 1.0) self.assertTrue(parse_value("true")) self.assertFalse(parse_value("false")) self.assertIsNone(parse_value("")) self.assertIsNone(parse_value('""')) self.assertIsNone(parse_value("missing value"))
9de4ba984ce009c310e201ff3d00958f56c96d55
tests/test_length.py
tests/test_length.py
import pytest # type: ignore from ppb_vector import Vector @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_length(x, y, expected): vector = Vector(x, y) assert vector.length == expected
from math import sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_length(x, y, expected): vector = Vector(x, y) assert vector.length == expected @given(v=vectors()) def test_length_dot(v: Vector): """Test that |v| ≃ √v².""" assert isclose(v.length, sqrt(v * v))
Add comparison to (the square root of) the dot product
tests/length: Add comparison to (the square root of) the dot product
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
import pytest # type: ignore from ppb_vector import Vector @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_length(x, y, expected): vector = Vector(x, y) assert vector.length == expected tests/length: Add comparison to (the square root of) the dot product
from math import sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_length(x, y, expected): vector = Vector(x, y) assert vector.length == expected @given(v=vectors()) def test_length_dot(v: Vector): """Test that |v| ≃ √v².""" assert isclose(v.length, sqrt(v * v))
<commit_before>import pytest # type: ignore from ppb_vector import Vector @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_length(x, y, expected): vector = Vector(x, y) assert vector.length == expected <commit_msg>tests/length: Add comparison to (the square root of) the dot product<commit_after>
from math import sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_length(x, y, expected): vector = Vector(x, y) assert vector.length == expected @given(v=vectors()) def test_length_dot(v: Vector): """Test that |v| ≃ √v².""" assert isclose(v.length, sqrt(v * v))
import pytest # type: ignore from ppb_vector import Vector @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_length(x, y, expected): vector = Vector(x, y) assert vector.length == expected tests/length: Add comparison to (the square root of) the dot productfrom math import sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_length(x, y, expected): vector = Vector(x, y) assert vector.length == expected @given(v=vectors()) def test_length_dot(v: Vector): """Test that |v| ≃ √v².""" assert isclose(v.length, sqrt(v * v))
<commit_before>import pytest # type: ignore from ppb_vector import Vector @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_length(x, y, expected): vector = Vector(x, y) assert vector.length == expected <commit_msg>tests/length: Add comparison to (the square root of) the dot product<commit_after>from math import sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_length(x, y, expected): vector = Vector(x, y) assert vector.length == expected @given(v=vectors()) def test_length_dot(v: Vector): """Test that |v| ≃ √v².""" assert isclose(v.length, sqrt(v * v))
98efef62f50cf5de75e87ec03abe50639e4891a5
tests/test_search.py
tests/test_search.py
import unittest import os import sys sys.path.insert(1, os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, )) from website import search import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class TestSearch(unittest.TestCase): def setUp(self): source = "test" doc_id = 38 doc = { 'title': "TEST PROJECT", 'contributors': ['Me, Myself', 'And I'], 'properties': { 'description': 'science stuff', 'email': 'email stuff' }, 'meta': {}, 'id': doc_id, 'source': source } search.update(source, doc, 'article', doc_id) def tearDown(self): search.delete_all('test') def test_search(self): results = search.search('test', 'test') assert len(results) == 1 def test_delete_doc(self): search.delete_doc('test', 'article', 38) results = search.search('test', 'test') assert len(results) == 0
import unittest import os import sys sys.path.insert(1, os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, )) from website import search import logging import datetime logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class TestSearch(unittest.TestCase): def setUp(self): search.delete_all('test') source = "test" doc_id = 38 doc = { 'title': "TEST PROJECT", 'contributors': ['Me, Myself', 'And I'], 'properties': { 'description': 'science stuff', 'email': 'email stuff' }, 'meta': {}, 'id': doc_id, 'source': source, 'iso_timestamp': datetime.datetime.now().isoformat() } search.update(source, doc, 'article', doc_id) def tearDown(self): search.delete_all('test') def test_search(self): results, count = search.search('test', 'test') assert len(results) == count assert len(results) == 1 def test_delete_doc(self): search.delete_doc('test', 'article', '38') results, count = search.search('test', 'test') assert len(results) == count assert len(results) == 0
Update search tests for changes to search.py
Update search tests for changes to search.py
Python
apache-2.0
ostwald/scrapi,fabianvf/scrapi,mehanig/scrapi,CenterForOpenScience/scrapi,alexgarciac/scrapi,erinspace/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,erinspace/scrapi,felliott/scrapi,jeffreyliu3230/scrapi,mehanig/scrapi,icereval/scrapi
import unittest import os import sys sys.path.insert(1, os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, )) from website import search import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class TestSearch(unittest.TestCase): def setUp(self): source = "test" doc_id = 38 doc = { 'title': "TEST PROJECT", 'contributors': ['Me, Myself', 'And I'], 'properties': { 'description': 'science stuff', 'email': 'email stuff' }, 'meta': {}, 'id': doc_id, 'source': source } search.update(source, doc, 'article', doc_id) def tearDown(self): search.delete_all('test') def test_search(self): results = search.search('test', 'test') assert len(results) == 1 def test_delete_doc(self): search.delete_doc('test', 'article', 38) results = search.search('test', 'test') assert len(results) == 0 Update search tests for changes to search.py
import unittest import os import sys sys.path.insert(1, os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, )) from website import search import logging import datetime logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class TestSearch(unittest.TestCase): def setUp(self): search.delete_all('test') source = "test" doc_id = 38 doc = { 'title': "TEST PROJECT", 'contributors': ['Me, Myself', 'And I'], 'properties': { 'description': 'science stuff', 'email': 'email stuff' }, 'meta': {}, 'id': doc_id, 'source': source, 'iso_timestamp': datetime.datetime.now().isoformat() } search.update(source, doc, 'article', doc_id) def tearDown(self): search.delete_all('test') def test_search(self): results, count = search.search('test', 'test') assert len(results) == count assert len(results) == 1 def test_delete_doc(self): search.delete_doc('test', 'article', '38') results, count = search.search('test', 'test') assert len(results) == count assert len(results) == 0
<commit_before>import unittest import os import sys sys.path.insert(1, os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, )) from website import search import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class TestSearch(unittest.TestCase): def setUp(self): source = "test" doc_id = 38 doc = { 'title': "TEST PROJECT", 'contributors': ['Me, Myself', 'And I'], 'properties': { 'description': 'science stuff', 'email': 'email stuff' }, 'meta': {}, 'id': doc_id, 'source': source } search.update(source, doc, 'article', doc_id) def tearDown(self): search.delete_all('test') def test_search(self): results = search.search('test', 'test') assert len(results) == 1 def test_delete_doc(self): search.delete_doc('test', 'article', 38) results = search.search('test', 'test') assert len(results) == 0 <commit_msg>Update search tests for changes to search.py<commit_after>
import unittest import os import sys sys.path.insert(1, os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, )) from website import search import logging import datetime logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class TestSearch(unittest.TestCase): def setUp(self): search.delete_all('test') source = "test" doc_id = 38 doc = { 'title': "TEST PROJECT", 'contributors': ['Me, Myself', 'And I'], 'properties': { 'description': 'science stuff', 'email': 'email stuff' }, 'meta': {}, 'id': doc_id, 'source': source, 'iso_timestamp': datetime.datetime.now().isoformat() } search.update(source, doc, 'article', doc_id) def tearDown(self): search.delete_all('test') def test_search(self): results, count = search.search('test', 'test') assert len(results) == count assert len(results) == 1 def test_delete_doc(self): search.delete_doc('test', 'article', '38') results, count = search.search('test', 'test') assert len(results) == count assert len(results) == 0
import unittest import os import sys sys.path.insert(1, os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, )) from website import search import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class TestSearch(unittest.TestCase): def setUp(self): source = "test" doc_id = 38 doc = { 'title': "TEST PROJECT", 'contributors': ['Me, Myself', 'And I'], 'properties': { 'description': 'science stuff', 'email': 'email stuff' }, 'meta': {}, 'id': doc_id, 'source': source } search.update(source, doc, 'article', doc_id) def tearDown(self): search.delete_all('test') def test_search(self): results = search.search('test', 'test') assert len(results) == 1 def test_delete_doc(self): search.delete_doc('test', 'article', 38) results = search.search('test', 'test') assert len(results) == 0 Update search tests for changes to search.pyimport unittest import os import sys sys.path.insert(1, os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, )) from website import search import logging import datetime logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class TestSearch(unittest.TestCase): def setUp(self): search.delete_all('test') source = "test" doc_id = 38 doc = { 'title': "TEST PROJECT", 'contributors': ['Me, Myself', 'And I'], 'properties': { 'description': 'science stuff', 'email': 'email stuff' }, 'meta': {}, 'id': doc_id, 'source': source, 'iso_timestamp': datetime.datetime.now().isoformat() } search.update(source, doc, 'article', doc_id) def tearDown(self): search.delete_all('test') def test_search(self): results, count = search.search('test', 'test') assert len(results) == count assert len(results) == 1 def test_delete_doc(self): search.delete_doc('test', 'article', '38') results, count = search.search('test', 'test') assert len(results) == count assert len(results) == 0
<commit_before>import unittest import os import sys sys.path.insert(1, os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, )) from website import search import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class TestSearch(unittest.TestCase): def setUp(self): source = "test" doc_id = 38 doc = { 'title': "TEST PROJECT", 'contributors': ['Me, Myself', 'And I'], 'properties': { 'description': 'science stuff', 'email': 'email stuff' }, 'meta': {}, 'id': doc_id, 'source': source } search.update(source, doc, 'article', doc_id) def tearDown(self): search.delete_all('test') def test_search(self): results = search.search('test', 'test') assert len(results) == 1 def test_delete_doc(self): search.delete_doc('test', 'article', 38) results = search.search('test', 'test') assert len(results) == 0 <commit_msg>Update search tests for changes to search.py<commit_after>import unittest import os import sys sys.path.insert(1, os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, )) from website import search import logging import datetime logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class TestSearch(unittest.TestCase): def setUp(self): search.delete_all('test') source = "test" doc_id = 38 doc = { 'title': "TEST PROJECT", 'contributors': ['Me, Myself', 'And I'], 'properties': { 'description': 'science stuff', 'email': 'email stuff' }, 'meta': {}, 'id': doc_id, 'source': source, 'iso_timestamp': datetime.datetime.now().isoformat() } search.update(source, doc, 'article', doc_id) def tearDown(self): search.delete_all('test') def test_search(self): results, count = search.search('test', 'test') assert len(results) == count assert len(results) == 1 def test_delete_doc(self): search.delete_doc('test', 'article', '38') results, count = search.search('test', 'test') assert len(results) == count assert len(results) == 0
e21e3dec9a238785fefe275f600ff43991f3737c
nntpserver.py
nntpserver.py
#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if pid > 0: conn.close() else: nntp.NNTPServer(input=conn.makefile('r'), output=conn.makefile('w')).process_commands() conn.close() sys.exit(0)
#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if pid > 0: conn.close() else: nntp.NNTPServer(input=conn.makefile('r'), output=conn.makefile('w')).process_commands() conn.close() sys.exit(0)
Set SO_REUSADDR on the listening socket
Set SO_REUSADDR on the listening socket So that nntpserver.py can be killed and restarted wothout delay.
Python
mit
dpw/pnntprss
#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if pid > 0: conn.close() else: nntp.NNTPServer(input=conn.makefile('r'), output=conn.makefile('w')).process_commands() conn.close() sys.exit(0) Set SO_REUSADDR on the listening socket So that nntpserver.py can be killed and restarted wothout delay.
#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if pid > 0: conn.close() else: nntp.NNTPServer(input=conn.makefile('r'), output=conn.makefile('w')).process_commands() conn.close() sys.exit(0)
<commit_before>#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if pid > 0: conn.close() else: nntp.NNTPServer(input=conn.makefile('r'), output=conn.makefile('w')).process_commands() conn.close() sys.exit(0) <commit_msg>Set SO_REUSADDR on the listening socket So that nntpserver.py can be killed and restarted wothout delay.<commit_after>
#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if pid > 0: conn.close() else: nntp.NNTPServer(input=conn.makefile('r'), output=conn.makefile('w')).process_commands() conn.close() sys.exit(0)
#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if pid > 0: conn.close() else: nntp.NNTPServer(input=conn.makefile('r'), output=conn.makefile('w')).process_commands() conn.close() sys.exit(0) Set SO_REUSADDR on the listening socket So that nntpserver.py can be killed and restarted wothout delay.#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if pid > 0: conn.close() else: nntp.NNTPServer(input=conn.makefile('r'), output=conn.makefile('w')).process_commands() conn.close() sys.exit(0)
<commit_before>#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if pid > 0: conn.close() else: nntp.NNTPServer(input=conn.makefile('r'), output=conn.makefile('w')).process_commands() conn.close() sys.exit(0) <commit_msg>Set SO_REUSADDR on the listening socket So that nntpserver.py can be killed and restarted wothout delay.<commit_after>#!/usr/bin/python import socket, sys, os, signal import nntp signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', 4321)) s.listen(1) while True: conn, addr = s.accept() pid = os.fork() if pid > 0: conn.close() else: nntp.NNTPServer(input=conn.makefile('r'), output=conn.makefile('w')).process_commands() conn.close() sys.exit(0)
e8cd061ca203fa886757bdbf215b83c5ab2e43aa
geotrek/outdoor/migrations/0032_course_points_reference.py
geotrek/outdoor/migrations/0032_course_points_reference.py
# Generated by Django 3.1.13 on 2021-10-13 13:05 import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddField( model_name='course', name='points_reference', field=django.contrib.gis.db.models.fields.MultiPointField(blank=True, null=True, spatial_index=False, srid=2154, verbose_name='Points of reference'), ), ]
# Generated by Django 3.1.13 on 2021-10-13 13:05 from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddField( model_name='course', name='points_reference', field=django.contrib.gis.db.models.fields.MultiPointField(blank=True, null=True, spatial_index=False, srid=settings.SRID, verbose_name='Points of reference'), ), ]
Use settings SRID in migration
Use settings SRID in migration
Python
bsd-2-clause
GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
# Generated by Django 3.1.13 on 2021-10-13 13:05 import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddField( model_name='course', name='points_reference', field=django.contrib.gis.db.models.fields.MultiPointField(blank=True, null=True, spatial_index=False, srid=2154, verbose_name='Points of reference'), ), ] Use settings SRID in migration
# Generated by Django 3.1.13 on 2021-10-13 13:05 from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddField( model_name='course', name='points_reference', field=django.contrib.gis.db.models.fields.MultiPointField(blank=True, null=True, spatial_index=False, srid=settings.SRID, verbose_name='Points of reference'), ), ]
<commit_before># Generated by Django 3.1.13 on 2021-10-13 13:05 import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddField( model_name='course', name='points_reference', field=django.contrib.gis.db.models.fields.MultiPointField(blank=True, null=True, spatial_index=False, srid=2154, verbose_name='Points of reference'), ), ] <commit_msg>Use settings SRID in migration<commit_after>
# Generated by Django 3.1.13 on 2021-10-13 13:05 from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddField( model_name='course', name='points_reference', field=django.contrib.gis.db.models.fields.MultiPointField(blank=True, null=True, spatial_index=False, srid=settings.SRID, verbose_name='Points of reference'), ), ]
# Generated by Django 3.1.13 on 2021-10-13 13:05 import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddField( model_name='course', name='points_reference', field=django.contrib.gis.db.models.fields.MultiPointField(blank=True, null=True, spatial_index=False, srid=2154, verbose_name='Points of reference'), ), ] Use settings SRID in migration# Generated by Django 3.1.13 on 2021-10-13 13:05 from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddField( model_name='course', name='points_reference', field=django.contrib.gis.db.models.fields.MultiPointField(blank=True, null=True, spatial_index=False, srid=settings.SRID, verbose_name='Points of reference'), ), ]
<commit_before># Generated by Django 3.1.13 on 2021-10-13 13:05 import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddField( model_name='course', name='points_reference', field=django.contrib.gis.db.models.fields.MultiPointField(blank=True, null=True, spatial_index=False, srid=2154, verbose_name='Points of reference'), ), ] <commit_msg>Use settings SRID in migration<commit_after># Generated by Django 3.1.13 on 2021-10-13 13:05 from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('outdoor', '0031_course_parent_sites'), ] operations = [ migrations.AddField( model_name='course', name='points_reference', field=django.contrib.gis.db.models.fields.MultiPointField(blank=True, null=True, spatial_index=False, srid=settings.SRID, verbose_name='Points of reference'), ), ]
390f585994f6d021405de9aee3c174b054fb64a7
ietfparse/compat/parse.py
ietfparse/compat/parse.py
""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, splitnport, urlencode, urlsplit, urlunsplit) except ImportError: from urllib import quote, splitnport, urlencode from urlparse import urlsplit, urlunsplit
""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, splitnport, urlencode, urlsplit, urlunsplit) except ImportError: from urllib import quote, splitnport, urlencode as _urlencode from urlparse import urlsplit, urlunsplit # urlencode did not encode its parameters in Python 2.x so we # need to implement that ourselves for compatibility. def urlencode(query, doseq=0, safe='', encoding=None, errors=None): if encoding is None: encoding = 'utf-8' if errors is None: errors = 'strict' def encode_value(v): try: return codecs.encode(v, encoding, errors) except UnicodeError: raise except (AttributeError, TypeError): return str(v) try: quoted = [] for name, value in query: quoted.append((encode_value(name), encode_value(value))) query = quoted except UnicodeError: raise except (TypeError, ValueError) as exc: # pragma no cover # doesn't look like a sequence of tuples, maybe a dict? try: quoted = {} for name, value in query.items(): quoted[encode_value(name)] = encode_value(value) query = quoted except AttributeError: # not a dictionary either pass return _urlencode(query, doseq=doseq)
Fix urlencode for Python < 3.0.
compat: Fix urlencode for Python < 3.0. The urlencode function handles encoding in Python 3.x so our compatibility layer should do so to.
Python
bsd-3-clause
dave-shawley/ietfparse
""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, splitnport, urlencode, urlsplit, urlunsplit) except ImportError: from urllib import quote, splitnport, urlencode from urlparse import urlsplit, urlunsplit compat: Fix urlencode for Python < 3.0. The urlencode function handles encoding in Python 3.x so our compatibility layer should do so to.
""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, splitnport, urlencode, urlsplit, urlunsplit) except ImportError: from urllib import quote, splitnport, urlencode as _urlencode from urlparse import urlsplit, urlunsplit # urlencode did not encode its parameters in Python 2.x so we # need to implement that ourselves for compatibility. def urlencode(query, doseq=0, safe='', encoding=None, errors=None): if encoding is None: encoding = 'utf-8' if errors is None: errors = 'strict' def encode_value(v): try: return codecs.encode(v, encoding, errors) except UnicodeError: raise except (AttributeError, TypeError): return str(v) try: quoted = [] for name, value in query: quoted.append((encode_value(name), encode_value(value))) query = quoted except UnicodeError: raise except (TypeError, ValueError) as exc: # pragma no cover # doesn't look like a sequence of tuples, maybe a dict? try: quoted = {} for name, value in query.items(): quoted[encode_value(name)] = encode_value(value) query = quoted except AttributeError: # not a dictionary either pass return _urlencode(query, doseq=doseq)
<commit_before>""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, splitnport, urlencode, urlsplit, urlunsplit) except ImportError: from urllib import quote, splitnport, urlencode from urlparse import urlsplit, urlunsplit <commit_msg>compat: Fix urlencode for Python < 3.0. The urlencode function handles encoding in Python 3.x so our compatibility layer should do so to.<commit_after>
""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, splitnport, urlencode, urlsplit, urlunsplit) except ImportError: from urllib import quote, splitnport, urlencode as _urlencode from urlparse import urlsplit, urlunsplit # urlencode did not encode its parameters in Python 2.x so we # need to implement that ourselves for compatibility. def urlencode(query, doseq=0, safe='', encoding=None, errors=None): if encoding is None: encoding = 'utf-8' if errors is None: errors = 'strict' def encode_value(v): try: return codecs.encode(v, encoding, errors) except UnicodeError: raise except (AttributeError, TypeError): return str(v) try: quoted = [] for name, value in query: quoted.append((encode_value(name), encode_value(value))) query = quoted except UnicodeError: raise except (TypeError, ValueError) as exc: # pragma no cover # doesn't look like a sequence of tuples, maybe a dict? try: quoted = {} for name, value in query.items(): quoted[encode_value(name)] = encode_value(value) query = quoted except AttributeError: # not a dictionary either pass return _urlencode(query, doseq=doseq)
""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, splitnport, urlencode, urlsplit, urlunsplit) except ImportError: from urllib import quote, splitnport, urlencode from urlparse import urlsplit, urlunsplit compat: Fix urlencode for Python < 3.0. The urlencode function handles encoding in Python 3.x so our compatibility layer should do so to.""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, splitnport, urlencode, urlsplit, urlunsplit) except ImportError: from urllib import quote, splitnport, urlencode as _urlencode from urlparse import urlsplit, urlunsplit # urlencode did not encode its parameters in Python 2.x so we # need to implement that ourselves for compatibility. def urlencode(query, doseq=0, safe='', encoding=None, errors=None): if encoding is None: encoding = 'utf-8' if errors is None: errors = 'strict' def encode_value(v): try: return codecs.encode(v, encoding, errors) except UnicodeError: raise except (AttributeError, TypeError): return str(v) try: quoted = [] for name, value in query: quoted.append((encode_value(name), encode_value(value))) query = quoted except UnicodeError: raise except (TypeError, ValueError) as exc: # pragma no cover # doesn't look like a sequence of tuples, maybe a dict? try: quoted = {} for name, value in query.items(): quoted[encode_value(name)] = encode_value(value) query = quoted except AttributeError: # not a dictionary either pass return _urlencode(query, doseq=doseq)
<commit_before>""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, splitnport, urlencode, urlsplit, urlunsplit) except ImportError: from urllib import quote, splitnport, urlencode from urlparse import urlsplit, urlunsplit <commit_msg>compat: Fix urlencode for Python < 3.0. The urlencode function handles encoding in Python 3.x so our compatibility layer should do so to.<commit_after>""" Exports related to URL parsing. This module exports standard library functionality so that it matches :mod:`urllib.parse` from the Python 3 standard library. """ __all__ = ( 'quote', 'splitnport', 'urlencode', 'urlsplit', 'urlunsplit', ) try: from urllib.parse import ( quote, splitnport, urlencode, urlsplit, urlunsplit) except ImportError: from urllib import quote, splitnport, urlencode as _urlencode from urlparse import urlsplit, urlunsplit # urlencode did not encode its parameters in Python 2.x so we # need to implement that ourselves for compatibility. def urlencode(query, doseq=0, safe='', encoding=None, errors=None): if encoding is None: encoding = 'utf-8' if errors is None: errors = 'strict' def encode_value(v): try: return codecs.encode(v, encoding, errors) except UnicodeError: raise except (AttributeError, TypeError): return str(v) try: quoted = [] for name, value in query: quoted.append((encode_value(name), encode_value(value))) query = quoted except UnicodeError: raise except (TypeError, ValueError) as exc: # pragma no cover # doesn't look like a sequence of tuples, maybe a dict? try: quoted = {} for name, value in query.items(): quoted[encode_value(name)] = encode_value(value) query = quoted except AttributeError: # not a dictionary either pass return _urlencode(query, doseq=doseq)
67e47e0179352e9d5206fe7196762481d0bcaba4
aspen/server.py
aspen/server.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """Return a website object. Useful in testing. """ algorithm = self.get_algorithm() algorithm.run(argv=self.argv, _through='get_website_from_argv') return algorithm.state['website'] def main(self, argv=None): """http://aspen.io/cli/ """ try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does "something" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit("Oh no! Aspen crashed!") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """Return a website object. Useful in testing. """ algorithm = self.get_algorithm() state = algorithm.run(argv=self.argv, _through='get_website_from_argv') return state['website'] def main(self, argv=None): """http://aspen.io/cli/ """ try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does "something" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit("Oh no! Aspen crashed!") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': main()
Drop back to state as return val
Drop back to state as return val If we store state on Algorithm then we're not thread-safe.
Python
mit
gratipay/aspen.py,gratipay/aspen.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """Return a website object. Useful in testing. """ algorithm = self.get_algorithm() algorithm.run(argv=self.argv, _through='get_website_from_argv') return algorithm.state['website'] def main(self, argv=None): """http://aspen.io/cli/ """ try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does "something" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit("Oh no! Aspen crashed!") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': main() Drop back to state as return val If we store state on Algorithm then we're not thread-safe.
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """Return a website object. Useful in testing. """ algorithm = self.get_algorithm() state = algorithm.run(argv=self.argv, _through='get_website_from_argv') return state['website'] def main(self, argv=None): """http://aspen.io/cli/ """ try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does "something" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit("Oh no! Aspen crashed!") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': main()
<commit_before>from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """Return a website object. Useful in testing. """ algorithm = self.get_algorithm() algorithm.run(argv=self.argv, _through='get_website_from_argv') return algorithm.state['website'] def main(self, argv=None): """http://aspen.io/cli/ """ try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does "something" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit("Oh no! Aspen crashed!") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': main() <commit_msg>Drop back to state as return val If we store state on Algorithm then we're not thread-safe.<commit_after>
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """Return a website object. Useful in testing. """ algorithm = self.get_algorithm() state = algorithm.run(argv=self.argv, _through='get_website_from_argv') return state['website'] def main(self, argv=None): """http://aspen.io/cli/ """ try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does "something" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit("Oh no! Aspen crashed!") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """Return a website object. Useful in testing. """ algorithm = self.get_algorithm() algorithm.run(argv=self.argv, _through='get_website_from_argv') return algorithm.state['website'] def main(self, argv=None): """http://aspen.io/cli/ """ try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does "something" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit("Oh no! Aspen crashed!") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': main() Drop back to state as return val If we store state on Algorithm then we're not thread-safe.from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """Return a website object. Useful in testing. """ algorithm = self.get_algorithm() state = algorithm.run(argv=self.argv, _through='get_website_from_argv') return state['website'] def main(self, argv=None): """http://aspen.io/cli/ """ try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does "something" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit("Oh no! Aspen crashed!") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': main()
<commit_before>from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """Return a website object. Useful in testing. """ algorithm = self.get_algorithm() algorithm.run(argv=self.argv, _through='get_website_from_argv') return algorithm.state['website'] def main(self, argv=None): """http://aspen.io/cli/ """ try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does "something" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit("Oh no! Aspen crashed!") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': main() <commit_msg>Drop back to state as return val If we store state on Algorithm then we're not thread-safe.<commit_after>from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from algorithm import Algorithm def main(): Server().main() class Server(object): def __init__(self, argv=None): self.argv = argv def get_algorithm(self): return Algorithm('aspen.algorithms.server') def get_website(self): """Return a website object. Useful in testing. """ algorithm = self.get_algorithm() state = algorithm.run(argv=self.argv, _through='get_website_from_argv') return state['website'] def main(self, argv=None): """http://aspen.io/cli/ """ try: argv = argv if argv is not None else self.argv algorithm = self.get_algorithm() algorithm.run(argv=argv) except (SystemExit, KeyboardInterrupt): # Under some (most?) network engines, a SIGINT will be trapped by the # SIGINT signal handler above. However, gevent does "something" with # signals and our signal handler never fires. However, we *do* get a # KeyboardInterrupt here in that case. *shrug* # # See: https://github.com/gittip/aspen-python/issues/196 pass except: import aspen, traceback aspen.log_dammit("Oh no! Aspen crashed!") aspen.log_dammit(traceback.format_exc()) if __name__ == '__main__': main()
64a535ca3c311bdbbf99d87e46dba1969d7d4d7a
blog/models.py
blog/models.py
from django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): user = models.ForeignKey(User) title = models.CharField(max_lenght = 120) text = models.TextField() date = models.DateTimeField(auto_now_add = True) class Comment(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(BlogPost) text = models.TextField() date = models.DateTimeField(auto_now_add = True)
from django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length = 120) text = models.TextField() date = models.DateTimeField(auto_now_add = True) class Comment(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(BlogPost) text = models.TextField() date = models.DateTimeField(auto_now_add = True)
Fix a typo in BlogPost model
Fix a typo in BlogPost model
Python
mit
andreagrandi/bloggato,andreagrandi/bloggato
from django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): user = models.ForeignKey(User) title = models.CharField(max_lenght = 120) text = models.TextField() date = models.DateTimeField(auto_now_add = True) class Comment(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(BlogPost) text = models.TextField() date = models.DateTimeField(auto_now_add = True) Fix a typo in BlogPost model
from django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length = 120) text = models.TextField() date = models.DateTimeField(auto_now_add = True) class Comment(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(BlogPost) text = models.TextField() date = models.DateTimeField(auto_now_add = True)
<commit_before>from django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): user = models.ForeignKey(User) title = models.CharField(max_lenght = 120) text = models.TextField() date = models.DateTimeField(auto_now_add = True) class Comment(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(BlogPost) text = models.TextField() date = models.DateTimeField(auto_now_add = True) <commit_msg>Fix a typo in BlogPost model<commit_after>
from django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length = 120) text = models.TextField() date = models.DateTimeField(auto_now_add = True) class Comment(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(BlogPost) text = models.TextField() date = models.DateTimeField(auto_now_add = True)
from django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): user = models.ForeignKey(User) title = models.CharField(max_lenght = 120) text = models.TextField() date = models.DateTimeField(auto_now_add = True) class Comment(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(BlogPost) text = models.TextField() date = models.DateTimeField(auto_now_add = True) Fix a typo in BlogPost modelfrom django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length = 120) text = models.TextField() date = models.DateTimeField(auto_now_add = True) class Comment(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(BlogPost) text = models.TextField() date = models.DateTimeField(auto_now_add = True)
<commit_before>from django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): user = models.ForeignKey(User) title = models.CharField(max_lenght = 120) text = models.TextField() date = models.DateTimeField(auto_now_add = True) class Comment(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(BlogPost) text = models.TextField() date = models.DateTimeField(auto_now_add = True) <commit_msg>Fix a typo in BlogPost model<commit_after>from django.db import models from django.contrib.auth.models import User class BlogPost(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length = 120) text = models.TextField() date = models.DateTimeField(auto_now_add = True) class Comment(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(BlogPost) text = models.TextField() date = models.DateTimeField(auto_now_add = True)
94d4cb6a5c5d0c43e056bec73584d798f88ff70e
bnw_handlers/command_login.py
bnw_handlers/command_login.py
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=%s' % ( get_webui_base(request.user), request.user.get('login_key', ''))) @defer.inlineCallbacks def cmd_passlogin(request,user,password): """ Логин паролем """ if not (user and password): defer.returnValue(dict(ok=False,desc='Credentials cannot be empty')) u = yield objs.User.find_one({'name':user,'settings.password':password}) if u: defer.returnValue(dict(ok=True, desc=u.get('login_key','Successful, but no login key.'))) else: defer.returnValue(dict(ok=False, desc='Sorry, Dave.'))
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=%s' % ( get_webui_base(request.user), request.user.get('login_key', ''))) @defer.inlineCallbacks def cmd_passlogin(request,user=None,password=None): """ Логин паролем """ if not (user and password): defer.returnValue(dict(ok=False,desc='Credentials cannot be empty.')) u = yield objs.User.find_one({'name':user,'settings.password':password}) if u: defer.returnValue(dict(ok=True, desc=u.get('login_key','Successful, but no login key.'))) else: defer.returnValue(dict(ok=False, desc='Sorry, Dave.'))
Fix 500 error on empty passlogin values
Fix 500 error on empty passlogin values
Python
bsd-2-clause
stiletto/bnw,un-def/bnw,stiletto/bnw,ojab/bnw,stiletto/bnw,ojab/bnw,un-def/bnw,stiletto/bnw,ojab/bnw,un-def/bnw,ojab/bnw,un-def/bnw
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=%s' % ( get_webui_base(request.user), request.user.get('login_key', ''))) @defer.inlineCallbacks def cmd_passlogin(request,user,password): """ Логин паролем """ if not (user and password): defer.returnValue(dict(ok=False,desc='Credentials cannot be empty')) u = yield objs.User.find_one({'name':user,'settings.password':password}) if u: defer.returnValue(dict(ok=True, desc=u.get('login_key','Successful, but no login key.'))) else: defer.returnValue(dict(ok=False, desc='Sorry, Dave.')) Fix 500 error on empty passlogin values
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=%s' % ( get_webui_base(request.user), request.user.get('login_key', ''))) @defer.inlineCallbacks def cmd_passlogin(request,user=None,password=None): """ Логин паролем """ if not (user and password): defer.returnValue(dict(ok=False,desc='Credentials cannot be empty.')) u = yield objs.User.find_one({'name':user,'settings.password':password}) if u: defer.returnValue(dict(ok=True, desc=u.get('login_key','Successful, but no login key.'))) else: defer.returnValue(dict(ok=False, desc='Sorry, Dave.'))
<commit_before># -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=%s' % ( get_webui_base(request.user), request.user.get('login_key', ''))) @defer.inlineCallbacks def cmd_passlogin(request,user,password): """ Логин паролем """ if not (user and password): defer.returnValue(dict(ok=False,desc='Credentials cannot be empty')) u = yield objs.User.find_one({'name':user,'settings.password':password}) if u: defer.returnValue(dict(ok=True, desc=u.get('login_key','Successful, but no login key.'))) else: defer.returnValue(dict(ok=False, desc='Sorry, Dave.')) <commit_msg>Fix 500 error on empty passlogin values<commit_after>
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=%s' % ( get_webui_base(request.user), request.user.get('login_key', ''))) @defer.inlineCallbacks def cmd_passlogin(request,user=None,password=None): """ Логин паролем """ if not (user and password): defer.returnValue(dict(ok=False,desc='Credentials cannot be empty.')) u = yield objs.User.find_one({'name':user,'settings.password':password}) if u: defer.returnValue(dict(ok=True, desc=u.get('login_key','Successful, but no login key.'))) else: defer.returnValue(dict(ok=False, desc='Sorry, Dave.'))
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=%s' % ( get_webui_base(request.user), request.user.get('login_key', ''))) @defer.inlineCallbacks def cmd_passlogin(request,user,password): """ Логин паролем """ if not (user and password): defer.returnValue(dict(ok=False,desc='Credentials cannot be empty')) u = yield objs.User.find_one({'name':user,'settings.password':password}) if u: defer.returnValue(dict(ok=True, desc=u.get('login_key','Successful, but no login key.'))) else: defer.returnValue(dict(ok=False, desc='Sorry, Dave.')) Fix 500 error on empty passlogin values# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=%s' % ( get_webui_base(request.user), request.user.get('login_key', ''))) @defer.inlineCallbacks def cmd_passlogin(request,user=None,password=None): """ Логин паролем """ if not (user and password): defer.returnValue(dict(ok=False,desc='Credentials cannot be empty.')) u = yield objs.User.find_one({'name':user,'settings.password':password}) if u: defer.returnValue(dict(ok=True, desc=u.get('login_key','Successful, but no login key.'))) else: defer.returnValue(dict(ok=False, desc='Sorry, Dave.'))
<commit_before># -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=%s' % ( get_webui_base(request.user), request.user.get('login_key', ''))) @defer.inlineCallbacks def cmd_passlogin(request,user,password): """ Логин паролем """ if not (user and password): defer.returnValue(dict(ok=False,desc='Credentials cannot be empty')) u = yield objs.User.find_one({'name':user,'settings.password':password}) if u: defer.returnValue(dict(ok=True, desc=u.get('login_key','Successful, but no login key.'))) else: defer.returnValue(dict(ok=False, desc='Sorry, Dave.')) <commit_msg>Fix 500 error on empty passlogin values<commit_after># -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * from bnw_core.base import get_webui_base import bnw_core.bnw_objects as objs from twisted.internet import defer @require_auth def cmd_login(request): """ Логин-ссылка """ return dict( ok=True, desc='%s/login?key=%s' % ( get_webui_base(request.user), request.user.get('login_key', ''))) @defer.inlineCallbacks def cmd_passlogin(request,user=None,password=None): """ Логин паролем """ if not (user and password): defer.returnValue(dict(ok=False,desc='Credentials cannot be empty.')) u = yield objs.User.find_one({'name':user,'settings.password':password}) if u: defer.returnValue(dict(ok=True, desc=u.get('login_key','Successful, but no login key.'))) else: defer.returnValue(dict(ok=False, desc='Sorry, Dave.'))
743b678a2113f7f93d4c0cc27aa73745700a460a
bazaar/listings/filters.py
bazaar/listings/filters.py
from __future__ import unicode_literals import django_filters from .models import Listing class ListingFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_type="icontains") class Meta: model = Listing fields = ['title', "publishings__store", "publishings__available_units"]
from __future__ import unicode_literals from django import forms import django_filters from ..filters import BaseFilterSet from .models import Listing class LowStockListingFilter(django_filters.Filter): field_class = forms.BooleanField def filter(self, qs, value): if value: qs = qs.filter(pk__in=Listing.objects.low_stock_ids()) return qs class ListingFilter(BaseFilterSet): title = django_filters.CharFilter(lookup_type="icontains") low_stock = LowStockListingFilter() class Meta: model = Listing fields = ["title", "publishings__store", "publishings__available_units"]
Add filter for low stock listings
Add filter for low stock listings
Python
bsd-2-clause
meghabhoj/NEWBAZAAR,meghabhoj/NEWBAZAAR,evonove/django-bazaar,meghabhoj/NEWBAZAAR,evonove/django-bazaar,evonove/django-bazaar
from __future__ import unicode_literals import django_filters from .models import Listing class ListingFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_type="icontains") class Meta: model = Listing fields = ['title', "publishings__store", "publishings__available_units"] Add filter for low stock listings
from __future__ import unicode_literals from django import forms import django_filters from ..filters import BaseFilterSet from .models import Listing class LowStockListingFilter(django_filters.Filter): field_class = forms.BooleanField def filter(self, qs, value): if value: qs = qs.filter(pk__in=Listing.objects.low_stock_ids()) return qs class ListingFilter(BaseFilterSet): title = django_filters.CharFilter(lookup_type="icontains") low_stock = LowStockListingFilter() class Meta: model = Listing fields = ["title", "publishings__store", "publishings__available_units"]
<commit_before>from __future__ import unicode_literals import django_filters from .models import Listing class ListingFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_type="icontains") class Meta: model = Listing fields = ['title', "publishings__store", "publishings__available_units"] <commit_msg>Add filter for low stock listings<commit_after>
from __future__ import unicode_literals from django import forms import django_filters from ..filters import BaseFilterSet from .models import Listing class LowStockListingFilter(django_filters.Filter): field_class = forms.BooleanField def filter(self, qs, value): if value: qs = qs.filter(pk__in=Listing.objects.low_stock_ids()) return qs class ListingFilter(BaseFilterSet): title = django_filters.CharFilter(lookup_type="icontains") low_stock = LowStockListingFilter() class Meta: model = Listing fields = ["title", "publishings__store", "publishings__available_units"]
from __future__ import unicode_literals import django_filters from .models import Listing class ListingFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_type="icontains") class Meta: model = Listing fields = ['title', "publishings__store", "publishings__available_units"] Add filter for low stock listingsfrom __future__ import unicode_literals from django import forms import django_filters from ..filters import BaseFilterSet from .models import Listing class LowStockListingFilter(django_filters.Filter): field_class = forms.BooleanField def filter(self, qs, value): if value: qs = qs.filter(pk__in=Listing.objects.low_stock_ids()) return qs class ListingFilter(BaseFilterSet): title = django_filters.CharFilter(lookup_type="icontains") low_stock = LowStockListingFilter() class Meta: model = Listing fields = ["title", "publishings__store", "publishings__available_units"]
<commit_before>from __future__ import unicode_literals import django_filters from .models import Listing class ListingFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_type="icontains") class Meta: model = Listing fields = ['title', "publishings__store", "publishings__available_units"] <commit_msg>Add filter for low stock listings<commit_after>from __future__ import unicode_literals from django import forms import django_filters from ..filters import BaseFilterSet from .models import Listing class LowStockListingFilter(django_filters.Filter): field_class = forms.BooleanField def filter(self, qs, value): if value: qs = qs.filter(pk__in=Listing.objects.low_stock_ids()) return qs class ListingFilter(BaseFilterSet): title = django_filters.CharFilter(lookup_type="icontains") low_stock = LowStockListingFilter() class Meta: model = Listing fields = ["title", "publishings__store", "publishings__available_units"]
8ba164dca3d55d18e6b65c6f1e326fb3c0a2c11d
jarn/mkrelease/process.py
jarn/mkrelease/process.py
from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None): self.quiet = quiet self.env = env def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ trace(cmd) if self.quiet: echo = echo2 = False try: return run(cmd, echo, echo2, shell=True, env=self.env) except KeyboardInterrupt: if catch_keyboard_interrupts: return self.rc_keyboard_interrupt, [] raise def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc
from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None, runner=run): self.quiet = quiet self.env = env self.runner = runner def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ trace(cmd) if self.quiet: echo = echo2 = False try: return self.runner(cmd, echo, echo2, shell=True, env=self.env) except KeyboardInterrupt: if catch_keyboard_interrupts: return self.rc_keyboard_interrupt, [] raise def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc
Allow to pass a runner to Process.
Allow to pass a runner to Process.
Python
bsd-2-clause
Jarn/jarn.mkrelease
from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None): self.quiet = quiet self.env = env def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ trace(cmd) if self.quiet: echo = echo2 = False try: return run(cmd, echo, echo2, shell=True, env=self.env) except KeyboardInterrupt: if catch_keyboard_interrupts: return self.rc_keyboard_interrupt, [] raise def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc Allow to pass a runner to Process.
from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None, runner=run): self.quiet = quiet self.env = env self.runner = runner def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ trace(cmd) if self.quiet: echo = echo2 = False try: return self.runner(cmd, echo, echo2, shell=True, env=self.env) except KeyboardInterrupt: if catch_keyboard_interrupts: return self.rc_keyboard_interrupt, [] raise def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc
<commit_before>from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None): self.quiet = quiet self.env = env def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ trace(cmd) if self.quiet: echo = echo2 = False try: return run(cmd, echo, echo2, shell=True, env=self.env) except KeyboardInterrupt: if catch_keyboard_interrupts: return self.rc_keyboard_interrupt, [] raise def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc <commit_msg>Allow to pass a runner to Process.<commit_after>
from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None, runner=run): self.quiet = quiet self.env = env self.runner = runner def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ trace(cmd) if self.quiet: echo = echo2 = False try: return self.runner(cmd, echo, echo2, shell=True, env=self.env) except KeyboardInterrupt: if catch_keyboard_interrupts: return self.rc_keyboard_interrupt, [] raise def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc
from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None): self.quiet = quiet self.env = env def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ trace(cmd) if self.quiet: echo = echo2 = False try: return run(cmd, echo, echo2, shell=True, env=self.env) except KeyboardInterrupt: if catch_keyboard_interrupts: return self.rc_keyboard_interrupt, [] raise def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc Allow to pass a runner to Process.from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None, runner=run): self.quiet = quiet self.env = env self.runner = runner def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ trace(cmd) if self.quiet: echo = echo2 = False try: return self.runner(cmd, echo, echo2, shell=True, env=self.env) except KeyboardInterrupt: if catch_keyboard_interrupts: return self.rc_keyboard_interrupt, [] raise def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc
<commit_before>from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None): self.quiet = quiet self.env = env def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ trace(cmd) if self.quiet: echo = echo2 = False try: return run(cmd, echo, echo2, shell=True, env=self.env) except KeyboardInterrupt: if catch_keyboard_interrupts: return self.rc_keyboard_interrupt, [] raise def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc <commit_msg>Allow to pass a runner to Process.<commit_after>from __future__ import absolute_import import os from .tee import run from .exit import trace catch_keyboard_interrupts = True class Process(object): """Process related functions using the tee module.""" rc_keyboard_interrupt = 54321 def __init__(self, quiet=False, env=None, runner=run): self.quiet = quiet self.env = env self.runner = runner def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ trace(cmd) if self.quiet: echo = echo2 = False try: return self.runner(cmd, echo, echo2, shell=True, env=self.env) except KeyboardInterrupt: if catch_keyboard_interrupts: return self.rc_keyboard_interrupt, [] raise def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc
1180767250af525f9d11c6b3b7f45c3d9b1e00f0
skyfield/tests/test_searchlib.py
skyfield/tests/test_searchlib.py
from numpy import add, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): return indices[diff(indices, prepend=-1) != 0] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer(indices, [0, 1]), -1) left = _remove_adjacent_duplicates(left) right = left + 1 return left, right def test_brackets_of_simple_peak(): y = array((10, 11, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2], [2, 3]] def test_brackets_of_small_plateau(): y = array((10, 11, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 3], [2, 3, 4]] def test_brackets_of_wide_plateau(): y = array((10, 11, 12, 12, 12, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 5, 6], [2, 3, 6, 7]]
from numpy import add, append, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): mask = diff(indices) != 0 mask = append(mask, [True]) return indices[mask] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer(indices, [0, 1]), -1) left = _remove_adjacent_duplicates(left) right = left + 1 return left, right def test_brackets_of_simple_peak(): y = array((10, 11, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2], [2, 3]] def test_brackets_of_small_plateau(): y = array((10, 11, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 3], [2, 3, 4]] def test_brackets_of_wide_plateau(): y = array((10, 11, 12, 12, 12, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 5, 6], [2, 3, 6, 7]]
Fix use of a too-recent NumPy feature
Fix use of a too-recent NumPy feature
Python
mit
skyfielders/python-skyfield,skyfielders/python-skyfield
from numpy import add, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): return indices[diff(indices, prepend=-1) != 0] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer(indices, [0, 1]), -1) left = _remove_adjacent_duplicates(left) right = left + 1 return left, right def test_brackets_of_simple_peak(): y = array((10, 11, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2], [2, 3]] def test_brackets_of_small_plateau(): y = array((10, 11, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 3], [2, 3, 4]] def test_brackets_of_wide_plateau(): y = array((10, 11, 12, 12, 12, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 5, 6], [2, 3, 6, 7]] Fix use of a too-recent NumPy feature
from numpy import add, append, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): mask = diff(indices) != 0 mask = append(mask, [True]) return indices[mask] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer(indices, [0, 1]), -1) left = _remove_adjacent_duplicates(left) right = left + 1 return left, right def test_brackets_of_simple_peak(): y = array((10, 11, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2], [2, 3]] def test_brackets_of_small_plateau(): y = array((10, 11, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 3], [2, 3, 4]] def test_brackets_of_wide_plateau(): y = array((10, 11, 12, 12, 12, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 5, 6], [2, 3, 6, 7]]
<commit_before>from numpy import add, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): return indices[diff(indices, prepend=-1) != 0] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer(indices, [0, 1]), -1) left = _remove_adjacent_duplicates(left) right = left + 1 return left, right def test_brackets_of_simple_peak(): y = array((10, 11, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2], [2, 3]] def test_brackets_of_small_plateau(): y = array((10, 11, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 3], [2, 3, 4]] def test_brackets_of_wide_plateau(): y = array((10, 11, 12, 12, 12, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 5, 6], [2, 3, 6, 7]] <commit_msg>Fix use of a too-recent NumPy feature<commit_after>
from numpy import add, append, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): mask = diff(indices) != 0 mask = append(mask, [True]) return indices[mask] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer(indices, [0, 1]), -1) left = _remove_adjacent_duplicates(left) right = left + 1 return left, right def test_brackets_of_simple_peak(): y = array((10, 11, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2], [2, 3]] def test_brackets_of_small_plateau(): y = array((10, 11, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 3], [2, 3, 4]] def test_brackets_of_wide_plateau(): y = array((10, 11, 12, 12, 12, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 5, 6], [2, 3, 6, 7]]
from numpy import add, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): return indices[diff(indices, prepend=-1) != 0] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer(indices, [0, 1]), -1) left = _remove_adjacent_duplicates(left) right = left + 1 return left, right def test_brackets_of_simple_peak(): y = array((10, 11, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2], [2, 3]] def test_brackets_of_small_plateau(): y = array((10, 11, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 3], [2, 3, 4]] def test_brackets_of_wide_plateau(): y = array((10, 11, 12, 12, 12, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 5, 6], [2, 3, 6, 7]] Fix use of a too-recent NumPy featurefrom numpy import add, append, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): mask = diff(indices) != 0 mask = append(mask, [True]) return indices[mask] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer(indices, [0, 1]), -1) left = _remove_adjacent_duplicates(left) right = left + 1 return left, right def test_brackets_of_simple_peak(): y = array((10, 11, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2], [2, 3]] def test_brackets_of_small_plateau(): y = array((10, 11, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 3], [2, 3, 4]] def test_brackets_of_wide_plateau(): y = array((10, 11, 12, 12, 12, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 5, 6], [2, 3, 6, 7]]
<commit_before>from numpy import add, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): return indices[diff(indices, prepend=-1) != 0] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer(indices, [0, 1]), -1) left = _remove_adjacent_duplicates(left) right = left + 1 return left, right def test_brackets_of_simple_peak(): y = array((10, 11, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2], [2, 3]] def test_brackets_of_small_plateau(): y = array((10, 11, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 3], [2, 3, 4]] def test_brackets_of_wide_plateau(): y = array((10, 11, 12, 12, 12, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 5, 6], [2, 3, 6, 7]] <commit_msg>Fix use of a too-recent NumPy feature<commit_after>from numpy import add, append, array, diff, flatnonzero, reshape, sign def _remove_adjacent_duplicates(indices): mask = diff(indices) != 0 mask = append(mask, [True]) return indices[mask] def _choose_brackets(y): dsd = diff(sign(diff(y))) indices = flatnonzero(dsd < 0) left = reshape(add.outer(indices, [0, 1]), -1) left = _remove_adjacent_duplicates(left) right = left + 1 return left, right def test_brackets_of_simple_peak(): y = array((10, 11, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2], [2, 3]] def test_brackets_of_small_plateau(): y = array((10, 11, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 3], [2, 3, 4]] def test_brackets_of_wide_plateau(): y = array((10, 11, 12, 12, 12, 12, 12, 11, 10)) assert [list(v) for v in _choose_brackets(y)] == [[1, 2, 5, 6], [2, 3, 6, 7]]
7809a22a67f9c9d67d4765c2029d9b30656606bc
hello.py
hello.py
#!/usr/bin/python3.4 print("hello")
#!/usr/bin/python3.4 def greeting(msg): print(msg) if __name__=='__main__': greeting("hello")
Add function to print a message
Add function to print a message
Python
mit
ag4ml/cs3240-labdemo
#!/usr/bin/python3.4 print("hello") Add function to print a message
#!/usr/bin/python3.4 def greeting(msg): print(msg) if __name__=='__main__': greeting("hello")
<commit_before>#!/usr/bin/python3.4 print("hello") <commit_msg>Add function to print a message<commit_after>
#!/usr/bin/python3.4 def greeting(msg): print(msg) if __name__=='__main__': greeting("hello")
#!/usr/bin/python3.4 print("hello") Add function to print a message#!/usr/bin/python3.4 def greeting(msg): print(msg) if __name__=='__main__': greeting("hello")
<commit_before>#!/usr/bin/python3.4 print("hello") <commit_msg>Add function to print a message<commit_after>#!/usr/bin/python3.4 def greeting(msg): print(msg) if __name__=='__main__': greeting("hello")
d913b0a7f0031ca96ebe8f653f232a151cfca0bf
app/runserver.py
app/runserver.py
from flask_script import Manager from config.config import app # from mailchimp.redis_init import init_redis_with_mailchimp manager = Manager(app) @manager.command def run_local(): #init_redis_with_mailchimp(redis_server) app.run(debug=True) @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run()
from flask_script import Manager from config.config import app manager = Manager(app) @manager.command def run_local(): app.run(debug=True) @manager.command def run_test(): # To-Do pass @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run()
Add flask-script package to manage deploys
Add flask-script package to manage deploys
Python
mit
tforrest/soda-automation,tforrest/soda-automation
from flask_script import Manager from config.config import app # from mailchimp.redis_init import init_redis_with_mailchimp manager = Manager(app) @manager.command def run_local(): #init_redis_with_mailchimp(redis_server) app.run(debug=True) @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run() Add flask-script package to manage deploys
from flask_script import Manager from config.config import app manager = Manager(app) @manager.command def run_local(): app.run(debug=True) @manager.command def run_test(): # To-Do pass @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run()
<commit_before>from flask_script import Manager from config.config import app # from mailchimp.redis_init import init_redis_with_mailchimp manager = Manager(app) @manager.command def run_local(): #init_redis_with_mailchimp(redis_server) app.run(debug=True) @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run() <commit_msg>Add flask-script package to manage deploys<commit_after>
from flask_script import Manager from config.config import app manager = Manager(app) @manager.command def run_local(): app.run(debug=True) @manager.command def run_test(): # To-Do pass @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run()
from flask_script import Manager from config.config import app # from mailchimp.redis_init import init_redis_with_mailchimp manager = Manager(app) @manager.command def run_local(): #init_redis_with_mailchimp(redis_server) app.run(debug=True) @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run() Add flask-script package to manage deploysfrom flask_script import Manager from config.config import app manager = Manager(app) @manager.command def run_local(): app.run(debug=True) @manager.command def run_test(): # To-Do pass @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run()
<commit_before>from flask_script import Manager from config.config import app # from mailchimp.redis_init import init_redis_with_mailchimp manager = Manager(app) @manager.command def run_local(): #init_redis_with_mailchimp(redis_server) app.run(debug=True) @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run() <commit_msg>Add flask-script package to manage deploys<commit_after>from flask_script import Manager from config.config import app manager = Manager(app) @manager.command def run_local(): app.run(debug=True) @manager.command def run_test(): # To-Do pass @manager.command def run_production(): # TO-DO pass if __name__ == '__main__': manager.run()
ff545e2a60cc35537626acd16fb6fc39badef560
openedx/core/djangoapps/cors_csrf/authentication.py
openedx/core/djangoapps/cors_csrf/authentication.py
""" Django Rest Framework Authentication classes for cross-domain end-points. """ from rest_framework import authentication from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check class SessionAuthenticationCrossDomainCsrf(authentication.SessionAuthentication): """ Session authentication that skips the referer check over secure connections. Django Rest Framework's `SessionAuthentication` class calls Django's CSRF middleware implementation directly, which bypasses the middleware stack. This version of `SessionAuthentication` performs the same workaround as `CorsCSRFMiddleware` to skip the referer check for whitelisted domains over a secure connection. See `cors_csrf.middleware` for more information. Since this subclass overrides only the `enforce_csrf()` method, it can be mixed in with other `SessionAuthentication` subclasses. """ def enforce_csrf(self, request): """ Skip the referer check if the cross-domain request is allowed. """ if is_cross_domain_request_allowed(request): with skip_cross_domain_referer_check(request): return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) else: return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request)
""" Django Rest Framework Authentication classes for cross-domain end-points. """ import django from django.middleware.csrf import CsrfViewMiddleware from rest_framework import authentication from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check class SessionAuthenticationCrossDomainCsrf(authentication.SessionAuthentication): """ Session authentication that skips the referer check over secure connections. Django Rest Framework's `SessionAuthentication` class calls Django's CSRF middleware implementation directly, which bypasses the middleware stack. This version of `SessionAuthentication` performs the same workaround as `CorsCSRFMiddleware` to skip the referer check for whitelisted domains over a secure connection. See `cors_csrf.middleware` for more information. Since this subclass overrides only the `enforce_csrf()` method, it can be mixed in with other `SessionAuthentication` subclasses. """ # TODO: Remove Django 1.11 upgrade shim # SHIM: Call new process_request in Django 1.11 to process CSRF token in cookie. def _process_enforce_csrf(self, request): if django.VERSION >= (1, 11): CsrfViewMiddleware().process_request(request) return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) def enforce_csrf(self, request): """ Skip the referer check if the cross-domain request is allowed. """ if is_cross_domain_request_allowed(request): with skip_cross_domain_referer_check(request): return self._process_enforce_csrf(request) else: return self._process_enforce_csrf(request)
Handle different cookie processing for Django 1.11
Handle different cookie processing for Django 1.11
Python
agpl-3.0
ahmedaljazzar/edx-platform,TeachAtTUM/edx-platform,arbrandes/edx-platform,kmoocdev2/edx-platform,eduNEXT/edunext-platform,gsehub/edx-platform,philanthropy-u/edx-platform,Edraak/edraak-platform,edx-solutions/edx-platform,Edraak/edraak-platform,proversity-org/edx-platform,TeachAtTUM/edx-platform,Stanford-Online/edx-platform,angelapper/edx-platform,gymnasium/edx-platform,edx/edx-platform,CredoReference/edx-platform,msegado/edx-platform,gsehub/edx-platform,msegado/edx-platform,Edraak/edraak-platform,arbrandes/edx-platform,mitocw/edx-platform,msegado/edx-platform,proversity-org/edx-platform,CredoReference/edx-platform,stvstnfrd/edx-platform,eduNEXT/edunext-platform,philanthropy-u/edx-platform,kmoocdev2/edx-platform,procangroup/edx-platform,ahmedaljazzar/edx-platform,jolyonb/edx-platform,BehavioralInsightsTeam/edx-platform,appsembler/edx-platform,eduNEXT/edx-platform,jolyonb/edx-platform,kmoocdev2/edx-platform,stvstnfrd/edx-platform,jolyonb/edx-platform,EDUlib/edx-platform,a-parhom/edx-platform,cpennington/edx-platform,stvstnfrd/edx-platform,edx/edx-platform,gymnasium/edx-platform,gsehub/edx-platform,msegado/edx-platform,procangroup/edx-platform,ahmedaljazzar/edx-platform,stvstnfrd/edx-platform,TeachAtTUM/edx-platform,appsembler/edx-platform,edx/edx-platform,angelapper/edx-platform,ahmedaljazzar/edx-platform,eduNEXT/edx-platform,gymnasium/edx-platform,EDUlib/edx-platform,kmoocdev2/edx-platform,a-parhom/edx-platform,edx-solutions/edx-platform,kmoocdev2/edx-platform,teltek/edx-platform,Stanford-Online/edx-platform,CredoReference/edx-platform,gsehub/edx-platform,ESOedX/edx-platform,proversity-org/edx-platform,Edraak/edraak-platform,arbrandes/edx-platform,procangroup/edx-platform,a-parhom/edx-platform,BehavioralInsightsTeam/edx-platform,angelapper/edx-platform,ESOedX/edx-platform,gymnasium/edx-platform,mitocw/edx-platform,ESOedX/edx-platform,edx/edx-platform,a-parhom/edx-platform,mitocw/edx-platform,eduNEXT/edx-platform,edx-solutions/edx-platform,msegado/edx-platform,TeachAtTUM/edx-platform,teltek/edx-platform,edx-solutions/edx-platform,CredoReference/edx-platform,BehavioralInsightsTeam/edx-platform,teltek/edx-platform,appsembler/edx-platform,EDUlib/edx-platform,eduNEXT/edunext-platform,EDUlib/edx-platform,cpennington/edx-platform,procangroup/edx-platform,ESOedX/edx-platform,cpennington/edx-platform,jolyonb/edx-platform,angelapper/edx-platform,mitocw/edx-platform,eduNEXT/edunext-platform,BehavioralInsightsTeam/edx-platform,Stanford-Online/edx-platform,philanthropy-u/edx-platform,teltek/edx-platform,eduNEXT/edx-platform,arbrandes/edx-platform,proversity-org/edx-platform,appsembler/edx-platform,Stanford-Online/edx-platform,cpennington/edx-platform,philanthropy-u/edx-platform
""" Django Rest Framework Authentication classes for cross-domain end-points. """ from rest_framework import authentication from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check class SessionAuthenticationCrossDomainCsrf(authentication.SessionAuthentication): """ Session authentication that skips the referer check over secure connections. Django Rest Framework's `SessionAuthentication` class calls Django's CSRF middleware implementation directly, which bypasses the middleware stack. This version of `SessionAuthentication` performs the same workaround as `CorsCSRFMiddleware` to skip the referer check for whitelisted domains over a secure connection. See `cors_csrf.middleware` for more information. Since this subclass overrides only the `enforce_csrf()` method, it can be mixed in with other `SessionAuthentication` subclasses. """ def enforce_csrf(self, request): """ Skip the referer check if the cross-domain request is allowed. """ if is_cross_domain_request_allowed(request): with skip_cross_domain_referer_check(request): return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) else: return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) Handle different cookie processing for Django 1.11
""" Django Rest Framework Authentication classes for cross-domain end-points. """ import django from django.middleware.csrf import CsrfViewMiddleware from rest_framework import authentication from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check class SessionAuthenticationCrossDomainCsrf(authentication.SessionAuthentication): """ Session authentication that skips the referer check over secure connections. Django Rest Framework's `SessionAuthentication` class calls Django's CSRF middleware implementation directly, which bypasses the middleware stack. This version of `SessionAuthentication` performs the same workaround as `CorsCSRFMiddleware` to skip the referer check for whitelisted domains over a secure connection. See `cors_csrf.middleware` for more information. Since this subclass overrides only the `enforce_csrf()` method, it can be mixed in with other `SessionAuthentication` subclasses. """ # TODO: Remove Django 1.11 upgrade shim # SHIM: Call new process_request in Django 1.11 to process CSRF token in cookie. def _process_enforce_csrf(self, request): if django.VERSION >= (1, 11): CsrfViewMiddleware().process_request(request) return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) def enforce_csrf(self, request): """ Skip the referer check if the cross-domain request is allowed. """ if is_cross_domain_request_allowed(request): with skip_cross_domain_referer_check(request): return self._process_enforce_csrf(request) else: return self._process_enforce_csrf(request)
<commit_before>""" Django Rest Framework Authentication classes for cross-domain end-points. """ from rest_framework import authentication from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check class SessionAuthenticationCrossDomainCsrf(authentication.SessionAuthentication): """ Session authentication that skips the referer check over secure connections. Django Rest Framework's `SessionAuthentication` class calls Django's CSRF middleware implementation directly, which bypasses the middleware stack. This version of `SessionAuthentication` performs the same workaround as `CorsCSRFMiddleware` to skip the referer check for whitelisted domains over a secure connection. See `cors_csrf.middleware` for more information. Since this subclass overrides only the `enforce_csrf()` method, it can be mixed in with other `SessionAuthentication` subclasses. """ def enforce_csrf(self, request): """ Skip the referer check if the cross-domain request is allowed. """ if is_cross_domain_request_allowed(request): with skip_cross_domain_referer_check(request): return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) else: return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) <commit_msg>Handle different cookie processing for Django 1.11<commit_after>
""" Django Rest Framework Authentication classes for cross-domain end-points. """ import django from django.middleware.csrf import CsrfViewMiddleware from rest_framework import authentication from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check class SessionAuthenticationCrossDomainCsrf(authentication.SessionAuthentication): """ Session authentication that skips the referer check over secure connections. Django Rest Framework's `SessionAuthentication` class calls Django's CSRF middleware implementation directly, which bypasses the middleware stack. This version of `SessionAuthentication` performs the same workaround as `CorsCSRFMiddleware` to skip the referer check for whitelisted domains over a secure connection. See `cors_csrf.middleware` for more information. Since this subclass overrides only the `enforce_csrf()` method, it can be mixed in with other `SessionAuthentication` subclasses. """ # TODO: Remove Django 1.11 upgrade shim # SHIM: Call new process_request in Django 1.11 to process CSRF token in cookie. def _process_enforce_csrf(self, request): if django.VERSION >= (1, 11): CsrfViewMiddleware().process_request(request) return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) def enforce_csrf(self, request): """ Skip the referer check if the cross-domain request is allowed. """ if is_cross_domain_request_allowed(request): with skip_cross_domain_referer_check(request): return self._process_enforce_csrf(request) else: return self._process_enforce_csrf(request)
""" Django Rest Framework Authentication classes for cross-domain end-points. """ from rest_framework import authentication from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check class SessionAuthenticationCrossDomainCsrf(authentication.SessionAuthentication): """ Session authentication that skips the referer check over secure connections. Django Rest Framework's `SessionAuthentication` class calls Django's CSRF middleware implementation directly, which bypasses the middleware stack. This version of `SessionAuthentication` performs the same workaround as `CorsCSRFMiddleware` to skip the referer check for whitelisted domains over a secure connection. See `cors_csrf.middleware` for more information. Since this subclass overrides only the `enforce_csrf()` method, it can be mixed in with other `SessionAuthentication` subclasses. """ def enforce_csrf(self, request): """ Skip the referer check if the cross-domain request is allowed. """ if is_cross_domain_request_allowed(request): with skip_cross_domain_referer_check(request): return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) else: return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) Handle different cookie processing for Django 1.11""" Django Rest Framework Authentication classes for cross-domain end-points. """ import django from django.middleware.csrf import CsrfViewMiddleware from rest_framework import authentication from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check class SessionAuthenticationCrossDomainCsrf(authentication.SessionAuthentication): """ Session authentication that skips the referer check over secure connections. Django Rest Framework's `SessionAuthentication` class calls Django's CSRF middleware implementation directly, which bypasses the middleware stack. This version of `SessionAuthentication` performs the same workaround as `CorsCSRFMiddleware` to skip the referer check for whitelisted domains over a secure connection. See `cors_csrf.middleware` for more information. Since this subclass overrides only the `enforce_csrf()` method, it can be mixed in with other `SessionAuthentication` subclasses. """ # TODO: Remove Django 1.11 upgrade shim # SHIM: Call new process_request in Django 1.11 to process CSRF token in cookie. def _process_enforce_csrf(self, request): if django.VERSION >= (1, 11): CsrfViewMiddleware().process_request(request) return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) def enforce_csrf(self, request): """ Skip the referer check if the cross-domain request is allowed. """ if is_cross_domain_request_allowed(request): with skip_cross_domain_referer_check(request): return self._process_enforce_csrf(request) else: return self._process_enforce_csrf(request)
<commit_before>""" Django Rest Framework Authentication classes for cross-domain end-points. """ from rest_framework import authentication from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check class SessionAuthenticationCrossDomainCsrf(authentication.SessionAuthentication): """ Session authentication that skips the referer check over secure connections. Django Rest Framework's `SessionAuthentication` class calls Django's CSRF middleware implementation directly, which bypasses the middleware stack. This version of `SessionAuthentication` performs the same workaround as `CorsCSRFMiddleware` to skip the referer check for whitelisted domains over a secure connection. See `cors_csrf.middleware` for more information. Since this subclass overrides only the `enforce_csrf()` method, it can be mixed in with other `SessionAuthentication` subclasses. """ def enforce_csrf(self, request): """ Skip the referer check if the cross-domain request is allowed. """ if is_cross_domain_request_allowed(request): with skip_cross_domain_referer_check(request): return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) else: return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) <commit_msg>Handle different cookie processing for Django 1.11<commit_after>""" Django Rest Framework Authentication classes for cross-domain end-points. """ import django from django.middleware.csrf import CsrfViewMiddleware from rest_framework import authentication from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check class SessionAuthenticationCrossDomainCsrf(authentication.SessionAuthentication): """ Session authentication that skips the referer check over secure connections. Django Rest Framework's `SessionAuthentication` class calls Django's CSRF middleware implementation directly, which bypasses the middleware stack. This version of `SessionAuthentication` performs the same workaround as `CorsCSRFMiddleware` to skip the referer check for whitelisted domains over a secure connection. See `cors_csrf.middleware` for more information. Since this subclass overrides only the `enforce_csrf()` method, it can be mixed in with other `SessionAuthentication` subclasses. """ # TODO: Remove Django 1.11 upgrade shim # SHIM: Call new process_request in Django 1.11 to process CSRF token in cookie. def _process_enforce_csrf(self, request): if django.VERSION >= (1, 11): CsrfViewMiddleware().process_request(request) return super(SessionAuthenticationCrossDomainCsrf, self).enforce_csrf(request) def enforce_csrf(self, request): """ Skip the referer check if the cross-domain request is allowed. """ if is_cross_domain_request_allowed(request): with skip_cross_domain_referer_check(request): return self._process_enforce_csrf(request) else: return self._process_enforce_csrf(request)
d1db2f8e93e43be7fe89f38d6d2b5944fa5773cb
inotify_simple/__init__.py
inotify_simple/__init__.py
from __future__ import absolute_import from .inotify_simple import * try: from __version__ import __version__ except ImportError: __version__ = None
from __future__ import absolute_import from .inotify_simple import * try: from .__version__ import __version__ except ImportError: __version__ = None
Fix non relative import for __version__
Fix non relative import for __version__
Python
bsd-2-clause
chrisjbillington/inotify_simple
from __future__ import absolute_import from .inotify_simple import * try: from __version__ import __version__ except ImportError: __version__ = None Fix non relative import for __version__
from __future__ import absolute_import from .inotify_simple import * try: from .__version__ import __version__ except ImportError: __version__ = None
<commit_before>from __future__ import absolute_import from .inotify_simple import * try: from __version__ import __version__ except ImportError: __version__ = None <commit_msg>Fix non relative import for __version__<commit_after>
from __future__ import absolute_import from .inotify_simple import * try: from .__version__ import __version__ except ImportError: __version__ = None
from __future__ import absolute_import from .inotify_simple import * try: from __version__ import __version__ except ImportError: __version__ = None Fix non relative import for __version__from __future__ import absolute_import from .inotify_simple import * try: from .__version__ import __version__ except ImportError: __version__ = None
<commit_before>from __future__ import absolute_import from .inotify_simple import * try: from __version__ import __version__ except ImportError: __version__ = None <commit_msg>Fix non relative import for __version__<commit_after>from __future__ import absolute_import from .inotify_simple import * try: from .__version__ import __version__ except ImportError: __version__ = None
9f5ad1ddf7942fd61d22acebe8e9854239832b6f
python/lolopy/loloserver.py
python/lolopy/loloserver.py
"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat") return _gateway JavaGateway()
"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat", die_on_exit=True) return _gateway JavaGateway()
Make sure to kill JVM on exit
Make sure to kill JVM on exit
Python
apache-2.0
CitrineInformatics/lolo,CitrineInformatics/lolo
"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat") return _gateway JavaGateway() Make sure to kill JVM on exit
"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat", die_on_exit=True) return _gateway JavaGateway()
<commit_before>"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat") return _gateway JavaGateway() <commit_msg>Make sure to kill JVM on exit<commit_after>
"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat", die_on_exit=True) return _gateway JavaGateway()
"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat") return _gateway JavaGateway() Make sure to kill JVM on exit"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat", die_on_exit=True) return _gateway JavaGateway()
<commit_before>"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat") return _gateway JavaGateway() <commit_msg>Make sure to kill JVM on exit<commit_after>"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat", die_on_exit=True) return _gateway JavaGateway()
faa1d74ccbfea43697c08db59db467b7a99ccb62
optimize/py/main.py
optimize/py/main.py
from scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, bracket=None, bounds=None, args=(), method='brent', tol=None, options=None): return o.minimize_scalar(func, bracket, bounds, args, method, tol, options)
from scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, options): bracket = options['bracket'] bounds = options['bounds'] method = options['method'] tol = options['tol'] options = options['options'] return o.minimize_scalar(func, bracket=bracket, bounds=bounds, method=method, tol=tol, options=options)
Allow options to be passed into minimization
Allow options to be passed into minimization
Python
mit
acjones617/scipy-node,acjones617/scipy-node
from scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, bracket=None, bounds=None, args=(), method='brent', tol=None, options=None): return o.minimize_scalar(func, bracket, bounds, args, method, tol, options)Allow options to be passed into minimization
from scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, options): bracket = options['bracket'] bounds = options['bounds'] method = options['method'] tol = options['tol'] options = options['options'] return o.minimize_scalar(func, bracket=bracket, bounds=bounds, method=method, tol=tol, options=options)
<commit_before>from scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, bracket=None, bounds=None, args=(), method='brent', tol=None, options=None): return o.minimize_scalar(func, bracket, bounds, args, method, tol, options)<commit_msg>Allow options to be passed into minimization<commit_after>
from scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, options): bracket = options['bracket'] bounds = options['bounds'] method = options['method'] tol = options['tol'] options = options['options'] return o.minimize_scalar(func, bracket=bracket, bounds=bounds, method=method, tol=tol, options=options)
from scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, bracket=None, bounds=None, args=(), method='brent', tol=None, options=None): return o.minimize_scalar(func, bracket, bounds, args, method, tol, options)Allow options to be passed into minimizationfrom scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, options): bracket = options['bracket'] bounds = options['bounds'] method = options['method'] tol = options['tol'] options = options['options'] return o.minimize_scalar(func, bracket=bracket, bounds=bounds, method=method, tol=tol, options=options)
<commit_before>from scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, bracket=None, bounds=None, args=(), method='brent', tol=None, options=None): return o.minimize_scalar(func, bracket, bounds, args, method, tol, options)<commit_msg>Allow options to be passed into minimization<commit_after>from scipy import optimize as o import clean as c def minimize(func, guess): return o.minimize(func, guess) def minimize_scalar(func, options): bracket = options['bracket'] bounds = options['bounds'] method = options['method'] tol = options['tol'] options = options['options'] return o.minimize_scalar(func, bracket=bracket, bounds=bounds, method=method, tol=tol, options=options)
60838f03a516859bee97c8133bb9e11e8fc61c39
perf_insights/perf_insights/local_file_trace_handle.py
perf_insights/perf_insights/local_file_trace_handle.py
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import gzip import os import shutil import tempfile from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def __init__(self, run_info, filename): super(LocalFileTraceHandle, self).__init__(run_info) self.filename = filename def Open(self): temp_trace_file = tempfile.NamedTemporaryFile( dir=os.path.dirname(self.filename)) try: with gzip.GzipFile(self.filename) as unzipped: shutil.copyfileobj(unzipped, temp_trace_file) temp_trace_file.flush() return temp_trace_file except IOError: temp_trace_file.close() return open(self.filename, 'r')
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def __init__(self, run_info, filename): super(LocalFileTraceHandle, self).__init__(run_info) self.filename = filename def Open(self): return open(self.filename, 'r')
Revert gunzip in python from performance insights mapping
Revert gunzip in python from performance insights mapping Reverts ade2e1a90cc69169b8c613606b44ac7503b64503. This appears to be causing significant contention on at least z840 machines. Only ~12 d8 instances run at any given time despite -j48. As noted in https://github.com/catapult-project/catapult/issues/1193 the speedup by moving unzip to python was negligible. BUG=#1193 Review URL: https://codereview.chromium.org/1304143009
Python
bsd-3-clause
SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult-csm,0x90sled/catapult,catapult-project/catapult,sahiljain/catapult,0x90sled/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,benschmaus/catapult,SummerLW/Perf-Insight-Report,benschmaus/catapult,sahiljain/catapult,SummerLW/Perf-Insight-Report,benschmaus/catapult,sahiljain/catapult,sahiljain/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult,benschmaus/catapult,sahiljain/catapult,catapult-project/catapult-csm,0x90sled/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,sahiljain/catapult,catapult-project/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import gzip import os import shutil import tempfile from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def __init__(self, run_info, filename): super(LocalFileTraceHandle, self).__init__(run_info) self.filename = filename def Open(self): temp_trace_file = tempfile.NamedTemporaryFile( dir=os.path.dirname(self.filename)) try: with gzip.GzipFile(self.filename) as unzipped: shutil.copyfileobj(unzipped, temp_trace_file) temp_trace_file.flush() return temp_trace_file except IOError: temp_trace_file.close() return open(self.filename, 'r') Revert gunzip in python from performance insights mapping Reverts ade2e1a90cc69169b8c613606b44ac7503b64503. This appears to be causing significant contention on at least z840 machines. Only ~12 d8 instances run at any given time despite -j48. As noted in https://github.com/catapult-project/catapult/issues/1193 the speedup by moving unzip to python was negligible. BUG=#1193 Review URL: https://codereview.chromium.org/1304143009
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def __init__(self, run_info, filename): super(LocalFileTraceHandle, self).__init__(run_info) self.filename = filename def Open(self): return open(self.filename, 'r')
<commit_before># Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import gzip import os import shutil import tempfile from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def __init__(self, run_info, filename): super(LocalFileTraceHandle, self).__init__(run_info) self.filename = filename def Open(self): temp_trace_file = tempfile.NamedTemporaryFile( dir=os.path.dirname(self.filename)) try: with gzip.GzipFile(self.filename) as unzipped: shutil.copyfileobj(unzipped, temp_trace_file) temp_trace_file.flush() return temp_trace_file except IOError: temp_trace_file.close() return open(self.filename, 'r') <commit_msg>Revert gunzip in python from performance insights mapping Reverts ade2e1a90cc69169b8c613606b44ac7503b64503. This appears to be causing significant contention on at least z840 machines. Only ~12 d8 instances run at any given time despite -j48. As noted in https://github.com/catapult-project/catapult/issues/1193 the speedup by moving unzip to python was negligible. BUG=#1193 Review URL: https://codereview.chromium.org/1304143009<commit_after>
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def __init__(self, run_info, filename): super(LocalFileTraceHandle, self).__init__(run_info) self.filename = filename def Open(self): return open(self.filename, 'r')
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import gzip import os import shutil import tempfile from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def __init__(self, run_info, filename): super(LocalFileTraceHandle, self).__init__(run_info) self.filename = filename def Open(self): temp_trace_file = tempfile.NamedTemporaryFile( dir=os.path.dirname(self.filename)) try: with gzip.GzipFile(self.filename) as unzipped: shutil.copyfileobj(unzipped, temp_trace_file) temp_trace_file.flush() return temp_trace_file except IOError: temp_trace_file.close() return open(self.filename, 'r') Revert gunzip in python from performance insights mapping Reverts ade2e1a90cc69169b8c613606b44ac7503b64503. This appears to be causing significant contention on at least z840 machines. Only ~12 d8 instances run at any given time despite -j48. As noted in https://github.com/catapult-project/catapult/issues/1193 the speedup by moving unzip to python was negligible. BUG=#1193 Review URL: https://codereview.chromium.org/1304143009# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def __init__(self, run_info, filename): super(LocalFileTraceHandle, self).__init__(run_info) self.filename = filename def Open(self): return open(self.filename, 'r')
<commit_before># Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import gzip import os import shutil import tempfile from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def __init__(self, run_info, filename): super(LocalFileTraceHandle, self).__init__(run_info) self.filename = filename def Open(self): temp_trace_file = tempfile.NamedTemporaryFile( dir=os.path.dirname(self.filename)) try: with gzip.GzipFile(self.filename) as unzipped: shutil.copyfileobj(unzipped, temp_trace_file) temp_trace_file.flush() return temp_trace_file except IOError: temp_trace_file.close() return open(self.filename, 'r') <commit_msg>Revert gunzip in python from performance insights mapping Reverts ade2e1a90cc69169b8c613606b44ac7503b64503. This appears to be causing significant contention on at least z840 machines. Only ~12 d8 instances run at any given time despite -j48. As noted in https://github.com/catapult-project/catapult/issues/1193 the speedup by moving unzip to python was negligible. BUG=#1193 Review URL: https://codereview.chromium.org/1304143009<commit_after># Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def __init__(self, run_info, filename): super(LocalFileTraceHandle, self).__init__(run_info) self.filename = filename def Open(self): return open(self.filename, 'r')
1f5c277d5c99c7a54bcd5d5141377a3f85a2f5d7
core/parser.py
core/parser.py
class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(line) return entries def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass
class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(self.tidyLog(line)) return entries def tidyLog(self, entry): """ Tidies up a single log entry to separate usefull infos. """ # TODO : replace this with some regex magic again logLine = {} logLine["date"] = entry[0:10] logLine["time"] = entry[11:19] logLine["service"] = entry[entry.find("[") + 1: entry.find("]")] logLIne["ip"] = entry[entry.find("Ban") + 4: len(entry) - 1] return logLine def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass
Add : entry tidy to keep relevant info.
Add : entry tidy to keep relevant info.
Python
mit
nocternology/fail2dash,nocternology/fail2dash
class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(line) return entries def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass Add : entry tidy to keep relevant info.
class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(self.tidyLog(line)) return entries def tidyLog(self, entry): """ Tidies up a single log entry to separate usefull infos. """ # TODO : replace this with some regex magic again logLine = {} logLine["date"] = entry[0:10] logLine["time"] = entry[11:19] logLine["service"] = entry[entry.find("[") + 1: entry.find("]")] logLIne["ip"] = entry[entry.find("Ban") + 4: len(entry) - 1] return logLine def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass
<commit_before>class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(line) return entries def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass <commit_msg>Add : entry tidy to keep relevant info.<commit_after>
class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(self.tidyLog(line)) return entries def tidyLog(self, entry): """ Tidies up a single log entry to separate usefull infos. """ # TODO : replace this with some regex magic again logLine = {} logLine["date"] = entry[0:10] logLine["time"] = entry[11:19] logLine["service"] = entry[entry.find("[") + 1: entry.find("]")] logLIne["ip"] = entry[entry.find("Ban") + 4: len(entry) - 1] return logLine def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass
class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(line) return entries def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass Add : entry tidy to keep relevant info.class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(self.tidyLog(line)) return entries def tidyLog(self, entry): """ Tidies up a single log entry to separate usefull infos. """ # TODO : replace this with some regex magic again logLine = {} logLine["date"] = entry[0:10] logLine["time"] = entry[11:19] logLine["service"] = entry[entry.find("[") + 1: entry.find("]")] logLIne["ip"] = entry[entry.find("Ban") + 4: len(entry) - 1] return logLine def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass
<commit_before>class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(line) return entries def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass <commit_msg>Add : entry tidy to keep relevant info.<commit_after>class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(self.tidyLog(line)) return entries def tidyLog(self, entry): """ Tidies up a single log entry to separate usefull infos. """ # TODO : replace this with some regex magic again logLine = {} logLine["date"] = entry[0:10] logLine["time"] = entry[11:19] logLine["service"] = entry[entry.find("[") + 1: entry.find("]")] logLIne["ip"] = entry[entry.find("Ban") + 4: len(entry) - 1] return logLine def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass
8f011917dc991165e2ae10b492bd3713a30f4126
axes/__init__.py
axes/__init__.py
__version__ = '2.0.0' def get_version(): return __version__
__version__ = '2.0.0' default_app_config = "axes.apps.AppConfig" def get_version(): return __version__
Add `default_app_config` so you can just use `axes` in `INSTALLED_APPS`
Add `default_app_config` so you can just use `axes` in `INSTALLED_APPS`
Python
mit
jazzband/django-axes,svenhertle/django-axes,django-pci/django-axes
__version__ = '2.0.0' def get_version(): return __version__ Add `default_app_config` so you can just use `axes` in `INSTALLED_APPS`
__version__ = '2.0.0' default_app_config = "axes.apps.AppConfig" def get_version(): return __version__
<commit_before>__version__ = '2.0.0' def get_version(): return __version__ <commit_msg>Add `default_app_config` so you can just use `axes` in `INSTALLED_APPS`<commit_after>
__version__ = '2.0.0' default_app_config = "axes.apps.AppConfig" def get_version(): return __version__
__version__ = '2.0.0' def get_version(): return __version__ Add `default_app_config` so you can just use `axes` in `INSTALLED_APPS`__version__ = '2.0.0' default_app_config = "axes.apps.AppConfig" def get_version(): return __version__
<commit_before>__version__ = '2.0.0' def get_version(): return __version__ <commit_msg>Add `default_app_config` so you can just use `axes` in `INSTALLED_APPS`<commit_after>__version__ = '2.0.0' default_app_config = "axes.apps.AppConfig" def get_version(): return __version__
bb4701103101c698f6afdc05bce02a186d228d89
celery/views.py
celery/views.py
"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data)) def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data}))
"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data), mimetype="application/json") def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data}), mimetype="application/json")
Send back a mimetype for JSON response.
Send back a mimetype for JSON response.
Python
bsd-3-clause
frac/celery,ask/celery,frac/celery,mitsuhiko/celery,cbrepo/celery,cbrepo/celery,mitsuhiko/celery,ask/celery,WoLpH/celery,WoLpH/celery
"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data)) def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data})) Send back a mimetype for JSON response.
"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data), mimetype="application/json") def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data}), mimetype="application/json")
<commit_before>"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data)) def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data})) <commit_msg>Send back a mimetype for JSON response.<commit_after>
"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data), mimetype="application/json") def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data}), mimetype="application/json")
"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data)) def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data})) Send back a mimetype for JSON response."""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data), mimetype="application/json") def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data}), mimetype="application/json")
<commit_before>"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data)) def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data})) <commit_msg>Send back a mimetype for JSON response.<commit_after>"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id": task_id, "executed": is_done(task_id)}} return HttpResponse(JSON_dump(response_data), mimetype="application/json") def task_status(request, task_id): """Returns task status and result in JSON format.""" async_result = AsyncResult(task_id) status = async_result.status if status == "FAILURE": response_data = { "id": task_id, "status": status, "result": async_result.result.args[0], } else: response_data = { "id": task_id, "status": status, "result": async_result.result, } return HttpResponse(JSON_dump({"task": response_data}), mimetype="application/json")
2f9ba8bb4c6c25777ddce19be94fdb0675174810
konstrukteur/HtmlParser.py
konstrukteur/HtmlParser.py
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filename, "rt").read()) body = parsedContent.find("body") page["content"] = "".join([str(tag) for tag in body.contents]) page["title"] = parsedContent.title.string page["summary"] = body.p.get_text() for meta in parsedContent.find_all("meta"): if not hasattr(meta, "name") or not hasattr(meta, "content"): raise RuntimeError("Meta elements must have attributes name and content : %s" % filename) page[meta["name"].lower()] = meta["content"] return page
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filename, "rt").read()) body = parsedContent.find("body") page["content"] = "".join([str(tag) for tag in body.contents]) page["title"] = parsedContent.title.string firstP = body.p if firstP: page["summary"] = body.p.get_text() else: page["summary"] = "" for meta in parsedContent.find_all("meta"): if not hasattr(meta, "name") or not hasattr(meta, "content"): raise RuntimeError("Meta elements must have attributes name and content : %s" % filename) page[meta["name"].lower()] = meta["content"] return page
Fix if no paragraph is in page
Fix if no paragraph is in page
Python
mit
fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filename, "rt").read()) body = parsedContent.find("body") page["content"] = "".join([str(tag) for tag in body.contents]) page["title"] = parsedContent.title.string page["summary"] = body.p.get_text() for meta in parsedContent.find_all("meta"): if not hasattr(meta, "name") or not hasattr(meta, "content"): raise RuntimeError("Meta elements must have attributes name and content : %s" % filename) page[meta["name"].lower()] = meta["content"] return pageFix if no paragraph is in page
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filename, "rt").read()) body = parsedContent.find("body") page["content"] = "".join([str(tag) for tag in body.contents]) page["title"] = parsedContent.title.string firstP = body.p if firstP: page["summary"] = body.p.get_text() else: page["summary"] = "" for meta in parsedContent.find_all("meta"): if not hasattr(meta, "name") or not hasattr(meta, "content"): raise RuntimeError("Meta elements must have attributes name and content : %s" % filename) page[meta["name"].lower()] = meta["content"] return page
<commit_before># # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filename, "rt").read()) body = parsedContent.find("body") page["content"] = "".join([str(tag) for tag in body.contents]) page["title"] = parsedContent.title.string page["summary"] = body.p.get_text() for meta in parsedContent.find_all("meta"): if not hasattr(meta, "name") or not hasattr(meta, "content"): raise RuntimeError("Meta elements must have attributes name and content : %s" % filename) page[meta["name"].lower()] = meta["content"] return page<commit_msg>Fix if no paragraph is in page<commit_after>
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filename, "rt").read()) body = parsedContent.find("body") page["content"] = "".join([str(tag) for tag in body.contents]) page["title"] = parsedContent.title.string firstP = body.p if firstP: page["summary"] = body.p.get_text() else: page["summary"] = "" for meta in parsedContent.find_all("meta"): if not hasattr(meta, "name") or not hasattr(meta, "content"): raise RuntimeError("Meta elements must have attributes name and content : %s" % filename) page[meta["name"].lower()] = meta["content"] return page
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filename, "rt").read()) body = parsedContent.find("body") page["content"] = "".join([str(tag) for tag in body.contents]) page["title"] = parsedContent.title.string page["summary"] = body.p.get_text() for meta in parsedContent.find_all("meta"): if not hasattr(meta, "name") or not hasattr(meta, "content"): raise RuntimeError("Meta elements must have attributes name and content : %s" % filename) page[meta["name"].lower()] = meta["content"] return pageFix if no paragraph is in page# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filename, "rt").read()) body = parsedContent.find("body") page["content"] = "".join([str(tag) for tag in body.contents]) page["title"] = parsedContent.title.string firstP = body.p if firstP: page["summary"] = body.p.get_text() else: page["summary"] = "" for meta in parsedContent.find_all("meta"): if not hasattr(meta, "name") or not hasattr(meta, "content"): raise RuntimeError("Meta elements must have attributes name and content : %s" % filename) page[meta["name"].lower()] = meta["content"] return page
<commit_before># # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filename, "rt").read()) body = parsedContent.find("body") page["content"] = "".join([str(tag) for tag in body.contents]) page["title"] = parsedContent.title.string page["summary"] = body.p.get_text() for meta in parsedContent.find_all("meta"): if not hasattr(meta, "name") or not hasattr(meta, "content"): raise RuntimeError("Meta elements must have attributes name and content : %s" % filename) page[meta["name"].lower()] = meta["content"] return page<commit_msg>Fix if no paragraph is in page<commit_after># # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filename, "rt").read()) body = parsedContent.find("body") page["content"] = "".join([str(tag) for tag in body.contents]) page["title"] = parsedContent.title.string firstP = body.p if firstP: page["summary"] = body.p.get_text() else: page["summary"] = "" for meta in parsedContent.find_all("meta"): if not hasattr(meta, "name") or not hasattr(meta, "content"): raise RuntimeError("Meta elements must have attributes name and content : %s" % filename) page[meta["name"].lower()] = meta["content"] return page
db45127fa93b495337df3e39a1c4622fce297ada
skimage/io/tests/test_io.py
skimage/io/tests/test_io.py
import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugin_store['imread'] = [] io.imread(image_path) if __name__ == "__main__": run_module_suite()
import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugins = plugin_store['imread'] plugin_store['imread'] = [] try: io.imread(image_path) finally: plugin_store['imread'] = plugins if __name__ == "__main__": run_module_suite()
Fix test so it doesn't have side-effects
Fix test so it doesn't have side-effects
Python
bsd-3-clause
chintak/scikit-image,ajaybhat/scikit-image,robintw/scikit-image,bsipocz/scikit-image,michaelpacer/scikit-image,Britefury/scikit-image,juliusbierk/scikit-image,ofgulban/scikit-image,paalge/scikit-image,emon10005/scikit-image,paalge/scikit-image,blink1073/scikit-image,michaelaye/scikit-image,ClinicalGraphics/scikit-image,Hiyorimi/scikit-image,chintak/scikit-image,jwiggins/scikit-image,jwiggins/scikit-image,keflavich/scikit-image,bennlich/scikit-image,bennlich/scikit-image,rjeli/scikit-image,SamHames/scikit-image,Midafi/scikit-image,chintak/scikit-image,michaelpacer/scikit-image,paalge/scikit-image,emon10005/scikit-image,dpshelio/scikit-image,newville/scikit-image,bsipocz/scikit-image,SamHames/scikit-image,Midafi/scikit-image,GaZ3ll3/scikit-image,ofgulban/scikit-image,chriscrosscutler/scikit-image,dpshelio/scikit-image,warmspringwinds/scikit-image,chintak/scikit-image,vighneshbirodkar/scikit-image,youprofit/scikit-image,rjeli/scikit-image,ajaybhat/scikit-image,juliusbierk/scikit-image,oew1v07/scikit-image,pratapvardhan/scikit-image,rjeli/scikit-image,Britefury/scikit-image,vighneshbirodkar/scikit-image,warmspringwinds/scikit-image,SamHames/scikit-image,pratapvardhan/scikit-image,ClinicalGraphics/scikit-image,youprofit/scikit-image,Hiyorimi/scikit-image,WarrenWeckesser/scikits-image,keflavich/scikit-image,oew1v07/scikit-image,WarrenWeckesser/scikits-image,michaelaye/scikit-image,ofgulban/scikit-image,GaZ3ll3/scikit-image,chriscrosscutler/scikit-image,robintw/scikit-image,SamHames/scikit-image,newville/scikit-image,blink1073/scikit-image,vighneshbirodkar/scikit-image
import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugin_store['imread'] = [] io.imread(image_path) if __name__ == "__main__": run_module_suite() Fix test so it doesn't have side-effects
import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugins = plugin_store['imread'] plugin_store['imread'] = [] try: io.imread(image_path) finally: plugin_store['imread'] = plugins if __name__ == "__main__": run_module_suite()
<commit_before>import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugin_store['imread'] = [] io.imread(image_path) if __name__ == "__main__": run_module_suite() <commit_msg>Fix test so it doesn't have side-effects<commit_after>
import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugins = plugin_store['imread'] plugin_store['imread'] = [] try: io.imread(image_path) finally: plugin_store['imread'] = plugins if __name__ == "__main__": run_module_suite()
import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugin_store['imread'] = [] io.imread(image_path) if __name__ == "__main__": run_module_suite() Fix test so it doesn't have side-effectsimport os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugins = plugin_store['imread'] plugin_store['imread'] = [] try: io.imread(image_path) finally: plugin_store['imread'] = plugins if __name__ == "__main__": run_module_suite()
<commit_before>import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugin_store['imread'] = [] io.imread(image_path) if __name__ == "__main__": run_module_suite() <commit_msg>Fix test so it doesn't have side-effects<commit_after>import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugins = plugin_store['imread'] plugin_store['imread'] = [] try: io.imread(image_path) finally: plugin_store['imread'] = plugins if __name__ == "__main__": run_module_suite()
4844f948cbac10b729b739b8c516943290bcbb70
cle/backends/pe/regions.py
cle/backends/pe/regions.py
from ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.Misc_PhysicalAddress, pe_section.VirtualAddress + remap_offset, pe_section.Misc_VirtualSize, ) self.characteristics = pe_section.Characteristics self.size_of_raw_data = pe_section.SizeOfRawData # # Public properties # @property def is_readable(self): return self.characteristics & 0x40000000 != 0 @property def is_writable(self): return self.characteristics & 0x80000000 != 0 @property def is_executable(self): return self.characteristics & 0x20000000 != 0 @property def only_contains_uninitialized_data(self): return self.size_of_raw_data == 0
from ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.PointerToRawData, pe_section.VirtualAddress + remap_offset, pe_section.Misc_VirtualSize, ) self.characteristics = pe_section.Characteristics self.size_of_raw_data = pe_section.SizeOfRawData # # Public properties # @property def is_readable(self): return self.characteristics & 0x40000000 != 0 @property def is_writable(self): return self.characteristics & 0x80000000 != 0 @property def is_executable(self): return self.characteristics & 0x20000000 != 0 @property def only_contains_uninitialized_data(self): return self.size_of_raw_data == 0
Fix PE backend file offset of section
Fix PE backend file offset of section
Python
bsd-2-clause
angr/cle
from ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.Misc_PhysicalAddress, pe_section.VirtualAddress + remap_offset, pe_section.Misc_VirtualSize, ) self.characteristics = pe_section.Characteristics self.size_of_raw_data = pe_section.SizeOfRawData # # Public properties # @property def is_readable(self): return self.characteristics & 0x40000000 != 0 @property def is_writable(self): return self.characteristics & 0x80000000 != 0 @property def is_executable(self): return self.characteristics & 0x20000000 != 0 @property def only_contains_uninitialized_data(self): return self.size_of_raw_data == 0 Fix PE backend file offset of section
from ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.PointerToRawData, pe_section.VirtualAddress + remap_offset, pe_section.Misc_VirtualSize, ) self.characteristics = pe_section.Characteristics self.size_of_raw_data = pe_section.SizeOfRawData # # Public properties # @property def is_readable(self): return self.characteristics & 0x40000000 != 0 @property def is_writable(self): return self.characteristics & 0x80000000 != 0 @property def is_executable(self): return self.characteristics & 0x20000000 != 0 @property def only_contains_uninitialized_data(self): return self.size_of_raw_data == 0
<commit_before>from ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.Misc_PhysicalAddress, pe_section.VirtualAddress + remap_offset, pe_section.Misc_VirtualSize, ) self.characteristics = pe_section.Characteristics self.size_of_raw_data = pe_section.SizeOfRawData # # Public properties # @property def is_readable(self): return self.characteristics & 0x40000000 != 0 @property def is_writable(self): return self.characteristics & 0x80000000 != 0 @property def is_executable(self): return self.characteristics & 0x20000000 != 0 @property def only_contains_uninitialized_data(self): return self.size_of_raw_data == 0 <commit_msg>Fix PE backend file offset of section<commit_after>
from ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.PointerToRawData, pe_section.VirtualAddress + remap_offset, pe_section.Misc_VirtualSize, ) self.characteristics = pe_section.Characteristics self.size_of_raw_data = pe_section.SizeOfRawData # # Public properties # @property def is_readable(self): return self.characteristics & 0x40000000 != 0 @property def is_writable(self): return self.characteristics & 0x80000000 != 0 @property def is_executable(self): return self.characteristics & 0x20000000 != 0 @property def only_contains_uninitialized_data(self): return self.size_of_raw_data == 0
from ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.Misc_PhysicalAddress, pe_section.VirtualAddress + remap_offset, pe_section.Misc_VirtualSize, ) self.characteristics = pe_section.Characteristics self.size_of_raw_data = pe_section.SizeOfRawData # # Public properties # @property def is_readable(self): return self.characteristics & 0x40000000 != 0 @property def is_writable(self): return self.characteristics & 0x80000000 != 0 @property def is_executable(self): return self.characteristics & 0x20000000 != 0 @property def only_contains_uninitialized_data(self): return self.size_of_raw_data == 0 Fix PE backend file offset of sectionfrom ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.PointerToRawData, pe_section.VirtualAddress + remap_offset, pe_section.Misc_VirtualSize, ) self.characteristics = pe_section.Characteristics self.size_of_raw_data = pe_section.SizeOfRawData # # Public properties # @property def is_readable(self): return self.characteristics & 0x40000000 != 0 @property def is_writable(self): return self.characteristics & 0x80000000 != 0 @property def is_executable(self): return self.characteristics & 0x20000000 != 0 @property def only_contains_uninitialized_data(self): return self.size_of_raw_data == 0
<commit_before>from ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.Misc_PhysicalAddress, pe_section.VirtualAddress + remap_offset, pe_section.Misc_VirtualSize, ) self.characteristics = pe_section.Characteristics self.size_of_raw_data = pe_section.SizeOfRawData # # Public properties # @property def is_readable(self): return self.characteristics & 0x40000000 != 0 @property def is_writable(self): return self.characteristics & 0x80000000 != 0 @property def is_executable(self): return self.characteristics & 0x20000000 != 0 @property def only_contains_uninitialized_data(self): return self.size_of_raw_data == 0 <commit_msg>Fix PE backend file offset of section<commit_after>from ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.PointerToRawData, pe_section.VirtualAddress + remap_offset, pe_section.Misc_VirtualSize, ) self.characteristics = pe_section.Characteristics self.size_of_raw_data = pe_section.SizeOfRawData # # Public properties # @property def is_readable(self): return self.characteristics & 0x40000000 != 0 @property def is_writable(self): return self.characteristics & 0x80000000 != 0 @property def is_executable(self): return self.characteristics & 0x20000000 != 0 @property def only_contains_uninitialized_data(self): return self.size_of_raw_data == 0
7261c5f96d52dba7f8a12716994e753910ceda64
tests/context_managers.py
tests/context_managers.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() yield original_prefs.copy() yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() yield original_recent_refs[:] yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock yield mock yvs.webbrowser = original_webbrowser
#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() try: yield original_prefs.copy() finally: yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() try: yield original_recent_refs[:] finally: yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock try: yield mock finally: yvs.webbrowser = original_webbrowser
Add finally blocks to ensure tests always clean up
Add finally blocks to ensure tests always clean up
Python
mit
caleb531/youversion-suggest,caleb531/youversion-suggest
#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() yield original_prefs.copy() yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() yield original_recent_refs[:] yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock yield mock yvs.webbrowser = original_webbrowser Add finally blocks to ensure tests always clean up
#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() try: yield original_prefs.copy() finally: yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() try: yield original_recent_refs[:] finally: yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock try: yield mock finally: yvs.webbrowser = original_webbrowser
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() yield original_prefs.copy() yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() yield original_recent_refs[:] yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock yield mock yvs.webbrowser = original_webbrowser <commit_msg>Add finally blocks to ensure tests always clean up<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() try: yield original_prefs.copy() finally: yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() try: yield original_recent_refs[:] finally: yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock try: yield mock finally: yvs.webbrowser = original_webbrowser
#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() yield original_prefs.copy() yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() yield original_recent_refs[:] yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock yield mock yvs.webbrowser = original_webbrowser Add finally blocks to ensure tests always clean up#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() try: yield original_prefs.copy() finally: yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() try: yield original_recent_refs[:] finally: yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock try: yield mock finally: yvs.webbrowser = original_webbrowser
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() yield original_prefs.copy() yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() yield original_recent_refs[:] yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock yield mock yvs.webbrowser = original_webbrowser <commit_msg>Add finally blocks to ensure tests always clean up<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() try: yield original_prefs.copy() finally: yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() try: yield original_recent_refs[:] finally: yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock try: yield mock finally: yvs.webbrowser = original_webbrowser
a7bb3eebdfa71ad87301fb84d54fd6de0249ec29
bin/initialize_data.py
bin/initialize_data.py
from twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis('127.0.0.1:6379') redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(redis, 'adjectives', adjectives) sentences = ('I really appreciate how {} you are.', 'I am super inspired by how {} you are.', 'I am so impressed by how {} you are.') add_data(redis, 'sentences', sentences)
from twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis() redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(redis, 'adjectives', adjectives) sentences = ('I really appreciate how {} you are.', 'I am super inspired by how {} you are.', 'I am so impressed by how {} you are.') add_data(redis, 'sentences', sentences)
Use redis configuration when initializing data
Use redis configuration when initializing data
Python
mit
jessamynsmith/twitterbot,jessamynsmith/heartbot,jessamynsmith/twitterbot,jessamynsmith/heartbot
from twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis('127.0.0.1:6379') redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(redis, 'adjectives', adjectives) sentences = ('I really appreciate how {} you are.', 'I am super inspired by how {} you are.', 'I am so impressed by how {} you are.') add_data(redis, 'sentences', sentences) Use redis configuration when initializing data
from twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis() redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(redis, 'adjectives', adjectives) sentences = ('I really appreciate how {} you are.', 'I am super inspired by how {} you are.', 'I am so impressed by how {} you are.') add_data(redis, 'sentences', sentences)
<commit_before>from twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis('127.0.0.1:6379') redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(redis, 'adjectives', adjectives) sentences = ('I really appreciate how {} you are.', 'I am super inspired by how {} you are.', 'I am so impressed by how {} you are.') add_data(redis, 'sentences', sentences) <commit_msg>Use redis configuration when initializing data<commit_after>
from twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis() redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(redis, 'adjectives', adjectives) sentences = ('I really appreciate how {} you are.', 'I am super inspired by how {} you are.', 'I am so impressed by how {} you are.') add_data(redis, 'sentences', sentences)
from twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis('127.0.0.1:6379') redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(redis, 'adjectives', adjectives) sentences = ('I really appreciate how {} you are.', 'I am super inspired by how {} you are.', 'I am so impressed by how {} you are.') add_data(redis, 'sentences', sentences) Use redis configuration when initializing datafrom twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis() redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(redis, 'adjectives', adjectives) sentences = ('I really appreciate how {} you are.', 'I am super inspired by how {} you are.', 'I am so impressed by how {} you are.') add_data(redis, 'sentences', sentences)
<commit_before>from twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis('127.0.0.1:6379') redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(redis, 'adjectives', adjectives) sentences = ('I really appreciate how {} you are.', 'I am super inspired by how {} you are.', 'I am so impressed by how {} you are.') add_data(redis, 'sentences', sentences) <commit_msg>Use redis configuration when initializing data<commit_after>from twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis() redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(redis, 'adjectives', adjectives) sentences = ('I really appreciate how {} you are.', 'I am super inspired by how {} you are.', 'I am so impressed by how {} you are.') add_data(redis, 'sentences', sentences)
9f484e6eb4fcf37f5515d62eb80be6a0f8d5a097
swteams/views.py
swteams/views.py
import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context = { 'group': team, } return render_to_response(template_name, template_context, RequestContext(request)) def topics_with_team_slug(*args, **kwargs): # Insert the team into the template context as 'group' so that # breadcrumbs, etc. render properly. slug = kwargs['slug'] extra_context = kwargs.setdefault('extra_context', {}) extra_context['group'] = Team.objects.get(slug=slug) return iris.views.topics(*args, **kwargs)
from django.shortcuts import get_object_or_404, render_to_response from django.template.context import RequestContext import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context = { 'group': team, } return render_to_response(template_name, template_context, RequestContext(request)) def topics_with_team_slug(*args, **kwargs): # Insert the team into the template context as 'group' so that # breadcrumbs, etc. render properly. slug = kwargs['slug'] extra_context = kwargs.setdefault('extra_context', {}) extra_context['group'] = Team.objects.get(slug=slug) return iris.views.topics(*args, **kwargs)
Fix team activity history view (was missing imports)
Fix team activity history view (was missing imports)
Python
apache-2.0
snswa/swsites,snswa/swsites,snswa/swsites
import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context = { 'group': team, } return render_to_response(template_name, template_context, RequestContext(request)) def topics_with_team_slug(*args, **kwargs): # Insert the team into the template context as 'group' so that # breadcrumbs, etc. render properly. slug = kwargs['slug'] extra_context = kwargs.setdefault('extra_context', {}) extra_context['group'] = Team.objects.get(slug=slug) return iris.views.topics(*args, **kwargs) Fix team activity history view (was missing imports)
from django.shortcuts import get_object_or_404, render_to_response from django.template.context import RequestContext import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context = { 'group': team, } return render_to_response(template_name, template_context, RequestContext(request)) def topics_with_team_slug(*args, **kwargs): # Insert the team into the template context as 'group' so that # breadcrumbs, etc. render properly. slug = kwargs['slug'] extra_context = kwargs.setdefault('extra_context', {}) extra_context['group'] = Team.objects.get(slug=slug) return iris.views.topics(*args, **kwargs)
<commit_before>import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context = { 'group': team, } return render_to_response(template_name, template_context, RequestContext(request)) def topics_with_team_slug(*args, **kwargs): # Insert the team into the template context as 'group' so that # breadcrumbs, etc. render properly. slug = kwargs['slug'] extra_context = kwargs.setdefault('extra_context', {}) extra_context['group'] = Team.objects.get(slug=slug) return iris.views.topics(*args, **kwargs) <commit_msg>Fix team activity history view (was missing imports)<commit_after>
from django.shortcuts import get_object_or_404, render_to_response from django.template.context import RequestContext import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context = { 'group': team, } return render_to_response(template_name, template_context, RequestContext(request)) def topics_with_team_slug(*args, **kwargs): # Insert the team into the template context as 'group' so that # breadcrumbs, etc. render properly. slug = kwargs['slug'] extra_context = kwargs.setdefault('extra_context', {}) extra_context['group'] = Team.objects.get(slug=slug) return iris.views.topics(*args, **kwargs)
import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context = { 'group': team, } return render_to_response(template_name, template_context, RequestContext(request)) def topics_with_team_slug(*args, **kwargs): # Insert the team into the template context as 'group' so that # breadcrumbs, etc. render properly. slug = kwargs['slug'] extra_context = kwargs.setdefault('extra_context', {}) extra_context['group'] = Team.objects.get(slug=slug) return iris.views.topics(*args, **kwargs) Fix team activity history view (was missing imports)from django.shortcuts import get_object_or_404, render_to_response from django.template.context import RequestContext import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context = { 'group': team, } return render_to_response(template_name, template_context, RequestContext(request)) def topics_with_team_slug(*args, **kwargs): # Insert the team into the template context as 'group' so that # breadcrumbs, etc. render properly. slug = kwargs['slug'] extra_context = kwargs.setdefault('extra_context', {}) extra_context['group'] = Team.objects.get(slug=slug) return iris.views.topics(*args, **kwargs)
<commit_before>import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context = { 'group': team, } return render_to_response(template_name, template_context, RequestContext(request)) def topics_with_team_slug(*args, **kwargs): # Insert the team into the template context as 'group' so that # breadcrumbs, etc. render properly. slug = kwargs['slug'] extra_context = kwargs.setdefault('extra_context', {}) extra_context['group'] = Team.objects.get(slug=slug) return iris.views.topics(*args, **kwargs) <commit_msg>Fix team activity history view (was missing imports)<commit_after>from django.shortcuts import get_object_or_404, render_to_response from django.template.context import RequestContext import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context = { 'group': team, } return render_to_response(template_name, template_context, RequestContext(request)) def topics_with_team_slug(*args, **kwargs): # Insert the team into the template context as 'group' so that # breadcrumbs, etc. render properly. slug = kwargs['slug'] extra_context = kwargs.setdefault('extra_context', {}) extra_context['group'] = Team.objects.get(slug=slug) return iris.views.topics(*args, **kwargs)
becc6b8913e85e55d3dcb3a9dcd3287718833990
tests/prov_test_common.py
tests/prov_test_common.py
import platform import re import subprocess from time import sleep def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not in stdout or b'Primary ecu hardware ID: ' + machine.encode() not in stdout or b'Fetched metadata: yes' not in stdout): print('Provisioning failed: ' + stderr.decode() + stdout.decode()) return 1 p = re.compile(r'Device ID: ([a-z0-9-]*)\n') m = p.search(stdout.decode()) if not m or m.lastindex <= 0: print('Device ID could not be read: ' + stderr.decode() + stdout.decode()) return 1 print('Device successfully provisioned with ID: ' + m.group(1)) return 0 def run_subprocess(command, **kwargs): print('> Running {}'.format(' '.join(command))) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) try: stdout, stderr = proc.communicate(timeout=60) except TimeoutExpired: proc.kill() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode
import platform import re import subprocess def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not in stdout or b'Primary ecu hardware ID: ' + machine.encode() not in stdout or b'Fetched metadata: yes' not in stdout): print('Provisioning failed: ' + stderr.decode() + stdout.decode()) return 1 p = re.compile(r'Device ID: ([a-z0-9-]*)\n') m = p.search(stdout.decode()) if not m or m.lastindex <= 0: print('Device ID could not be read: ' + stderr.decode() + stdout.decode()) return 1 print('Device successfully provisioned with ID: ' + m.group(1)) return 0 def run_subprocess(command, **kwargs): print('> Running {}'.format(' '.join(command))) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) try: stdout, stderr = proc.communicate(timeout=60) except subprocess.TimeoutExpired: proc.kill() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode
Fix a python undefined name in test scripts
Fix a python undefined name in test scripts Signed-off-by: Laurent Bonnans <0909bc0a3d1b0c91d8e00372b9633e8e9ea958de@here.com>
Python
mpl-2.0
advancedtelematic/sota_client_cpp,advancedtelematic/aktualizr,advancedtelematic/aktualizr,advancedtelematic/sota_client_cpp,advancedtelematic/aktualizr,advancedtelematic/aktualizr
import platform import re import subprocess from time import sleep def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not in stdout or b'Primary ecu hardware ID: ' + machine.encode() not in stdout or b'Fetched metadata: yes' not in stdout): print('Provisioning failed: ' + stderr.decode() + stdout.decode()) return 1 p = re.compile(r'Device ID: ([a-z0-9-]*)\n') m = p.search(stdout.decode()) if not m or m.lastindex <= 0: print('Device ID could not be read: ' + stderr.decode() + stdout.decode()) return 1 print('Device successfully provisioned with ID: ' + m.group(1)) return 0 def run_subprocess(command, **kwargs): print('> Running {}'.format(' '.join(command))) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) try: stdout, stderr = proc.communicate(timeout=60) except TimeoutExpired: proc.kill() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode Fix a python undefined name in test scripts Signed-off-by: Laurent Bonnans <0909bc0a3d1b0c91d8e00372b9633e8e9ea958de@here.com>
import platform import re import subprocess def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not in stdout or b'Primary ecu hardware ID: ' + machine.encode() not in stdout or b'Fetched metadata: yes' not in stdout): print('Provisioning failed: ' + stderr.decode() + stdout.decode()) return 1 p = re.compile(r'Device ID: ([a-z0-9-]*)\n') m = p.search(stdout.decode()) if not m or m.lastindex <= 0: print('Device ID could not be read: ' + stderr.decode() + stdout.decode()) return 1 print('Device successfully provisioned with ID: ' + m.group(1)) return 0 def run_subprocess(command, **kwargs): print('> Running {}'.format(' '.join(command))) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) try: stdout, stderr = proc.communicate(timeout=60) except subprocess.TimeoutExpired: proc.kill() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode
<commit_before>import platform import re import subprocess from time import sleep def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not in stdout or b'Primary ecu hardware ID: ' + machine.encode() not in stdout or b'Fetched metadata: yes' not in stdout): print('Provisioning failed: ' + stderr.decode() + stdout.decode()) return 1 p = re.compile(r'Device ID: ([a-z0-9-]*)\n') m = p.search(stdout.decode()) if not m or m.lastindex <= 0: print('Device ID could not be read: ' + stderr.decode() + stdout.decode()) return 1 print('Device successfully provisioned with ID: ' + m.group(1)) return 0 def run_subprocess(command, **kwargs): print('> Running {}'.format(' '.join(command))) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) try: stdout, stderr = proc.communicate(timeout=60) except TimeoutExpired: proc.kill() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode <commit_msg>Fix a python undefined name in test scripts Signed-off-by: Laurent Bonnans <0909bc0a3d1b0c91d8e00372b9633e8e9ea958de@here.com><commit_after>
import platform import re import subprocess def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not in stdout or b'Primary ecu hardware ID: ' + machine.encode() not in stdout or b'Fetched metadata: yes' not in stdout): print('Provisioning failed: ' + stderr.decode() + stdout.decode()) return 1 p = re.compile(r'Device ID: ([a-z0-9-]*)\n') m = p.search(stdout.decode()) if not m or m.lastindex <= 0: print('Device ID could not be read: ' + stderr.decode() + stdout.decode()) return 1 print('Device successfully provisioned with ID: ' + m.group(1)) return 0 def run_subprocess(command, **kwargs): print('> Running {}'.format(' '.join(command))) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) try: stdout, stderr = proc.communicate(timeout=60) except subprocess.TimeoutExpired: proc.kill() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode
import platform import re import subprocess from time import sleep def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not in stdout or b'Primary ecu hardware ID: ' + machine.encode() not in stdout or b'Fetched metadata: yes' not in stdout): print('Provisioning failed: ' + stderr.decode() + stdout.decode()) return 1 p = re.compile(r'Device ID: ([a-z0-9-]*)\n') m = p.search(stdout.decode()) if not m or m.lastindex <= 0: print('Device ID could not be read: ' + stderr.decode() + stdout.decode()) return 1 print('Device successfully provisioned with ID: ' + m.group(1)) return 0 def run_subprocess(command, **kwargs): print('> Running {}'.format(' '.join(command))) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) try: stdout, stderr = proc.communicate(timeout=60) except TimeoutExpired: proc.kill() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode Fix a python undefined name in test scripts Signed-off-by: Laurent Bonnans <0909bc0a3d1b0c91d8e00372b9633e8e9ea958de@here.com>import platform import re import subprocess def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not in stdout or b'Primary ecu hardware ID: ' + machine.encode() not in stdout or b'Fetched metadata: yes' not in stdout): print('Provisioning failed: ' + stderr.decode() + stdout.decode()) return 1 p = re.compile(r'Device ID: ([a-z0-9-]*)\n') m = p.search(stdout.decode()) if not m or m.lastindex <= 0: print('Device ID could not be read: ' + stderr.decode() + stdout.decode()) return 1 print('Device successfully provisioned with ID: ' + m.group(1)) return 0 def run_subprocess(command, **kwargs): print('> Running {}'.format(' '.join(command))) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) try: stdout, stderr = proc.communicate(timeout=60) except subprocess.TimeoutExpired: proc.kill() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode
<commit_before>import platform import re import subprocess from time import sleep def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not in stdout or b'Primary ecu hardware ID: ' + machine.encode() not in stdout or b'Fetched metadata: yes' not in stdout): print('Provisioning failed: ' + stderr.decode() + stdout.decode()) return 1 p = re.compile(r'Device ID: ([a-z0-9-]*)\n') m = p.search(stdout.decode()) if not m or m.lastindex <= 0: print('Device ID could not be read: ' + stderr.decode() + stdout.decode()) return 1 print('Device successfully provisioned with ID: ' + m.group(1)) return 0 def run_subprocess(command, **kwargs): print('> Running {}'.format(' '.join(command))) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) try: stdout, stderr = proc.communicate(timeout=60) except TimeoutExpired: proc.kill() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode <commit_msg>Fix a python undefined name in test scripts Signed-off-by: Laurent Bonnans <0909bc0a3d1b0c91d8e00372b9633e8e9ea958de@here.com><commit_after>import platform import re import subprocess def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not in stdout or b'Primary ecu hardware ID: ' + machine.encode() not in stdout or b'Fetched metadata: yes' not in stdout): print('Provisioning failed: ' + stderr.decode() + stdout.decode()) return 1 p = re.compile(r'Device ID: ([a-z0-9-]*)\n') m = p.search(stdout.decode()) if not m or m.lastindex <= 0: print('Device ID could not be read: ' + stderr.decode() + stdout.decode()) return 1 print('Device successfully provisioned with ID: ' + m.group(1)) return 0 def run_subprocess(command, **kwargs): print('> Running {}'.format(' '.join(command))) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) try: stdout, stderr = proc.communicate(timeout=60) except subprocess.TimeoutExpired: proc.kill() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode
2666359d1e2e441e36e417430cbec1a99414a940
salt_observer/private_settings.example.py
salt_observer/private_settings.example.py
import os # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'l=fg3h+kynh^y77ac7k%4ubsk4wz=z&1ud8uy*m%p(iw8*+xp-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'db.sqlite3'), } }
import os # SECURITY WARNING: # keep the secret key used in production secret! # by the way, you should change it if you are reading this ;) SECRET_KEY = 'l=fg3h+kynh^y77ac7k%4ubsk4wz=z&1ud8uy*m%p(iw8*+xp-' # SECURITY WARNING: # don't run with debug turned on in production! DEBUG = False # change this! ALLOWED_HOSTS = ['localhost'] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'db.sqlite3'), } }
Make the private settings file a bit user friendly
Make the private settings file a bit user friendly
Python
mit
hs-hannover/salt-observer,hs-hannover/salt-observer,hs-hannover/salt-observer
import os # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'l=fg3h+kynh^y77ac7k%4ubsk4wz=z&1ud8uy*m%p(iw8*+xp-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'db.sqlite3'), } } Make the private settings file a bit user friendly
import os # SECURITY WARNING: # keep the secret key used in production secret! # by the way, you should change it if you are reading this ;) SECRET_KEY = 'l=fg3h+kynh^y77ac7k%4ubsk4wz=z&1ud8uy*m%p(iw8*+xp-' # SECURITY WARNING: # don't run with debug turned on in production! DEBUG = False # change this! ALLOWED_HOSTS = ['localhost'] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'db.sqlite3'), } }
<commit_before>import os # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'l=fg3h+kynh^y77ac7k%4ubsk4wz=z&1ud8uy*m%p(iw8*+xp-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'db.sqlite3'), } } <commit_msg>Make the private settings file a bit user friendly<commit_after>
import os # SECURITY WARNING: # keep the secret key used in production secret! # by the way, you should change it if you are reading this ;) SECRET_KEY = 'l=fg3h+kynh^y77ac7k%4ubsk4wz=z&1ud8uy*m%p(iw8*+xp-' # SECURITY WARNING: # don't run with debug turned on in production! DEBUG = False # change this! ALLOWED_HOSTS = ['localhost'] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'db.sqlite3'), } }
import os # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'l=fg3h+kynh^y77ac7k%4ubsk4wz=z&1ud8uy*m%p(iw8*+xp-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'db.sqlite3'), } } Make the private settings file a bit user friendlyimport os # SECURITY WARNING: # keep the secret key used in production secret! # by the way, you should change it if you are reading this ;) SECRET_KEY = 'l=fg3h+kynh^y77ac7k%4ubsk4wz=z&1ud8uy*m%p(iw8*+xp-' # SECURITY WARNING: # don't run with debug turned on in production! DEBUG = False # change this! ALLOWED_HOSTS = ['localhost'] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'db.sqlite3'), } }
<commit_before>import os # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'l=fg3h+kynh^y77ac7k%4ubsk4wz=z&1ud8uy*m%p(iw8*+xp-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'db.sqlite3'), } } <commit_msg>Make the private settings file a bit user friendly<commit_after>import os # SECURITY WARNING: # keep the secret key used in production secret! # by the way, you should change it if you are reading this ;) SECRET_KEY = 'l=fg3h+kynh^y77ac7k%4ubsk4wz=z&1ud8uy*m%p(iw8*+xp-' # SECURITY WARNING: # don't run with debug turned on in production! DEBUG = False # change this! ALLOWED_HOSTS = ['localhost'] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'db.sqlite3'), } }
1af286a6ce7f4194314e0a7ed97c5d83428d8869
startup.py
startup.py
import tables import tables as tb try: import fipy import fipy as fp except: pass import numpy import numpy as np import scipy import scipy as spy import matplotlib.pylot as plt def gitCommand(cmd, verbose=False): from subprocess import Popen, PIPE p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) p.wait() out = p.stdout.read() if verbose: print out print p.stderr.read() return out def gitCurrentCommit(): return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') class _Prompt(object): def __str__(self): import datetime sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') if len(sha) > 0: sha = ' ' + sha return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']' class _PromptIn(_Prompt): def __str__(self): return super(_PromptIn, self).__str__() + ' >>> ' class _PromptOut(_Prompt): def __str__(self): return super(_PromptOut, self).__str__() + ' <<< ' _promptIn = _PromptIn() _promptOut = _PromptOut()
import tables import tables as tb try: import fipy import fipy as fp except: pass import numpy import numpy as np import scipy import scipy as spy import matplotlib.pyplot as plt def gitCommand(cmd, verbose=False): from subprocess import Popen, PIPE p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) p.wait() out = p.stdout.read() if verbose: print out print p.stderr.read() return out def gitCurrentCommit(): return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') class _Prompt(object): def __str__(self): import datetime sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') if len(sha) > 0: sha = ' ' + sha return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']' class _PromptIn(_Prompt): def __str__(self): return super(_PromptIn, self).__str__() + ' >>> ' class _PromptOut(_Prompt): def __str__(self): return super(_PromptOut, self).__str__() + ' <<< ' _promptIn = _PromptIn() _promptOut = _PromptOut()
Fix typo in matplotlib setup.
Fix typo in matplotlib setup.
Python
mit
wd15/env,wd15/env,wd15/env
import tables import tables as tb try: import fipy import fipy as fp except: pass import numpy import numpy as np import scipy import scipy as spy import matplotlib.pylot as plt def gitCommand(cmd, verbose=False): from subprocess import Popen, PIPE p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) p.wait() out = p.stdout.read() if verbose: print out print p.stderr.read() return out def gitCurrentCommit(): return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') class _Prompt(object): def __str__(self): import datetime sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') if len(sha) > 0: sha = ' ' + sha return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']' class _PromptIn(_Prompt): def __str__(self): return super(_PromptIn, self).__str__() + ' >>> ' class _PromptOut(_Prompt): def __str__(self): return super(_PromptOut, self).__str__() + ' <<< ' _promptIn = _PromptIn() _promptOut = _PromptOut() Fix typo in matplotlib setup.
import tables import tables as tb try: import fipy import fipy as fp except: pass import numpy import numpy as np import scipy import scipy as spy import matplotlib.pyplot as plt def gitCommand(cmd, verbose=False): from subprocess import Popen, PIPE p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) p.wait() out = p.stdout.read() if verbose: print out print p.stderr.read() return out def gitCurrentCommit(): return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') class _Prompt(object): def __str__(self): import datetime sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') if len(sha) > 0: sha = ' ' + sha return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']' class _PromptIn(_Prompt): def __str__(self): return super(_PromptIn, self).__str__() + ' >>> ' class _PromptOut(_Prompt): def __str__(self): return super(_PromptOut, self).__str__() + ' <<< ' _promptIn = _PromptIn() _promptOut = _PromptOut()
<commit_before>import tables import tables as tb try: import fipy import fipy as fp except: pass import numpy import numpy as np import scipy import scipy as spy import matplotlib.pylot as plt def gitCommand(cmd, verbose=False): from subprocess import Popen, PIPE p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) p.wait() out = p.stdout.read() if verbose: print out print p.stderr.read() return out def gitCurrentCommit(): return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') class _Prompt(object): def __str__(self): import datetime sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') if len(sha) > 0: sha = ' ' + sha return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']' class _PromptIn(_Prompt): def __str__(self): return super(_PromptIn, self).__str__() + ' >>> ' class _PromptOut(_Prompt): def __str__(self): return super(_PromptOut, self).__str__() + ' <<< ' _promptIn = _PromptIn() _promptOut = _PromptOut() <commit_msg>Fix typo in matplotlib setup.<commit_after>
import tables import tables as tb try: import fipy import fipy as fp except: pass import numpy import numpy as np import scipy import scipy as spy import matplotlib.pyplot as plt def gitCommand(cmd, verbose=False): from subprocess import Popen, PIPE p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) p.wait() out = p.stdout.read() if verbose: print out print p.stderr.read() return out def gitCurrentCommit(): return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') class _Prompt(object): def __str__(self): import datetime sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') if len(sha) > 0: sha = ' ' + sha return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']' class _PromptIn(_Prompt): def __str__(self): return super(_PromptIn, self).__str__() + ' >>> ' class _PromptOut(_Prompt): def __str__(self): return super(_PromptOut, self).__str__() + ' <<< ' _promptIn = _PromptIn() _promptOut = _PromptOut()
import tables import tables as tb try: import fipy import fipy as fp except: pass import numpy import numpy as np import scipy import scipy as spy import matplotlib.pylot as plt def gitCommand(cmd, verbose=False): from subprocess import Popen, PIPE p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) p.wait() out = p.stdout.read() if verbose: print out print p.stderr.read() return out def gitCurrentCommit(): return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') class _Prompt(object): def __str__(self): import datetime sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') if len(sha) > 0: sha = ' ' + sha return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']' class _PromptIn(_Prompt): def __str__(self): return super(_PromptIn, self).__str__() + ' >>> ' class _PromptOut(_Prompt): def __str__(self): return super(_PromptOut, self).__str__() + ' <<< ' _promptIn = _PromptIn() _promptOut = _PromptOut() Fix typo in matplotlib setup.import tables import tables as tb try: import fipy import fipy as fp except: pass import numpy import numpy as np import scipy import scipy as spy import matplotlib.pyplot as plt def gitCommand(cmd, verbose=False): from subprocess import Popen, PIPE p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) p.wait() out = p.stdout.read() if verbose: print out print p.stderr.read() return out def gitCurrentCommit(): return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') class _Prompt(object): def __str__(self): import datetime sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') if len(sha) > 0: sha = ' ' + sha return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']' class _PromptIn(_Prompt): def __str__(self): return super(_PromptIn, self).__str__() + ' >>> ' class _PromptOut(_Prompt): def __str__(self): return super(_PromptOut, self).__str__() + ' <<< ' _promptIn = _PromptIn() _promptOut = _PromptOut()
<commit_before>import tables import tables as tb try: import fipy import fipy as fp except: pass import numpy import numpy as np import scipy import scipy as spy import matplotlib.pylot as plt def gitCommand(cmd, verbose=False): from subprocess import Popen, PIPE p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) p.wait() out = p.stdout.read() if verbose: print out print p.stderr.read() return out def gitCurrentCommit(): return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') class _Prompt(object): def __str__(self): import datetime sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') if len(sha) > 0: sha = ' ' + sha return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']' class _PromptIn(_Prompt): def __str__(self): return super(_PromptIn, self).__str__() + ' >>> ' class _PromptOut(_Prompt): def __str__(self): return super(_PromptOut, self).__str__() + ' <<< ' _promptIn = _PromptIn() _promptOut = _PromptOut() <commit_msg>Fix typo in matplotlib setup.<commit_after>import tables import tables as tb try: import fipy import fipy as fp except: pass import numpy import numpy as np import scipy import scipy as spy import matplotlib.pyplot as plt def gitCommand(cmd, verbose=False): from subprocess import Popen, PIPE p = Popen(['git'] + cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) p.wait() out = p.stdout.read() if verbose: print out print p.stderr.read() return out def gitCurrentCommit(): return gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') class _Prompt(object): def __str__(self): import datetime sha = gitCommand(['log', '--oneline', '-1', '--abbrev=12', '--format="%h"']).strip().strip('"') if len(sha) > 0: sha = ' ' + sha return '[' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + sha + ']' class _PromptIn(_Prompt): def __str__(self): return super(_PromptIn, self).__str__() + ' >>> ' class _PromptOut(_Prompt): def __str__(self): return super(_PromptOut, self).__str__() + ' <<< ' _promptIn = _PromptIn() _promptOut = _PromptOut()
01a71f10f94d9e7b7c90d19540df8015455ae2ad
commands/say.py
commands/say.py
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) if triggerInMsg == 'say': bot.say(msgParts[1], messageToSay) elif triggerInMsg == 'do': bot.doAction(msgParts[1], messageToSay)
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do', 'notice'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) messageType = 'say' if triggerInMsg == 'do': messageType = 'action' elif triggerInMsg == 'notice': messageType = 'notice' bot.sendMessage(msgParts[1], messageToSay, messageType)
Move to sendMessage command for message sending. Also add 'notice' trigger, because why not
Move to sendMessage command for message sending. Also add 'notice' trigger, because why not
Python
mit
Didero/DideRobot
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) if triggerInMsg == 'say': bot.say(msgParts[1], messageToSay) elif triggerInMsg == 'do': bot.doAction(msgParts[1], messageToSay) Move to sendMessage command for message sending. Also add 'notice' trigger, because why not
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do', 'notice'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) messageType = 'say' if triggerInMsg == 'do': messageType = 'action' elif triggerInMsg == 'notice': messageType = 'notice' bot.sendMessage(msgParts[1], messageToSay, messageType)
<commit_before>from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) if triggerInMsg == 'say': bot.say(msgParts[1], messageToSay) elif triggerInMsg == 'do': bot.doAction(msgParts[1], messageToSay) <commit_msg>Move to sendMessage command for message sending. Also add 'notice' trigger, because why not<commit_after>
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do', 'notice'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) messageType = 'say' if triggerInMsg == 'do': messageType = 'action' elif triggerInMsg == 'notice': messageType = 'notice' bot.sendMessage(msgParts[1], messageToSay, messageType)
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) if triggerInMsg == 'say': bot.say(msgParts[1], messageToSay) elif triggerInMsg == 'do': bot.doAction(msgParts[1], messageToSay) Move to sendMessage command for message sending. Also add 'notice' trigger, because why notfrom CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do', 'notice'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) messageType = 'say' if triggerInMsg == 'do': messageType = 'action' elif triggerInMsg == 'notice': messageType = 'notice' bot.sendMessage(msgParts[1], messageToSay, messageType)
<commit_before>from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) if triggerInMsg == 'say': bot.say(msgParts[1], messageToSay) elif triggerInMsg == 'do': bot.doAction(msgParts[1], messageToSay) <commit_msg>Move to sendMessage command for message sending. Also add 'notice' trigger, because why not<commit_after>from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do', 'notice'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) messageType = 'say' if triggerInMsg == 'do': messageType = 'action' elif triggerInMsg == 'notice': messageType = 'notice' bot.sendMessage(msgParts[1], messageToSay, messageType)