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
f9a8e5107cc3f9d94f43bd5ce60054f849be2c15
tests/utils.py
tests/utils.py
import copy import os from django.conf import settings from django.template import Context from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator to specify the template path. """ # copy the original setting TEMPLATES = copy.deepcopy(settings.TEMPLATES) for tpl_cfg in TEMPLATES: tpl_cfg['DIRS'] = [template_path(rel_dir) for rel_dir in relative_dirs] return override_settings(TEMPLATES=TEMPLATES) class TemplateTestMixin(object): def setUp(self): self.ctx = Context() def assertNotInHTML(self, needle, haystack, msg_prefix=''): self.assertInHTML(needle, haystack, count=0, msg_prefix=msg_prefix)
import copy import os from django.conf import settings from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator to specify the template path. """ # copy the original setting TEMPLATES = copy.deepcopy(settings.TEMPLATES) for tpl_cfg in TEMPLATES: tpl_cfg['DIRS'] = [template_path(rel_dir) for rel_dir in relative_dirs] return override_settings(TEMPLATES=TEMPLATES) class TemplateTestMixin(object): def setUp(self): self.ctx = {} def assertNotInHTML(self, needle, haystack, msg_prefix=''): self.assertInHTML(needle, haystack, count=0, msg_prefix=msg_prefix)
Fix use of Context for dj1.11
Fix use of Context for dj1.11
Python
mit
funkybob/django-sniplates,funkybob/django-sniplates
import copy import os from django.conf import settings from django.template import Context from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator to specify the template path. """ # copy the original setting TEMPLATES = copy.deepcopy(settings.TEMPLATES) for tpl_cfg in TEMPLATES: tpl_cfg['DIRS'] = [template_path(rel_dir) for rel_dir in relative_dirs] return override_settings(TEMPLATES=TEMPLATES) class TemplateTestMixin(object): def setUp(self): self.ctx = Context() def assertNotInHTML(self, needle, haystack, msg_prefix=''): self.assertInHTML(needle, haystack, count=0, msg_prefix=msg_prefix) Fix use of Context for dj1.11
import copy import os from django.conf import settings from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator to specify the template path. """ # copy the original setting TEMPLATES = copy.deepcopy(settings.TEMPLATES) for tpl_cfg in TEMPLATES: tpl_cfg['DIRS'] = [template_path(rel_dir) for rel_dir in relative_dirs] return override_settings(TEMPLATES=TEMPLATES) class TemplateTestMixin(object): def setUp(self): self.ctx = {} def assertNotInHTML(self, needle, haystack, msg_prefix=''): self.assertInHTML(needle, haystack, count=0, msg_prefix=msg_prefix)
<commit_before>import copy import os from django.conf import settings from django.template import Context from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator to specify the template path. """ # copy the original setting TEMPLATES = copy.deepcopy(settings.TEMPLATES) for tpl_cfg in TEMPLATES: tpl_cfg['DIRS'] = [template_path(rel_dir) for rel_dir in relative_dirs] return override_settings(TEMPLATES=TEMPLATES) class TemplateTestMixin(object): def setUp(self): self.ctx = Context() def assertNotInHTML(self, needle, haystack, msg_prefix=''): self.assertInHTML(needle, haystack, count=0, msg_prefix=msg_prefix) <commit_msg>Fix use of Context for dj1.11<commit_after>
import copy import os from django.conf import settings from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator to specify the template path. """ # copy the original setting TEMPLATES = copy.deepcopy(settings.TEMPLATES) for tpl_cfg in TEMPLATES: tpl_cfg['DIRS'] = [template_path(rel_dir) for rel_dir in relative_dirs] return override_settings(TEMPLATES=TEMPLATES) class TemplateTestMixin(object): def setUp(self): self.ctx = {} def assertNotInHTML(self, needle, haystack, msg_prefix=''): self.assertInHTML(needle, haystack, count=0, msg_prefix=msg_prefix)
import copy import os from django.conf import settings from django.template import Context from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator to specify the template path. """ # copy the original setting TEMPLATES = copy.deepcopy(settings.TEMPLATES) for tpl_cfg in TEMPLATES: tpl_cfg['DIRS'] = [template_path(rel_dir) for rel_dir in relative_dirs] return override_settings(TEMPLATES=TEMPLATES) class TemplateTestMixin(object): def setUp(self): self.ctx = Context() def assertNotInHTML(self, needle, haystack, msg_prefix=''): self.assertInHTML(needle, haystack, count=0, msg_prefix=msg_prefix) Fix use of Context for dj1.11import copy import os from django.conf import settings from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator to specify the template path. """ # copy the original setting TEMPLATES = copy.deepcopy(settings.TEMPLATES) for tpl_cfg in TEMPLATES: tpl_cfg['DIRS'] = [template_path(rel_dir) for rel_dir in relative_dirs] return override_settings(TEMPLATES=TEMPLATES) class TemplateTestMixin(object): def setUp(self): self.ctx = {} def assertNotInHTML(self, needle, haystack, msg_prefix=''): self.assertInHTML(needle, haystack, count=0, msg_prefix=msg_prefix)
<commit_before>import copy import os from django.conf import settings from django.template import Context from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator to specify the template path. """ # copy the original setting TEMPLATES = copy.deepcopy(settings.TEMPLATES) for tpl_cfg in TEMPLATES: tpl_cfg['DIRS'] = [template_path(rel_dir) for rel_dir in relative_dirs] return override_settings(TEMPLATES=TEMPLATES) class TemplateTestMixin(object): def setUp(self): self.ctx = Context() def assertNotInHTML(self, needle, haystack, msg_prefix=''): self.assertInHTML(needle, haystack, count=0, msg_prefix=msg_prefix) <commit_msg>Fix use of Context for dj1.11<commit_after>import copy import os from django.conf import settings from django.test import override_settings HERE = os.path.dirname(__file__) def template_path(path): return os.path.join(HERE, 'templates', path, '') def template_dirs(*relative_dirs): """ Convenient decorator to specify the template path. """ # copy the original setting TEMPLATES = copy.deepcopy(settings.TEMPLATES) for tpl_cfg in TEMPLATES: tpl_cfg['DIRS'] = [template_path(rel_dir) for rel_dir in relative_dirs] return override_settings(TEMPLATES=TEMPLATES) class TemplateTestMixin(object): def setUp(self): self.ctx = {} def assertNotInHTML(self, needle, haystack, msg_prefix=''): self.assertInHTML(needle, haystack, count=0, msg_prefix=msg_prefix)
8095c37e0ab99e9827acbe4621f2fcb9334e1426
games/management/commands/autocreate_steamdb_installers.py
games/management/commands/autocreate_steamdb_installers.py
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'] == 'Game Works': appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save()
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'].startswith('Game Works'): appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save()
Update installer autocreate for games with no icon
Update installer autocreate for games with no icon
Python
agpl-3.0
Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,lutris/website,lutris/website,lutris/website,Turupawn/website
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'] == 'Game Works': appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save() Update installer autocreate for games with no icon
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'].startswith('Game Works'): appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save()
<commit_before>import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'] == 'Game Works': appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save() <commit_msg>Update installer autocreate for games with no icon<commit_after>
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'].startswith('Game Works'): appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save()
import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'] == 'Game Works': appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save() Update installer autocreate for games with no iconimport json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'].startswith('Game Works'): appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save()
<commit_before>import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'] == 'Game Works': appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save() <commit_msg>Update installer autocreate for games with no icon<commit_after>import json from django.core.management.base import BaseCommand from games import models from accounts.models import User class Command(BaseCommand): def handle(self, *args, **options): with open("steamdb.json") as steamdb_file: steamdb = json.loads(steamdb_file.read()) steam_runner = models.Runner.objects.get(slug='steam') user = User.objects.get(username='strider') for steamapp in steamdb: if steamapp['linux_status'].startswith('Game Works'): appid = steamapp['appid'] name = steamapp['name'] try: game = models.Game.objects.get(steamid=int(appid)) except models.Game.DoesNotExist: continue current_installer = game.installer_set.all() if current_installer: continue self.stdout.write("Creating installer for %s" % name) installer = models.Installer() installer.runner = steam_runner installer.user = user installer.game = game installer.set_default_installer() installer.published = True installer.save()
f87b9dd4674031aceb7e47de37a57ea190ec264d
tmc/exercise_tests/check.py
tmc/exercise_tests/check.py
import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(False, err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = xmlsrc.replace(r"&", "&amp;") ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret
import re import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(success=False, message=err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = re.sub(r"&(\s)", r"&amp;\1", xmlsrc) ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret
Use a bit better regex for XML error workaround, actually failable compile
Use a bit better regex for XML error workaround, actually failable compile
Python
mit
JuhaniImberg/tmc.py,JuhaniImberg/tmc.py
import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(False, err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = xmlsrc.replace(r"&", "&amp;") ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret Use a bit better regex for XML error workaround, actually failable compile
import re import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(success=False, message=err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = re.sub(r"&(\s)", r"&amp;\1", xmlsrc) ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret
<commit_before>import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(False, err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = xmlsrc.replace(r"&", "&amp;") ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret <commit_msg>Use a bit better regex for XML error workaround, actually failable compile<commit_after>
import re import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(success=False, message=err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = re.sub(r"&(\s)", r"&amp;\1", xmlsrc) ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret
import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(False, err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = xmlsrc.replace(r"&", "&amp;") ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret Use a bit better regex for XML error workaround, actually failable compileimport re import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(success=False, message=err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = re.sub(r"&(\s)", r"&amp;\1", xmlsrc) ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret
<commit_before>import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(False, err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = xmlsrc.replace(r"&", "&amp;") ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret <commit_msg>Use a bit better regex for XML error workaround, actually failable compile<commit_after>import re import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(success=False, message=err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = re.sub(r"&(\s)", r"&amp;\1", xmlsrc) ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret
b0ed850da2573cd8a99fc9f628f2da8a3bc97c71
greenmine/base/monkey.py
greenmine/base/monkey.py
# -*- coding: utf-8 -*- from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print "Patching APIView" views.APIView = APIView
# -*- coding: utf-8 -*- from __future__ import print_function import sys from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print("Patching APIView", file=sys.stderr) views.APIView = APIView
Send print message to sys.stderr
Smallfix: Send print message to sys.stderr
Python
agpl-3.0
EvgeneOskin/taiga-back,taigaio/taiga-back,rajiteh/taiga-back,Zaneh-/bearded-tribble-back,gauravjns/taiga-back,obimod/taiga-back,dycodedev/taiga-back,WALR/taiga-back,joshisa/taiga-back,bdang2012/taiga-back-casting,Rademade/taiga-back,CMLL/taiga-back,crr0004/taiga-back,taigaio/taiga-back,obimod/taiga-back,dayatz/taiga-back,Zaneh-/bearded-tribble-back,seanchen/taiga-back,WALR/taiga-back,forging2012/taiga-back,CMLL/taiga-back,coopsource/taiga-back,EvgeneOskin/taiga-back,gauravjns/taiga-back,19kestier/taiga-back,xdevelsistemas/taiga-back-community,gauravjns/taiga-back,Rademade/taiga-back,CoolCloud/taiga-back,xdevelsistemas/taiga-back-community,CMLL/taiga-back,jeffdwyatt/taiga-back,Rademade/taiga-back,dycodedev/taiga-back,dayatz/taiga-back,EvgeneOskin/taiga-back,gam-phon/taiga-back,frt-arch/taiga-back,forging2012/taiga-back,19kestier/taiga-back,CoolCloud/taiga-back,gam-phon/taiga-back,Rademade/taiga-back,astagi/taiga-back,Tigerwhit4/taiga-back,dycodedev/taiga-back,astronaut1712/taiga-back,seanchen/taiga-back,Tigerwhit4/taiga-back,astagi/taiga-back,19kestier/taiga-back,bdang2012/taiga-back-casting,crr0004/taiga-back,gauravjns/taiga-back,crr0004/taiga-back,gam-phon/taiga-back,CoolCloud/taiga-back,jeffdwyatt/taiga-back,Tigerwhit4/taiga-back,astagi/taiga-back,obimod/taiga-back,forging2012/taiga-back,EvgeneOskin/taiga-back,rajiteh/taiga-back,crr0004/taiga-back,seanchen/taiga-back,CMLL/taiga-back,rajiteh/taiga-back,joshisa/taiga-back,taigaio/taiga-back,forging2012/taiga-back,coopsource/taiga-back,astronaut1712/taiga-back,Zaneh-/bearded-tribble-back,dayatz/taiga-back,joshisa/taiga-back,gam-phon/taiga-back,jeffdwyatt/taiga-back,bdang2012/taiga-back-casting,coopsource/taiga-back,obimod/taiga-back,WALR/taiga-back,coopsource/taiga-back,bdang2012/taiga-back-casting,joshisa/taiga-back,astronaut1712/taiga-back,CoolCloud/taiga-back,astagi/taiga-back,dycodedev/taiga-back,seanchen/taiga-back,Rademade/taiga-back,xdevelsistemas/taiga-back-community,WALR/taiga-back,rajiteh/taiga-back,Tigerwhit4/taiga-back,frt-arch/taiga-back,astronaut1712/taiga-back,jeffdwyatt/taiga-back,frt-arch/taiga-back
# -*- coding: utf-8 -*- from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print "Patching APIView" views.APIView = APIView Smallfix: Send print message to sys.stderr
# -*- coding: utf-8 -*- from __future__ import print_function import sys from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print("Patching APIView", file=sys.stderr) views.APIView = APIView
<commit_before># -*- coding: utf-8 -*- from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print "Patching APIView" views.APIView = APIView <commit_msg>Smallfix: Send print message to sys.stderr<commit_after>
# -*- coding: utf-8 -*- from __future__ import print_function import sys from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print("Patching APIView", file=sys.stderr) views.APIView = APIView
# -*- coding: utf-8 -*- from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print "Patching APIView" views.APIView = APIView Smallfix: Send print message to sys.stderr# -*- coding: utf-8 -*- from __future__ import print_function import sys from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print("Patching APIView", file=sys.stderr) views.APIView = APIView
<commit_before># -*- coding: utf-8 -*- from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print "Patching APIView" views.APIView = APIView <commit_msg>Smallfix: Send print message to sys.stderr<commit_after># -*- coding: utf-8 -*- from __future__ import print_function import sys from rest_framework import views from rest_framework import status, exceptions from rest_framework.response import Response def patch_api_view(): from django.views.generic import View if hasattr(views, "_patched"): return views._APIView = views.APIView views._patched = True class APIView(views.APIView): def handle_exception(self, exc): if isinstance(exc, exceptions.NotAuthenticated): return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED, exception=True) return super(APIView, self).handle_exception(exc) @classmethod def as_view(cls, **initkwargs): view = super(views._APIView, cls).as_view(**initkwargs) view.cls_instance = cls(**initkwargs) return view print("Patching APIView", file=sys.stderr) views.APIView = APIView
6611153650b697d56f14be347946f4a814d7fc72
src/urllib3/_version.py
src/urllib3/_version.py
# This file is protected via CODEOWNERS __version__ = "1.26.0.dev0"
# This file is protected via CODEOWNERS __version__ = "2.0.0.dev0"
Mark master branch as 2.0.0 development branch
Mark master branch as 2.0.0 development branch
Python
mit
urllib3/urllib3,sigmavirus24/urllib3,sigmavirus24/urllib3,urllib3/urllib3
# This file is protected via CODEOWNERS __version__ = "1.26.0.dev0" Mark master branch as 2.0.0 development branch
# This file is protected via CODEOWNERS __version__ = "2.0.0.dev0"
<commit_before># This file is protected via CODEOWNERS __version__ = "1.26.0.dev0" <commit_msg>Mark master branch as 2.0.0 development branch<commit_after>
# This file is protected via CODEOWNERS __version__ = "2.0.0.dev0"
# This file is protected via CODEOWNERS __version__ = "1.26.0.dev0" Mark master branch as 2.0.0 development branch# This file is protected via CODEOWNERS __version__ = "2.0.0.dev0"
<commit_before># This file is protected via CODEOWNERS __version__ = "1.26.0.dev0" <commit_msg>Mark master branch as 2.0.0 development branch<commit_after># This file is protected via CODEOWNERS __version__ = "2.0.0.dev0"
fee78440de784bee91669e6c4f1d2c301202e29d
apps/blogs/serializers.py
apps/blogs/serializers.py
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def to_native(self, obj): request = self.context.get('request', None) contents_html = render_placeholder(request, obj) return contents_html class BlogPostAuthorSerializer(serializers.ModelSerializer): picture = SorlImageField('userprofile.picture', '90x90', crop='center') class Meta: model = User fields = ('first_name', 'last_name', 'picture') class BlogPostDetailSerializer(serializers.ModelSerializer): contents = BlogPostContentsField('contents') author = BlogPostAuthorSerializer() url = SlugHyperlinkedIdentityField(view_name='blogpost-instance') class Meta: model = BlogPost exclude = ('id',) class BlogPostPreviewSerializer(BlogPostDetailSerializer): class Meta: model = BlogPost exclude = ('id',)
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def to_native(self, obj): request = self.context.get('request', None) contents_html = render_placeholder(request, obj) return contents_html class BlogPostAuthorSerializer(serializers.ModelSerializer): picture = SorlImageField('userprofile.picture', '90x90', crop='center') class Meta: model = User fields = ('first_name', 'last_name', 'picture') class BlogPostDetailSerializer(serializers.ModelSerializer): contents = BlogPostContentsField(source='contents') author = BlogPostAuthorSerializer() url = SlugHyperlinkedIdentityField(view_name='blogpost-instance') main_image = SorlImageField('main_image', '300x200', crop='center') class Meta: model = BlogPost exclude = ('id',) class BlogPostPreviewSerializer(BlogPostDetailSerializer): class Meta: model = BlogPost exclude = ('id',)
Add main_image to BlogPost API response.
Add main_image to BlogPost API response.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def to_native(self, obj): request = self.context.get('request', None) contents_html = render_placeholder(request, obj) return contents_html class BlogPostAuthorSerializer(serializers.ModelSerializer): picture = SorlImageField('userprofile.picture', '90x90', crop='center') class Meta: model = User fields = ('first_name', 'last_name', 'picture') class BlogPostDetailSerializer(serializers.ModelSerializer): contents = BlogPostContentsField('contents') author = BlogPostAuthorSerializer() url = SlugHyperlinkedIdentityField(view_name='blogpost-instance') class Meta: model = BlogPost exclude = ('id',) class BlogPostPreviewSerializer(BlogPostDetailSerializer): class Meta: model = BlogPost exclude = ('id',) Add main_image to BlogPost API response.
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def to_native(self, obj): request = self.context.get('request', None) contents_html = render_placeholder(request, obj) return contents_html class BlogPostAuthorSerializer(serializers.ModelSerializer): picture = SorlImageField('userprofile.picture', '90x90', crop='center') class Meta: model = User fields = ('first_name', 'last_name', 'picture') class BlogPostDetailSerializer(serializers.ModelSerializer): contents = BlogPostContentsField(source='contents') author = BlogPostAuthorSerializer() url = SlugHyperlinkedIdentityField(view_name='blogpost-instance') main_image = SorlImageField('main_image', '300x200', crop='center') class Meta: model = BlogPost exclude = ('id',) class BlogPostPreviewSerializer(BlogPostDetailSerializer): class Meta: model = BlogPost exclude = ('id',)
<commit_before>from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def to_native(self, obj): request = self.context.get('request', None) contents_html = render_placeholder(request, obj) return contents_html class BlogPostAuthorSerializer(serializers.ModelSerializer): picture = SorlImageField('userprofile.picture', '90x90', crop='center') class Meta: model = User fields = ('first_name', 'last_name', 'picture') class BlogPostDetailSerializer(serializers.ModelSerializer): contents = BlogPostContentsField('contents') author = BlogPostAuthorSerializer() url = SlugHyperlinkedIdentityField(view_name='blogpost-instance') class Meta: model = BlogPost exclude = ('id',) class BlogPostPreviewSerializer(BlogPostDetailSerializer): class Meta: model = BlogPost exclude = ('id',) <commit_msg>Add main_image to BlogPost API response.<commit_after>
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def to_native(self, obj): request = self.context.get('request', None) contents_html = render_placeholder(request, obj) return contents_html class BlogPostAuthorSerializer(serializers.ModelSerializer): picture = SorlImageField('userprofile.picture', '90x90', crop='center') class Meta: model = User fields = ('first_name', 'last_name', 'picture') class BlogPostDetailSerializer(serializers.ModelSerializer): contents = BlogPostContentsField(source='contents') author = BlogPostAuthorSerializer() url = SlugHyperlinkedIdentityField(view_name='blogpost-instance') main_image = SorlImageField('main_image', '300x200', crop='center') class Meta: model = BlogPost exclude = ('id',) class BlogPostPreviewSerializer(BlogPostDetailSerializer): class Meta: model = BlogPost exclude = ('id',)
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def to_native(self, obj): request = self.context.get('request', None) contents_html = render_placeholder(request, obj) return contents_html class BlogPostAuthorSerializer(serializers.ModelSerializer): picture = SorlImageField('userprofile.picture', '90x90', crop='center') class Meta: model = User fields = ('first_name', 'last_name', 'picture') class BlogPostDetailSerializer(serializers.ModelSerializer): contents = BlogPostContentsField('contents') author = BlogPostAuthorSerializer() url = SlugHyperlinkedIdentityField(view_name='blogpost-instance') class Meta: model = BlogPost exclude = ('id',) class BlogPostPreviewSerializer(BlogPostDetailSerializer): class Meta: model = BlogPost exclude = ('id',) Add main_image to BlogPost API response.from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def to_native(self, obj): request = self.context.get('request', None) contents_html = render_placeholder(request, obj) return contents_html class BlogPostAuthorSerializer(serializers.ModelSerializer): picture = SorlImageField('userprofile.picture', '90x90', crop='center') class Meta: model = User fields = ('first_name', 'last_name', 'picture') class BlogPostDetailSerializer(serializers.ModelSerializer): contents = BlogPostContentsField(source='contents') author = BlogPostAuthorSerializer() url = SlugHyperlinkedIdentityField(view_name='blogpost-instance') main_image = SorlImageField('main_image', '300x200', crop='center') class Meta: model = BlogPost exclude = ('id',) class BlogPostPreviewSerializer(BlogPostDetailSerializer): class Meta: model = BlogPost exclude = ('id',)
<commit_before>from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def to_native(self, obj): request = self.context.get('request', None) contents_html = render_placeholder(request, obj) return contents_html class BlogPostAuthorSerializer(serializers.ModelSerializer): picture = SorlImageField('userprofile.picture', '90x90', crop='center') class Meta: model = User fields = ('first_name', 'last_name', 'picture') class BlogPostDetailSerializer(serializers.ModelSerializer): contents = BlogPostContentsField('contents') author = BlogPostAuthorSerializer() url = SlugHyperlinkedIdentityField(view_name='blogpost-instance') class Meta: model = BlogPost exclude = ('id',) class BlogPostPreviewSerializer(BlogPostDetailSerializer): class Meta: model = BlogPost exclude = ('id',) <commit_msg>Add main_image to BlogPost API response.<commit_after>from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField from django.contrib.auth.models import User from fluent_contents.rendering import render_placeholder from rest_framework import serializers from .models import BlogPost class BlogPostContentsField(serializers.Field): def to_native(self, obj): request = self.context.get('request', None) contents_html = render_placeholder(request, obj) return contents_html class BlogPostAuthorSerializer(serializers.ModelSerializer): picture = SorlImageField('userprofile.picture', '90x90', crop='center') class Meta: model = User fields = ('first_name', 'last_name', 'picture') class BlogPostDetailSerializer(serializers.ModelSerializer): contents = BlogPostContentsField(source='contents') author = BlogPostAuthorSerializer() url = SlugHyperlinkedIdentityField(view_name='blogpost-instance') main_image = SorlImageField('main_image', '300x200', crop='center') class Meta: model = BlogPost exclude = ('id',) class BlogPostPreviewSerializer(BlogPostDetailSerializer): class Meta: model = BlogPost exclude = ('id',)
ddd5adaa1023bc30753fa7ef893ddc8e2ae186d8
clowder_server/management/commands/send_alerts.py
clowder_server/management/commands/send_alerts.py
import datetime from django.core.management.base import BaseCommand, CommandError from clowder_account.models import Company from clowder_server.emailer import send_alert from clowder_server.models import Alert, Ping class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **options): # delete old pings for company in Company.objects.all(): pings_by_name = Ping.objects.filter(company=company).distinct('name') if not pings_by_name: continue max_per_ping = 500 / len(pings_by_name) for name in pings_by_name: pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping] pings = list(pings.values_list("id", flat=True)) Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete() # send alerts alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now) for alert in alerts: send_alert(alert.company, alert.name) alert.notify_at = None alert.save()
import datetime from django.core.management.base import BaseCommand, CommandError from clowder_account.models import Company from clowder_server.emailer import send_alert from clowder_server.models import Alert, Ping class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **options): # delete old pings for company in Company.objects.all(): pings_by_name = Ping.objects.filter(company=company).distinct('name') if not pings_by_name: continue max_per_ping = 2000 / len(pings_by_name) for name in pings_by_name: pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping] pings = list(pings.values_list("id", flat=True)) Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete() # send alerts alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now) for alert in alerts: send_alert(alert.company, alert.name) alert.notify_at = None alert.save()
Store more pings per transaction
Store more pings per transaction
Python
agpl-3.0
keithhackbarth/clowder_server,framewr/clowder_server,keithhackbarth/clowder_server,framewr/clowder_server,framewr/clowder_server,keithhackbarth/clowder_server,keithhackbarth/clowder_server,framewr/clowder_server
import datetime from django.core.management.base import BaseCommand, CommandError from clowder_account.models import Company from clowder_server.emailer import send_alert from clowder_server.models import Alert, Ping class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **options): # delete old pings for company in Company.objects.all(): pings_by_name = Ping.objects.filter(company=company).distinct('name') if not pings_by_name: continue max_per_ping = 500 / len(pings_by_name) for name in pings_by_name: pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping] pings = list(pings.values_list("id", flat=True)) Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete() # send alerts alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now) for alert in alerts: send_alert(alert.company, alert.name) alert.notify_at = None alert.save() Store more pings per transaction
import datetime from django.core.management.base import BaseCommand, CommandError from clowder_account.models import Company from clowder_server.emailer import send_alert from clowder_server.models import Alert, Ping class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **options): # delete old pings for company in Company.objects.all(): pings_by_name = Ping.objects.filter(company=company).distinct('name') if not pings_by_name: continue max_per_ping = 2000 / len(pings_by_name) for name in pings_by_name: pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping] pings = list(pings.values_list("id", flat=True)) Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete() # send alerts alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now) for alert in alerts: send_alert(alert.company, alert.name) alert.notify_at = None alert.save()
<commit_before>import datetime from django.core.management.base import BaseCommand, CommandError from clowder_account.models import Company from clowder_server.emailer import send_alert from clowder_server.models import Alert, Ping class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **options): # delete old pings for company in Company.objects.all(): pings_by_name = Ping.objects.filter(company=company).distinct('name') if not pings_by_name: continue max_per_ping = 500 / len(pings_by_name) for name in pings_by_name: pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping] pings = list(pings.values_list("id", flat=True)) Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete() # send alerts alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now) for alert in alerts: send_alert(alert.company, alert.name) alert.notify_at = None alert.save() <commit_msg>Store more pings per transaction<commit_after>
import datetime from django.core.management.base import BaseCommand, CommandError from clowder_account.models import Company from clowder_server.emailer import send_alert from clowder_server.models import Alert, Ping class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **options): # delete old pings for company in Company.objects.all(): pings_by_name = Ping.objects.filter(company=company).distinct('name') if not pings_by_name: continue max_per_ping = 2000 / len(pings_by_name) for name in pings_by_name: pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping] pings = list(pings.values_list("id", flat=True)) Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete() # send alerts alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now) for alert in alerts: send_alert(alert.company, alert.name) alert.notify_at = None alert.save()
import datetime from django.core.management.base import BaseCommand, CommandError from clowder_account.models import Company from clowder_server.emailer import send_alert from clowder_server.models import Alert, Ping class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **options): # delete old pings for company in Company.objects.all(): pings_by_name = Ping.objects.filter(company=company).distinct('name') if not pings_by_name: continue max_per_ping = 500 / len(pings_by_name) for name in pings_by_name: pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping] pings = list(pings.values_list("id", flat=True)) Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete() # send alerts alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now) for alert in alerts: send_alert(alert.company, alert.name) alert.notify_at = None alert.save() Store more pings per transactionimport datetime from django.core.management.base import BaseCommand, CommandError from clowder_account.models import Company from clowder_server.emailer import send_alert from clowder_server.models import Alert, Ping class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **options): # delete old pings for company in Company.objects.all(): pings_by_name = Ping.objects.filter(company=company).distinct('name') if not pings_by_name: continue max_per_ping = 2000 / len(pings_by_name) for name in pings_by_name: pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping] pings = list(pings.values_list("id", flat=True)) Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete() # send alerts alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now) for alert in alerts: send_alert(alert.company, alert.name) alert.notify_at = None alert.save()
<commit_before>import datetime from django.core.management.base import BaseCommand, CommandError from clowder_account.models import Company from clowder_server.emailer import send_alert from clowder_server.models import Alert, Ping class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **options): # delete old pings for company in Company.objects.all(): pings_by_name = Ping.objects.filter(company=company).distinct('name') if not pings_by_name: continue max_per_ping = 500 / len(pings_by_name) for name in pings_by_name: pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping] pings = list(pings.values_list("id", flat=True)) Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete() # send alerts alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now) for alert in alerts: send_alert(alert.company, alert.name) alert.notify_at = None alert.save() <commit_msg>Store more pings per transaction<commit_after>import datetime from django.core.management.base import BaseCommand, CommandError from clowder_account.models import Company from clowder_server.emailer import send_alert from clowder_server.models import Alert, Ping class Command(BaseCommand): help = 'Checks and sends alerts' def handle(self, *args, **options): # delete old pings for company in Company.objects.all(): pings_by_name = Ping.objects.filter(company=company).distinct('name') if not pings_by_name: continue max_per_ping = 2000 / len(pings_by_name) for name in pings_by_name: pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping] pings = list(pings.values_list("id", flat=True)) Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete() # send alerts alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now) for alert in alerts: send_alert(alert.company, alert.name) alert.notify_at = None alert.save()
8fd5c5c8c7aec1cc045f7f2fcbecb16be129c19b
jobs/templatetags/jobs_tags.py
jobs/templatetags/jobs_tags.py
from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None
from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): if 'page' not in context: return None try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None
Add fix for non pages like search.
Add fix for non pages like search.
Python
mit
OpenCanada/website,OpenCanada/website,OpenCanada/website,OpenCanada/website
from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None Add fix for non pages like search.
from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): if 'page' not in context: return None try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None
<commit_before>from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None <commit_msg>Add fix for non pages like search.<commit_after>
from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): if 'page' not in context: return None try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None
from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None Add fix for non pages like search.from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): if 'page' not in context: return None try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None
<commit_before>from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None <commit_msg>Add fix for non pages like search.<commit_after>from django import template from django.db.models import ObjectDoesNotExist from jobs.models import JobPostingListPage register = template.Library() @register.simple_tag(takes_context=True) def get_active_posting_page(context): if 'page' not in context: return None try: root = context['page'].get_root() listing_pages = JobPostingListPage.objects.descendant_of(root) if listing_pages.count() > 0: listing_page = listing_pages[0] if listing_page.subpages.count() > 0: if listing_page.subpages.count() == 1: return listing_page.subpages[0] return listing_page return None except ObjectDoesNotExist: return None
e1a27161621038cc3bdfd4030aef130ee09e92ec
troposphere/dax.py
troposphere/dax.py
# Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): resource_type = "AWS::DAX::Cluster" props = { "AvailabilityZones": (str, False), "ClusterName": (str, False), "Description": (str, False), "IAMRoleARN": (str, True), "NodeType": (str, True), "NotificationTopicARN": (str, False), "ParameterGroupName": (str, False), "PreferredMaintenanceWindow": (str, False), "ReplicationFactor": (str, True), "SSESpecification": (SSESpecification, False), "SecurityGroupIds": ([str], False), "SubnetGroupName": (str, True), "Tags": (dict, False), } class ParameterGroup(AWSObject): resource_type = "AWS::DAX::ParameterGroup" props = { "Description": (str, False), "ParameterGroupName": (str, False), "ParameterNameValues": (dict, False), } class SubnetGroup(AWSObject): resource_type = "AWS::DAX::SubnetGroup" props = { "Description": (str, False), "SubnetGroupName": (str, False), "SubnetIds": ([str], False), }
# Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): resource_type = "AWS::DAX::Cluster" props = { "AvailabilityZones": (str, False), "ClusterEndpointEncryptionType": (str, False), "ClusterName": (str, False), "Description": (str, False), "IAMRoleARN": (str, True), "NodeType": (str, True), "NotificationTopicARN": (str, False), "ParameterGroupName": (str, False), "PreferredMaintenanceWindow": (str, False), "ReplicationFactor": (str, True), "SSESpecification": (SSESpecification, False), "SecurityGroupIds": ([str], False), "SubnetGroupName": (str, True), "Tags": (dict, False), } class ParameterGroup(AWSObject): resource_type = "AWS::DAX::ParameterGroup" props = { "Description": (str, False), "ParameterGroupName": (str, False), "ParameterNameValues": (dict, False), } class SubnetGroup(AWSObject): resource_type = "AWS::DAX::SubnetGroup" props = { "Description": (str, False), "SubnetGroupName": (str, False), "SubnetIds": ([str], False), }
Update DAX per 2021-06-24 changes
Update DAX per 2021-06-24 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
# Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): resource_type = "AWS::DAX::Cluster" props = { "AvailabilityZones": (str, False), "ClusterName": (str, False), "Description": (str, False), "IAMRoleARN": (str, True), "NodeType": (str, True), "NotificationTopicARN": (str, False), "ParameterGroupName": (str, False), "PreferredMaintenanceWindow": (str, False), "ReplicationFactor": (str, True), "SSESpecification": (SSESpecification, False), "SecurityGroupIds": ([str], False), "SubnetGroupName": (str, True), "Tags": (dict, False), } class ParameterGroup(AWSObject): resource_type = "AWS::DAX::ParameterGroup" props = { "Description": (str, False), "ParameterGroupName": (str, False), "ParameterNameValues": (dict, False), } class SubnetGroup(AWSObject): resource_type = "AWS::DAX::SubnetGroup" props = { "Description": (str, False), "SubnetGroupName": (str, False), "SubnetIds": ([str], False), } Update DAX per 2021-06-24 changes
# Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): resource_type = "AWS::DAX::Cluster" props = { "AvailabilityZones": (str, False), "ClusterEndpointEncryptionType": (str, False), "ClusterName": (str, False), "Description": (str, False), "IAMRoleARN": (str, True), "NodeType": (str, True), "NotificationTopicARN": (str, False), "ParameterGroupName": (str, False), "PreferredMaintenanceWindow": (str, False), "ReplicationFactor": (str, True), "SSESpecification": (SSESpecification, False), "SecurityGroupIds": ([str], False), "SubnetGroupName": (str, True), "Tags": (dict, False), } class ParameterGroup(AWSObject): resource_type = "AWS::DAX::ParameterGroup" props = { "Description": (str, False), "ParameterGroupName": (str, False), "ParameterNameValues": (dict, False), } class SubnetGroup(AWSObject): resource_type = "AWS::DAX::SubnetGroup" props = { "Description": (str, False), "SubnetGroupName": (str, False), "SubnetIds": ([str], False), }
<commit_before># Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): resource_type = "AWS::DAX::Cluster" props = { "AvailabilityZones": (str, False), "ClusterName": (str, False), "Description": (str, False), "IAMRoleARN": (str, True), "NodeType": (str, True), "NotificationTopicARN": (str, False), "ParameterGroupName": (str, False), "PreferredMaintenanceWindow": (str, False), "ReplicationFactor": (str, True), "SSESpecification": (SSESpecification, False), "SecurityGroupIds": ([str], False), "SubnetGroupName": (str, True), "Tags": (dict, False), } class ParameterGroup(AWSObject): resource_type = "AWS::DAX::ParameterGroup" props = { "Description": (str, False), "ParameterGroupName": (str, False), "ParameterNameValues": (dict, False), } class SubnetGroup(AWSObject): resource_type = "AWS::DAX::SubnetGroup" props = { "Description": (str, False), "SubnetGroupName": (str, False), "SubnetIds": ([str], False), } <commit_msg>Update DAX per 2021-06-24 changes<commit_after>
# Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): resource_type = "AWS::DAX::Cluster" props = { "AvailabilityZones": (str, False), "ClusterEndpointEncryptionType": (str, False), "ClusterName": (str, False), "Description": (str, False), "IAMRoleARN": (str, True), "NodeType": (str, True), "NotificationTopicARN": (str, False), "ParameterGroupName": (str, False), "PreferredMaintenanceWindow": (str, False), "ReplicationFactor": (str, True), "SSESpecification": (SSESpecification, False), "SecurityGroupIds": ([str], False), "SubnetGroupName": (str, True), "Tags": (dict, False), } class ParameterGroup(AWSObject): resource_type = "AWS::DAX::ParameterGroup" props = { "Description": (str, False), "ParameterGroupName": (str, False), "ParameterNameValues": (dict, False), } class SubnetGroup(AWSObject): resource_type = "AWS::DAX::SubnetGroup" props = { "Description": (str, False), "SubnetGroupName": (str, False), "SubnetIds": ([str], False), }
# Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): resource_type = "AWS::DAX::Cluster" props = { "AvailabilityZones": (str, False), "ClusterName": (str, False), "Description": (str, False), "IAMRoleARN": (str, True), "NodeType": (str, True), "NotificationTopicARN": (str, False), "ParameterGroupName": (str, False), "PreferredMaintenanceWindow": (str, False), "ReplicationFactor": (str, True), "SSESpecification": (SSESpecification, False), "SecurityGroupIds": ([str], False), "SubnetGroupName": (str, True), "Tags": (dict, False), } class ParameterGroup(AWSObject): resource_type = "AWS::DAX::ParameterGroup" props = { "Description": (str, False), "ParameterGroupName": (str, False), "ParameterNameValues": (dict, False), } class SubnetGroup(AWSObject): resource_type = "AWS::DAX::SubnetGroup" props = { "Description": (str, False), "SubnetGroupName": (str, False), "SubnetIds": ([str], False), } Update DAX per 2021-06-24 changes# Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): resource_type = "AWS::DAX::Cluster" props = { "AvailabilityZones": (str, False), "ClusterEndpointEncryptionType": (str, False), "ClusterName": (str, False), "Description": (str, False), "IAMRoleARN": (str, True), "NodeType": (str, True), "NotificationTopicARN": (str, False), "ParameterGroupName": (str, False), "PreferredMaintenanceWindow": (str, False), "ReplicationFactor": (str, True), "SSESpecification": (SSESpecification, False), "SecurityGroupIds": ([str], False), "SubnetGroupName": (str, True), "Tags": (dict, False), } class ParameterGroup(AWSObject): resource_type = "AWS::DAX::ParameterGroup" props = { "Description": (str, False), "ParameterGroupName": (str, False), "ParameterNameValues": (dict, False), } class SubnetGroup(AWSObject): resource_type = "AWS::DAX::SubnetGroup" props = { "Description": (str, False), "SubnetGroupName": (str, False), "SubnetIds": ([str], False), }
<commit_before># Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): resource_type = "AWS::DAX::Cluster" props = { "AvailabilityZones": (str, False), "ClusterName": (str, False), "Description": (str, False), "IAMRoleARN": (str, True), "NodeType": (str, True), "NotificationTopicARN": (str, False), "ParameterGroupName": (str, False), "PreferredMaintenanceWindow": (str, False), "ReplicationFactor": (str, True), "SSESpecification": (SSESpecification, False), "SecurityGroupIds": ([str], False), "SubnetGroupName": (str, True), "Tags": (dict, False), } class ParameterGroup(AWSObject): resource_type = "AWS::DAX::ParameterGroup" props = { "Description": (str, False), "ParameterGroupName": (str, False), "ParameterNameValues": (dict, False), } class SubnetGroup(AWSObject): resource_type = "AWS::DAX::SubnetGroup" props = { "Description": (str, False), "SubnetGroupName": (str, False), "SubnetIds": ([str], False), } <commit_msg>Update DAX per 2021-06-24 changes<commit_after># Copyright (c) 2012-2017, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty from .validators import boolean class SSESpecification(AWSProperty): props = { "SSEEnabled": (boolean, False), } class Cluster(AWSObject): resource_type = "AWS::DAX::Cluster" props = { "AvailabilityZones": (str, False), "ClusterEndpointEncryptionType": (str, False), "ClusterName": (str, False), "Description": (str, False), "IAMRoleARN": (str, True), "NodeType": (str, True), "NotificationTopicARN": (str, False), "ParameterGroupName": (str, False), "PreferredMaintenanceWindow": (str, False), "ReplicationFactor": (str, True), "SSESpecification": (SSESpecification, False), "SecurityGroupIds": ([str], False), "SubnetGroupName": (str, True), "Tags": (dict, False), } class ParameterGroup(AWSObject): resource_type = "AWS::DAX::ParameterGroup" props = { "Description": (str, False), "ParameterGroupName": (str, False), "ParameterNameValues": (dict, False), } class SubnetGroup(AWSObject): resource_type = "AWS::DAX::SubnetGroup" props = { "Description": (str, False), "SubnetGroupName": (str, False), "SubnetIds": ([str], False), }
31a0d75b573421dbc05aad95df8b3c74a7154057
tx_highered/api.py
tx_highered/api.py
import json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': unicode(i), }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view()
import json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': i.name, }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view()
Return name instead of unicode in autocomplete API
Return name instead of unicode in autocomplete API
Python
apache-2.0
texastribune/the-dp,texastribune/the-dp,texastribune/the-dp,texastribune/the-dp
import json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': unicode(i), }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view() Return name instead of unicode in autocomplete API
import json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': i.name, }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view()
<commit_before>import json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': unicode(i), }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view() <commit_msg>Return name instead of unicode in autocomplete API<commit_after>
import json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': i.name, }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view()
import json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': unicode(i), }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view() Return name instead of unicode in autocomplete APIimport json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': i.name, }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view()
<commit_before>import json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': unicode(i), }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view() <commit_msg>Return name instead of unicode in autocomplete API<commit_after>import json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': i.name, }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view()
815891deabea40d3c38f84ab16047a67972889d6
simplesqlite/loader/error.py
simplesqlite/loader/error.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class ValidationError(Exception): """ Raised data is not properly formatted. """ class InvalidDataError(Exception): """ Raised when data is invalid to load. """ class OpenError(IOError): """ Raised when failed to open a file. """
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class ValidationError(Exception): """ Raised data is not properly formatted. """ class InvalidDataError(ValueError): """ Raised when data is invalid to load. """ class OpenError(IOError): """ Raised when failed to open a file. """
Modify super class of InvalidDataError
Modify super class of InvalidDataError
Python
mit
thombashi/SimpleSQLite,thombashi/SimpleSQLite
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class ValidationError(Exception): """ Raised data is not properly formatted. """ class InvalidDataError(Exception): """ Raised when data is invalid to load. """ class OpenError(IOError): """ Raised when failed to open a file. """ Modify super class of InvalidDataError
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class ValidationError(Exception): """ Raised data is not properly formatted. """ class InvalidDataError(ValueError): """ Raised when data is invalid to load. """ class OpenError(IOError): """ Raised when failed to open a file. """
<commit_before># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class ValidationError(Exception): """ Raised data is not properly formatted. """ class InvalidDataError(Exception): """ Raised when data is invalid to load. """ class OpenError(IOError): """ Raised when failed to open a file. """ <commit_msg>Modify super class of InvalidDataError<commit_after>
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class ValidationError(Exception): """ Raised data is not properly formatted. """ class InvalidDataError(ValueError): """ Raised when data is invalid to load. """ class OpenError(IOError): """ Raised when failed to open a file. """
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class ValidationError(Exception): """ Raised data is not properly formatted. """ class InvalidDataError(Exception): """ Raised when data is invalid to load. """ class OpenError(IOError): """ Raised when failed to open a file. """ Modify super class of InvalidDataError# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class ValidationError(Exception): """ Raised data is not properly formatted. """ class InvalidDataError(ValueError): """ Raised when data is invalid to load. """ class OpenError(IOError): """ Raised when failed to open a file. """
<commit_before># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class ValidationError(Exception): """ Raised data is not properly formatted. """ class InvalidDataError(Exception): """ Raised when data is invalid to load. """ class OpenError(IOError): """ Raised when failed to open a file. """ <commit_msg>Modify super class of InvalidDataError<commit_after># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class ValidationError(Exception): """ Raised data is not properly formatted. """ class InvalidDataError(ValueError): """ Raised when data is invalid to load. """ class OpenError(IOError): """ Raised when failed to open a file. """
94ad884a245dea36110718577e47eb0c7b0c2b0a
skyfield/tests/test_topos.py
skyfield/tests/test_topos.py
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (15, 25, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=0, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees #print(b.latitude.degrees, deg, error_mas) assert error_mas < 0.1
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (-15, 15, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=angle, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1 error_degrees = abs(b.longitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1
Add test for subpoint() longitude correctness
Add test for subpoint() longitude correctness
Python
mit
skyfielders/python-skyfield,skyfielders/python-skyfield
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (15, 25, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=0, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees #print(b.latitude.degrees, deg, error_mas) assert error_mas < 0.1 Add test for subpoint() longitude correctness
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (-15, 15, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=angle, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1 error_degrees = abs(b.longitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1
<commit_before>from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (15, 25, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=0, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees #print(b.latitude.degrees, deg, error_mas) assert error_mas < 0.1 <commit_msg>Add test for subpoint() longitude correctness<commit_after>
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (-15, 15, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=angle, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1 error_degrees = abs(b.longitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (15, 25, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=0, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees #print(b.latitude.degrees, deg, error_mas) assert error_mas < 0.1 Add test for subpoint() longitude correctnessfrom numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (-15, 15, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=angle, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1 error_degrees = abs(b.longitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1
<commit_before>from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (15, 25, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=0, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees #print(b.latitude.degrees, deg, error_mas) assert error_mas < 0.1 <commit_msg>Add test for subpoint() longitude correctness<commit_after>from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (-15, 15, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=angle, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1 error_degrees = abs(b.longitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1
88a5a74ee1e3d3f3fe9e6a43bacd73b2f3f5bb96
tests/test_mongo.py
tests/test_mongo.py
import unittest import logging logging.basicConfig() logger = logging.getLogger() from checks.db.mongo import MongoDb class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logger) def testCheck(self): r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals("opcounters" in r, False) r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals(r["asserts"]["regularPS"], 0) self.assertEquals(r["asserts"]["userPS"], 0) self.assertEquals(r["opcounters"]["commandPS"], (244 - 18) / (10191 - 2893)) if __name__ == '__main__': unittest.main()
import unittest import logging logging.basicConfig() import subprocess from tempfile import mkdtemp from checks.db.mongo import MongoDb PORT1 = 27017 PORT2 = 37017 class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logging.getLogger()) # Start 1 instances of Mongo dir1 = mkdtemp() self.p1 = subprocess.Popen(["mongod", "--dbpath", dir1, "--port", str(PORT1)], executable="mongod", stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): if self.p1 is not None: self.p1.terminate() def testCheck(self): if self.p1 is not None: r = self.c.check({"MongoDBServer": "localhost", "mongodb_port": PORT1}) self.assertEquals(r and r["connections"]["current"] == 1, True) assert r["connections"]["available"] >= 1 assert r["uptime"] >= 0, r assert r["mem"]["resident"] > 0 assert r["mem"]["virtual"] > 0 if __name__ == '__main__': unittest.main()
Test does start a mongo instance.
Test does start a mongo instance.
Python
bsd-3-clause
jshum/dd-agent,mderomph-coolblue/dd-agent,AniruddhaSAtre/dd-agent,remh/dd-agent,lookout/dd-agent,PagerDuty/dd-agent,Mashape/dd-agent,indeedops/dd-agent,GabrielNicolasAvellaneda/dd-agent,AntoCard/powerdns-recursor_check,citrusleaf/dd-agent,benmccann/dd-agent,gphat/dd-agent,mderomph-coolblue/dd-agent,zendesk/dd-agent,huhongbo/dd-agent,a20012251/dd-agent,joelvanvelden/dd-agent,huhongbo/dd-agent,jshum/dd-agent,truthbk/dd-agent,AniruddhaSAtre/dd-agent,brettlangdon/dd-agent,jraede/dd-agent,jvassev/dd-agent,zendesk/dd-agent,jshum/dd-agent,darron/dd-agent,Mashape/dd-agent,polynomial/dd-agent,ess/dd-agent,amalakar/dd-agent,mderomph-coolblue/dd-agent,jyogi/purvar-agent,huhongbo/dd-agent,GabrielNicolasAvellaneda/dd-agent,urosgruber/dd-agent,gphat/dd-agent,cberry777/dd-agent,Mashape/dd-agent,urosgruber/dd-agent,citrusleaf/dd-agent,pfmooney/dd-agent,pmav99/praktoras,amalakar/dd-agent,a20012251/dd-agent,manolama/dd-agent,cberry777/dd-agent,JohnLZeller/dd-agent,yuecong/dd-agent,citrusleaf/dd-agent,packetloop/dd-agent,brettlangdon/dd-agent,Shopify/dd-agent,eeroniemi/dd-agent,pmav99/praktoras,darron/dd-agent,PagerDuty/dd-agent,c960657/dd-agent,JohnLZeller/dd-agent,jraede/dd-agent,benmccann/dd-agent,AniruddhaSAtre/dd-agent,pfmooney/dd-agent,ess/dd-agent,takus/dd-agent,PagerDuty/dd-agent,polynomial/dd-agent,tebriel/dd-agent,takus/dd-agent,oneandoneis2/dd-agent,AntoCard/powerdns-recursor_check,zendesk/dd-agent,joelvanvelden/dd-agent,jamesandariese/dd-agent,tebriel/dd-agent,oneandoneis2/dd-agent,guruxu/dd-agent,jraede/dd-agent,yuecong/dd-agent,oneandoneis2/dd-agent,PagerDuty/dd-agent,pmav99/praktoras,lookout/dd-agent,relateiq/dd-agent,jamesandariese/dd-agent,Shopify/dd-agent,truthbk/dd-agent,manolama/dd-agent,eeroniemi/dd-agent,indeedops/dd-agent,gphat/dd-agent,jvassev/dd-agent,urosgruber/dd-agent,jraede/dd-agent,indeedops/dd-agent,a20012251/dd-agent,huhongbo/dd-agent,mderomph-coolblue/dd-agent,Wattpad/dd-agent,remh/dd-agent,Shopify/dd-agent,takus/dd-agent,joelvanvelden/dd-agent,Mashape/dd-agent,pmav99/praktoras,relateiq/dd-agent,amalakar/dd-agent,ess/dd-agent,truthbk/dd-agent,relateiq/dd-agent,jshum/dd-agent,lookout/dd-agent,brettlangdon/dd-agent,jvassev/dd-agent,darron/dd-agent,manolama/dd-agent,eeroniemi/dd-agent,yuecong/dd-agent,ess/dd-agent,c960657/dd-agent,AntoCard/powerdns-recursor_check,zendesk/dd-agent,urosgruber/dd-agent,tebriel/dd-agent,jamesandariese/dd-agent,truthbk/dd-agent,jshum/dd-agent,relateiq/dd-agent,benmccann/dd-agent,guruxu/dd-agent,jvassev/dd-agent,pfmooney/dd-agent,packetloop/dd-agent,ess/dd-agent,amalakar/dd-agent,yuecong/dd-agent,guruxu/dd-agent,a20012251/dd-agent,polynomial/dd-agent,oneandoneis2/dd-agent,gphat/dd-agent,indeedops/dd-agent,Shopify/dd-agent,zendesk/dd-agent,AniruddhaSAtre/dd-agent,darron/dd-agent,citrusleaf/dd-agent,oneandoneis2/dd-agent,tebriel/dd-agent,packetloop/dd-agent,a20012251/dd-agent,Wattpad/dd-agent,jyogi/purvar-agent,jamesandariese/dd-agent,jamesandariese/dd-agent,JohnLZeller/dd-agent,relateiq/dd-agent,pfmooney/dd-agent,indeedops/dd-agent,jvassev/dd-agent,PagerDuty/dd-agent,brettlangdon/dd-agent,darron/dd-agent,Wattpad/dd-agent,remh/dd-agent,eeroniemi/dd-agent,c960657/dd-agent,GabrielNicolasAvellaneda/dd-agent,gphat/dd-agent,tebriel/dd-agent,guruxu/dd-agent,brettlangdon/dd-agent,benmccann/dd-agent,takus/dd-agent,remh/dd-agent,Mashape/dd-agent,manolama/dd-agent,JohnLZeller/dd-agent,JohnLZeller/dd-agent,takus/dd-agent,truthbk/dd-agent,pfmooney/dd-agent,polynomial/dd-agent,citrusleaf/dd-agent,yuecong/dd-agent,cberry777/dd-agent,c960657/dd-agent,urosgruber/dd-agent,manolama/dd-agent,AntoCard/powerdns-recursor_check,jyogi/purvar-agent,Wattpad/dd-agent,GabrielNicolasAvellaneda/dd-agent,remh/dd-agent,jyogi/purvar-agent,pmav99/praktoras,jyogi/purvar-agent,cberry777/dd-agent,mderomph-coolblue/dd-agent,lookout/dd-agent,benmccann/dd-agent,polynomial/dd-agent,amalakar/dd-agent,huhongbo/dd-agent,joelvanvelden/dd-agent,packetloop/dd-agent,packetloop/dd-agent,GabrielNicolasAvellaneda/dd-agent,AntoCard/powerdns-recursor_check,guruxu/dd-agent,AniruddhaSAtre/dd-agent,c960657/dd-agent,cberry777/dd-agent,eeroniemi/dd-agent,joelvanvelden/dd-agent,Wattpad/dd-agent,jraede/dd-agent,lookout/dd-agent,Shopify/dd-agent
import unittest import logging logging.basicConfig() logger = logging.getLogger() from checks.db.mongo import MongoDb class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logger) def testCheck(self): r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals("opcounters" in r, False) r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals(r["asserts"]["regularPS"], 0) self.assertEquals(r["asserts"]["userPS"], 0) self.assertEquals(r["opcounters"]["commandPS"], (244 - 18) / (10191 - 2893)) if __name__ == '__main__': unittest.main() Test does start a mongo instance.
import unittest import logging logging.basicConfig() import subprocess from tempfile import mkdtemp from checks.db.mongo import MongoDb PORT1 = 27017 PORT2 = 37017 class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logging.getLogger()) # Start 1 instances of Mongo dir1 = mkdtemp() self.p1 = subprocess.Popen(["mongod", "--dbpath", dir1, "--port", str(PORT1)], executable="mongod", stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): if self.p1 is not None: self.p1.terminate() def testCheck(self): if self.p1 is not None: r = self.c.check({"MongoDBServer": "localhost", "mongodb_port": PORT1}) self.assertEquals(r and r["connections"]["current"] == 1, True) assert r["connections"]["available"] >= 1 assert r["uptime"] >= 0, r assert r["mem"]["resident"] > 0 assert r["mem"]["virtual"] > 0 if __name__ == '__main__': unittest.main()
<commit_before>import unittest import logging logging.basicConfig() logger = logging.getLogger() from checks.db.mongo import MongoDb class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logger) def testCheck(self): r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals("opcounters" in r, False) r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals(r["asserts"]["regularPS"], 0) self.assertEquals(r["asserts"]["userPS"], 0) self.assertEquals(r["opcounters"]["commandPS"], (244 - 18) / (10191 - 2893)) if __name__ == '__main__': unittest.main() <commit_msg>Test does start a mongo instance.<commit_after>
import unittest import logging logging.basicConfig() import subprocess from tempfile import mkdtemp from checks.db.mongo import MongoDb PORT1 = 27017 PORT2 = 37017 class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logging.getLogger()) # Start 1 instances of Mongo dir1 = mkdtemp() self.p1 = subprocess.Popen(["mongod", "--dbpath", dir1, "--port", str(PORT1)], executable="mongod", stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): if self.p1 is not None: self.p1.terminate() def testCheck(self): if self.p1 is not None: r = self.c.check({"MongoDBServer": "localhost", "mongodb_port": PORT1}) self.assertEquals(r and r["connections"]["current"] == 1, True) assert r["connections"]["available"] >= 1 assert r["uptime"] >= 0, r assert r["mem"]["resident"] > 0 assert r["mem"]["virtual"] > 0 if __name__ == '__main__': unittest.main()
import unittest import logging logging.basicConfig() logger = logging.getLogger() from checks.db.mongo import MongoDb class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logger) def testCheck(self): r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals("opcounters" in r, False) r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals(r["asserts"]["regularPS"], 0) self.assertEquals(r["asserts"]["userPS"], 0) self.assertEquals(r["opcounters"]["commandPS"], (244 - 18) / (10191 - 2893)) if __name__ == '__main__': unittest.main() Test does start a mongo instance.import unittest import logging logging.basicConfig() import subprocess from tempfile import mkdtemp from checks.db.mongo import MongoDb PORT1 = 27017 PORT2 = 37017 class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logging.getLogger()) # Start 1 instances of Mongo dir1 = mkdtemp() self.p1 = subprocess.Popen(["mongod", "--dbpath", dir1, "--port", str(PORT1)], executable="mongod", stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): if self.p1 is not None: self.p1.terminate() def testCheck(self): if self.p1 is not None: r = self.c.check({"MongoDBServer": "localhost", "mongodb_port": PORT1}) self.assertEquals(r and r["connections"]["current"] == 1, True) assert r["connections"]["available"] >= 1 assert r["uptime"] >= 0, r assert r["mem"]["resident"] > 0 assert r["mem"]["virtual"] > 0 if __name__ == '__main__': unittest.main()
<commit_before>import unittest import logging logging.basicConfig() logger = logging.getLogger() from checks.db.mongo import MongoDb class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logger) def testCheck(self): r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals("opcounters" in r, False) r = self.c.check({"MongoDBServer": "blah"}) self.assertEquals(r["connections"]["current"], 1) self.assertEquals(r["asserts"]["regularPS"], 0) self.assertEquals(r["asserts"]["userPS"], 0) self.assertEquals(r["opcounters"]["commandPS"], (244 - 18) / (10191 - 2893)) if __name__ == '__main__': unittest.main() <commit_msg>Test does start a mongo instance.<commit_after>import unittest import logging logging.basicConfig() import subprocess from tempfile import mkdtemp from checks.db.mongo import MongoDb PORT1 = 27017 PORT2 = 37017 class TestMongo(unittest.TestCase): def setUp(self): self.c = MongoDb(logging.getLogger()) # Start 1 instances of Mongo dir1 = mkdtemp() self.p1 = subprocess.Popen(["mongod", "--dbpath", dir1, "--port", str(PORT1)], executable="mongod", stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): if self.p1 is not None: self.p1.terminate() def testCheck(self): if self.p1 is not None: r = self.c.check({"MongoDBServer": "localhost", "mongodb_port": PORT1}) self.assertEquals(r and r["connections"]["current"] == 1, True) assert r["connections"]["available"] >= 1 assert r["uptime"] >= 0, r assert r["mem"]["resident"] > 0 assert r["mem"]["virtual"] > 0 if __name__ == '__main__': unittest.main()
31c60902c7e09fd01b6b89550df342e5431de961
mysite/profile/search_indexes.py
mysite/profile/search_indexes.py
import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() def prepare_null_document(self, person_instance): return '' # lollerskates def prepare_all_tag_texts(self, person_instance): return person_instance.get_tag_texts_for_map() def get_queryset(self): everybody = mysite.profile.models.Person.objects.all() mappable_filter = ( ~Q(location_display_name='') & Q(location_confirmed=True) ) return everybody.filter(mappable_filter) site.register(mysite.profile.models.Person, PersonIndex)
import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() all_public_projects_exact = indexes.MultiValueField() def prepare_null_document(self, person_instance): return '' # lollerskates def prepare_all_tag_texts(self, person_instance): return person_instance.get_tag_texts_for_map() def prepare_all_public_projects_exact(self, person_instance): return list(person_instance.get_list_of_project_names()) def get_queryset(self): everybody = mysite.profile.models.Person.objects.all() mappable_filter = ( ~Q(location_display_name='') & Q(location_confirmed=True) ) return everybody.filter(mappable_filter) site.register(mysite.profile.models.Person, PersonIndex)
Add a column in the search index for the list of projects.
Add a column in the search index for the list of projects.
Python
agpl-3.0
SnappleCap/oh-mainline,campbe13/openhatch,SnappleCap/oh-mainline,mzdaniel/oh-mainline,nirmeshk/oh-mainline,onceuponatimeforever/oh-mainline,sudheesh001/oh-mainline,heeraj123/oh-mainline,onceuponatimeforever/oh-mainline,sudheesh001/oh-mainline,vipul-sharma20/oh-mainline,heeraj123/oh-mainline,openhatch/oh-mainline,willingc/oh-mainline,campbe13/openhatch,willingc/oh-mainline,waseem18/oh-mainline,SnappleCap/oh-mainline,moijes12/oh-mainline,Changaco/oh-mainline,sudheesh001/oh-mainline,ojengwa/oh-mainline,sudheesh001/oh-mainline,vipul-sharma20/oh-mainline,eeshangarg/oh-mainline,vipul-sharma20/oh-mainline,vipul-sharma20/oh-mainline,eeshangarg/oh-mainline,moijes12/oh-mainline,waseem18/oh-mainline,waseem18/oh-mainline,waseem18/oh-mainline,ojengwa/oh-mainline,willingc/oh-mainline,ehashman/oh-mainline,ojengwa/oh-mainline,onceuponatimeforever/oh-mainline,jledbetter/openhatch,onceuponatimeforever/oh-mainline,mzdaniel/oh-mainline,eeshangarg/oh-mainline,onceuponatimeforever/oh-mainline,mzdaniel/oh-mainline,mzdaniel/oh-mainline,jledbetter/openhatch,nirmeshk/oh-mainline,campbe13/openhatch,heeraj123/oh-mainline,mzdaniel/oh-mainline,nirmeshk/oh-mainline,Changaco/oh-mainline,campbe13/openhatch,eeshangarg/oh-mainline,mzdaniel/oh-mainline,campbe13/openhatch,ehashman/oh-mainline,heeraj123/oh-mainline,ehashman/oh-mainline,willingc/oh-mainline,jledbetter/openhatch,openhatch/oh-mainline,moijes12/oh-mainline,jledbetter/openhatch,willingc/oh-mainline,moijes12/oh-mainline,moijes12/oh-mainline,nirmeshk/oh-mainline,ojengwa/oh-mainline,waseem18/oh-mainline,SnappleCap/oh-mainline,eeshangarg/oh-mainline,heeraj123/oh-mainline,Changaco/oh-mainline,vipul-sharma20/oh-mainline,openhatch/oh-mainline,ehashman/oh-mainline,ojengwa/oh-mainline,Changaco/oh-mainline,jledbetter/openhatch,ehashman/oh-mainline,openhatch/oh-mainline,sudheesh001/oh-mainline,mzdaniel/oh-mainline,nirmeshk/oh-mainline,openhatch/oh-mainline,SnappleCap/oh-mainline,Changaco/oh-mainline
import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() def prepare_null_document(self, person_instance): return '' # lollerskates def prepare_all_tag_texts(self, person_instance): return person_instance.get_tag_texts_for_map() def get_queryset(self): everybody = mysite.profile.models.Person.objects.all() mappable_filter = ( ~Q(location_display_name='') & Q(location_confirmed=True) ) return everybody.filter(mappable_filter) site.register(mysite.profile.models.Person, PersonIndex) Add a column in the search index for the list of projects.
import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() all_public_projects_exact = indexes.MultiValueField() def prepare_null_document(self, person_instance): return '' # lollerskates def prepare_all_tag_texts(self, person_instance): return person_instance.get_tag_texts_for_map() def prepare_all_public_projects_exact(self, person_instance): return list(person_instance.get_list_of_project_names()) def get_queryset(self): everybody = mysite.profile.models.Person.objects.all() mappable_filter = ( ~Q(location_display_name='') & Q(location_confirmed=True) ) return everybody.filter(mappable_filter) site.register(mysite.profile.models.Person, PersonIndex)
<commit_before>import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() def prepare_null_document(self, person_instance): return '' # lollerskates def prepare_all_tag_texts(self, person_instance): return person_instance.get_tag_texts_for_map() def get_queryset(self): everybody = mysite.profile.models.Person.objects.all() mappable_filter = ( ~Q(location_display_name='') & Q(location_confirmed=True) ) return everybody.filter(mappable_filter) site.register(mysite.profile.models.Person, PersonIndex) <commit_msg>Add a column in the search index for the list of projects.<commit_after>
import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() all_public_projects_exact = indexes.MultiValueField() def prepare_null_document(self, person_instance): return '' # lollerskates def prepare_all_tag_texts(self, person_instance): return person_instance.get_tag_texts_for_map() def prepare_all_public_projects_exact(self, person_instance): return list(person_instance.get_list_of_project_names()) def get_queryset(self): everybody = mysite.profile.models.Person.objects.all() mappable_filter = ( ~Q(location_display_name='') & Q(location_confirmed=True) ) return everybody.filter(mappable_filter) site.register(mysite.profile.models.Person, PersonIndex)
import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() def prepare_null_document(self, person_instance): return '' # lollerskates def prepare_all_tag_texts(self, person_instance): return person_instance.get_tag_texts_for_map() def get_queryset(self): everybody = mysite.profile.models.Person.objects.all() mappable_filter = ( ~Q(location_display_name='') & Q(location_confirmed=True) ) return everybody.filter(mappable_filter) site.register(mysite.profile.models.Person, PersonIndex) Add a column in the search index for the list of projects.import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() all_public_projects_exact = indexes.MultiValueField() def prepare_null_document(self, person_instance): return '' # lollerskates def prepare_all_tag_texts(self, person_instance): return person_instance.get_tag_texts_for_map() def prepare_all_public_projects_exact(self, person_instance): return list(person_instance.get_list_of_project_names()) def get_queryset(self): everybody = mysite.profile.models.Person.objects.all() mappable_filter = ( ~Q(location_display_name='') & Q(location_confirmed=True) ) return everybody.filter(mappable_filter) site.register(mysite.profile.models.Person, PersonIndex)
<commit_before>import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() def prepare_null_document(self, person_instance): return '' # lollerskates def prepare_all_tag_texts(self, person_instance): return person_instance.get_tag_texts_for_map() def get_queryset(self): everybody = mysite.profile.models.Person.objects.all() mappable_filter = ( ~Q(location_display_name='') & Q(location_confirmed=True) ) return everybody.filter(mappable_filter) site.register(mysite.profile.models.Person, PersonIndex) <commit_msg>Add a column in the search index for the list of projects.<commit_after>import datetime from haystack import indexes from haystack import site import mysite.profile.models from django.db.models import Q class PersonIndex(indexes.SearchIndex): null_document = indexes.CharField(document=True) all_tag_texts = indexes.MultiValueField() all_public_projects_exact = indexes.MultiValueField() def prepare_null_document(self, person_instance): return '' # lollerskates def prepare_all_tag_texts(self, person_instance): return person_instance.get_tag_texts_for_map() def prepare_all_public_projects_exact(self, person_instance): return list(person_instance.get_list_of_project_names()) def get_queryset(self): everybody = mysite.profile.models.Person.objects.all() mappable_filter = ( ~Q(location_display_name='') & Q(location_confirmed=True) ) return everybody.filter(mappable_filter) site.register(mysite.profile.models.Person, PersonIndex)
d2bec26a63877e31e2d887e0879a8fd197741147
thinc/t2t.py
thinc/t2t.py
# coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401
# coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401 from .neural._classes.multiheaded_attention import MultiHeadedAttention from .neural._classes.multiheaded_attention import prepare_self_attention
Add import links for MultiHeadedAttention and prepare_self_attention
Add import links for MultiHeadedAttention and prepare_self_attention
Python
mit
spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc
# coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401 Add import links for MultiHeadedAttention and prepare_self_attention
# coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401 from .neural._classes.multiheaded_attention import MultiHeadedAttention from .neural._classes.multiheaded_attention import prepare_self_attention
<commit_before># coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401 <commit_msg>Add import links for MultiHeadedAttention and prepare_self_attention<commit_after>
# coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401 from .neural._classes.multiheaded_attention import MultiHeadedAttention from .neural._classes.multiheaded_attention import prepare_self_attention
# coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401 Add import links for MultiHeadedAttention and prepare_self_attention# coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401 from .neural._classes.multiheaded_attention import MultiHeadedAttention from .neural._classes.multiheaded_attention import prepare_self_attention
<commit_before># coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401 <commit_msg>Add import links for MultiHeadedAttention and prepare_self_attention<commit_after># coding: utf8 from __future__ import unicode_literals from .neural._classes.convolution import ExtractWindow # noqa: F401 from .neural._classes.attention import ParametricAttention # noqa: F401 from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401 from .neural._classes.multiheaded_attention import MultiHeadedAttention from .neural._classes.multiheaded_attention import prepare_self_attention
830ac1f89950c34a6f691d2a55b5e0044861066c
neuroimaging/testing/__init__.py
neuroimaging/testing/__init__.py
"""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy-data-suite to be created later and downloaded separately. Examples -------- >>> from neuroimaging.testing import funcfile >>> from neuroimaging.core.image import image >>> img = image.load(funcfile) >>> img.shape (20, 2, 20, 20) Notes ----- BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder until we build a proper anatomical test image. """ import os #__all__ = ['funcfile', 'anatfile'] # Discover directory path filepath = os.path.abspath(__file__) basedir = os.path.dirname(filepath) funcfile = os.path.join(basedir, 'functional.nii.gz') anatfile = os.path.join(basedir, 'anatomical.nii.gz') from numpy.testing import * import decorators as dec
"""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy-data-suite to be created later and downloaded separately. Examples -------- >>> from neuroimaging.testing import funcfile >>> from neuroimaging.core.image import image >>> img = image.load(funcfile) >>> img.shape (20, 2, 20, 20) Notes ----- BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder until we build a proper anatomical test image. """ import os #__all__ = ['funcfile', 'anatfile'] # Discover directory path filepath = os.path.abspath(__file__) basedir = os.path.dirname(filepath) funcfile = os.path.join(basedir, 'functional.nii.gz') anatfile = os.path.join(basedir, 'anatomical.nii.gz') from numpy.testing import * import decorators as dec from nose.tools import assert_true, assert_false
Add some nose.tools to testing imports.
Add some nose.tools to testing imports.
Python
bsd-3-clause
yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD
"""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy-data-suite to be created later and downloaded separately. Examples -------- >>> from neuroimaging.testing import funcfile >>> from neuroimaging.core.image import image >>> img = image.load(funcfile) >>> img.shape (20, 2, 20, 20) Notes ----- BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder until we build a proper anatomical test image. """ import os #__all__ = ['funcfile', 'anatfile'] # Discover directory path filepath = os.path.abspath(__file__) basedir = os.path.dirname(filepath) funcfile = os.path.join(basedir, 'functional.nii.gz') anatfile = os.path.join(basedir, 'anatomical.nii.gz') from numpy.testing import * import decorators as dec Add some nose.tools to testing imports.
"""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy-data-suite to be created later and downloaded separately. Examples -------- >>> from neuroimaging.testing import funcfile >>> from neuroimaging.core.image import image >>> img = image.load(funcfile) >>> img.shape (20, 2, 20, 20) Notes ----- BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder until we build a proper anatomical test image. """ import os #__all__ = ['funcfile', 'anatfile'] # Discover directory path filepath = os.path.abspath(__file__) basedir = os.path.dirname(filepath) funcfile = os.path.join(basedir, 'functional.nii.gz') anatfile = os.path.join(basedir, 'anatomical.nii.gz') from numpy.testing import * import decorators as dec from nose.tools import assert_true, assert_false
<commit_before>"""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy-data-suite to be created later and downloaded separately. Examples -------- >>> from neuroimaging.testing import funcfile >>> from neuroimaging.core.image import image >>> img = image.load(funcfile) >>> img.shape (20, 2, 20, 20) Notes ----- BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder until we build a proper anatomical test image. """ import os #__all__ = ['funcfile', 'anatfile'] # Discover directory path filepath = os.path.abspath(__file__) basedir = os.path.dirname(filepath) funcfile = os.path.join(basedir, 'functional.nii.gz') anatfile = os.path.join(basedir, 'anatomical.nii.gz') from numpy.testing import * import decorators as dec <commit_msg>Add some nose.tools to testing imports.<commit_after>
"""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy-data-suite to be created later and downloaded separately. Examples -------- >>> from neuroimaging.testing import funcfile >>> from neuroimaging.core.image import image >>> img = image.load(funcfile) >>> img.shape (20, 2, 20, 20) Notes ----- BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder until we build a proper anatomical test image. """ import os #__all__ = ['funcfile', 'anatfile'] # Discover directory path filepath = os.path.abspath(__file__) basedir = os.path.dirname(filepath) funcfile = os.path.join(basedir, 'functional.nii.gz') anatfile = os.path.join(basedir, 'anatomical.nii.gz') from numpy.testing import * import decorators as dec from nose.tools import assert_true, assert_false
"""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy-data-suite to be created later and downloaded separately. Examples -------- >>> from neuroimaging.testing import funcfile >>> from neuroimaging.core.image import image >>> img = image.load(funcfile) >>> img.shape (20, 2, 20, 20) Notes ----- BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder until we build a proper anatomical test image. """ import os #__all__ = ['funcfile', 'anatfile'] # Discover directory path filepath = os.path.abspath(__file__) basedir = os.path.dirname(filepath) funcfile = os.path.join(basedir, 'functional.nii.gz') anatfile = os.path.join(basedir, 'anatomical.nii.gz') from numpy.testing import * import decorators as dec Add some nose.tools to testing imports."""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy-data-suite to be created later and downloaded separately. Examples -------- >>> from neuroimaging.testing import funcfile >>> from neuroimaging.core.image import image >>> img = image.load(funcfile) >>> img.shape (20, 2, 20, 20) Notes ----- BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder until we build a proper anatomical test image. """ import os #__all__ = ['funcfile', 'anatfile'] # Discover directory path filepath = os.path.abspath(__file__) basedir = os.path.dirname(filepath) funcfile = os.path.join(basedir, 'functional.nii.gz') anatfile = os.path.join(basedir, 'anatomical.nii.gz') from numpy.testing import * import decorators as dec from nose.tools import assert_true, assert_false
<commit_before>"""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy-data-suite to be created later and downloaded separately. Examples -------- >>> from neuroimaging.testing import funcfile >>> from neuroimaging.core.image import image >>> img = image.load(funcfile) >>> img.shape (20, 2, 20, 20) Notes ----- BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder until we build a proper anatomical test image. """ import os #__all__ = ['funcfile', 'anatfile'] # Discover directory path filepath = os.path.abspath(__file__) basedir = os.path.dirname(filepath) funcfile = os.path.join(basedir, 'functional.nii.gz') anatfile = os.path.join(basedir, 'anatomical.nii.gz') from numpy.testing import * import decorators as dec <commit_msg>Add some nose.tools to testing imports.<commit_after>"""The testing directory contains a small set of imaging files to be used for doctests only. More thorough tests and example data will be stored in a nipy-data-suite to be created later and downloaded separately. Examples -------- >>> from neuroimaging.testing import funcfile >>> from neuroimaging.core.image import image >>> img = image.load(funcfile) >>> img.shape (20, 2, 20, 20) Notes ----- BUG: anatomical.nii.gz is a copy of functional.nii.gz. This is a place-holder until we build a proper anatomical test image. """ import os #__all__ = ['funcfile', 'anatfile'] # Discover directory path filepath = os.path.abspath(__file__) basedir = os.path.dirname(filepath) funcfile = os.path.join(basedir, 'functional.nii.gz') anatfile = os.path.join(basedir, 'anatomical.nii.gz') from numpy.testing import * import decorators as dec from nose.tools import assert_true, assert_false
310005d0e22b071c1b5ed69cdf2a38371f2f7ec5
cloudenvy/commands/envy_list.py
cloudenvy/commands/envy_list.py
from cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser #TODO(jakedahn): The way this works is just silly. This should be totally # refactored to use nova's server metadata attributes. def run(self, config, args): envy = Envy(config) envys = [] servers = envy.list_servers() for server in servers: if len(server.name.split(envy.name)) > 1: envys.append(str(server.name)) print "ENVys for your project: %s" % str(envys)
from cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser def run(self, config, args): envy = Envy(config) for server in envy.list_servers(): if server.name.startswith(envy.name): print server.name
Print out ENVys with newlines for envy list
Print out ENVys with newlines for envy list
Python
apache-2.0
cloudenvy/cloudenvy
from cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser #TODO(jakedahn): The way this works is just silly. This should be totally # refactored to use nova's server metadata attributes. def run(self, config, args): envy = Envy(config) envys = [] servers = envy.list_servers() for server in servers: if len(server.name.split(envy.name)) > 1: envys.append(str(server.name)) print "ENVys for your project: %s" % str(envys) Print out ENVys with newlines for envy list
from cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser def run(self, config, args): envy = Envy(config) for server in envy.list_servers(): if server.name.startswith(envy.name): print server.name
<commit_before>from cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser #TODO(jakedahn): The way this works is just silly. This should be totally # refactored to use nova's server metadata attributes. def run(self, config, args): envy = Envy(config) envys = [] servers = envy.list_servers() for server in servers: if len(server.name.split(envy.name)) > 1: envys.append(str(server.name)) print "ENVys for your project: %s" % str(envys) <commit_msg>Print out ENVys with newlines for envy list<commit_after>
from cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser def run(self, config, args): envy = Envy(config) for server in envy.list_servers(): if server.name.startswith(envy.name): print server.name
from cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser #TODO(jakedahn): The way this works is just silly. This should be totally # refactored to use nova's server metadata attributes. def run(self, config, args): envy = Envy(config) envys = [] servers = envy.list_servers() for server in servers: if len(server.name.split(envy.name)) > 1: envys.append(str(server.name)) print "ENVys for your project: %s" % str(envys) Print out ENVys with newlines for envy listfrom cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser def run(self, config, args): envy = Envy(config) for server in envy.list_servers(): if server.name.startswith(envy.name): print server.name
<commit_before>from cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser #TODO(jakedahn): The way this works is just silly. This should be totally # refactored to use nova's server metadata attributes. def run(self, config, args): envy = Envy(config) envys = [] servers = envy.list_servers() for server in servers: if len(server.name.split(envy.name)) > 1: envys.append(str(server.name)) print "ENVys for your project: %s" % str(envys) <commit_msg>Print out ENVys with newlines for envy list<commit_after>from cloudenvy.envy import Envy class EnvyList(object): """List all ENVys in context of your current project""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('list', help='list help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser def run(self, config, args): envy = Envy(config) for server in envy.list_servers(): if server.name.startswith(envy.name): print server.name
cb7170785af4bf853ff8495aaade520d3b133332
casexml/apps/stock/admin.py
casexml/apps/stock/admin.py
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] search_fields = ['form_id'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] search_fields = ['case_id', 'product_id'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
Add search fields to stock models
Add search fields to stock models
Python
bsd-3-clause
dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,SEL-Columbia/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin) Add search fields to stock models
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] search_fields = ['form_id'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] search_fields = ['case_id', 'product_id'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
<commit_before>from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin) <commit_msg>Add search fields to stock models<commit_after>
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] search_fields = ['form_id'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] search_fields = ['case_id', 'product_id'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin) Add search fields to stock modelsfrom django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] search_fields = ['form_id'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] search_fields = ['case_id', 'product_id'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
<commit_before>from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin) <commit_msg>Add search fields to stock models<commit_after>from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] search_fields = ['form_id'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] search_fields = ['case_id', 'product_id'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
1821577ca19bb05847c37d856896d8e1ce8b3acb
plugins/religion.py
plugins/religion.py
from util import hook, http @hook.command('god') @hook.command def bible(inp): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('http://www.esvapi.org/v2/rest/passageQuery?key=IP&' 'output-format=plain-text&include-heading-horizontal-lines&' 'include-headings=false&include-passage-horizontal-lines=false&' 'include-passage-references=false&include-short-copyright=false&' 'include-footnotes=false&line-length=0&' 'include-heading-horizontal-lines=false') text = http.get(base_url, passage=inp) text = ' '.join(text.split()) if len(text) > 400: text = text[:text.rfind(' ', 0, 400)] + '...' return text @hook.command('allah') @hook.command def koran(inp): # Koran look-up plugin by Ghetto Wizard ".koran <chapter.verse> -- gets <chapter.verse> from the Koran" url = 'http://quod.lib.umich.edu/cgi/k/koran/koran-idx?type=simple' results = http.get_html(url, q1=inp).xpath('//li') if not results: return 'No results for ' + inp return results[0].text_content()
from util import hook, http # https://api.esv.org/account/create-application/ @hook.api_key('bible') @hook.command('god') @hook.command def bible(inp, api_key=None): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('https://api.esv.org/v3/passage/text/?' 'include-headings=false&' 'include-passage-horizontal-lines=false&' 'include-heading-horizontal-lines=false&' 'include-passage-references=false&' 'include-short-copyright=false&' 'include-footnotes=false&' ) text = http.get_json(base_url, q=inp, headers={'Authorization': 'Token ' + api_key}) text = ' '.join(text['passages']).strip() if len(text) > 400: text = text[:text.rfind(' ', 0, 400)] + '...' return text @hook.command('allah') @hook.command def koran(inp): # Koran look-up plugin by Ghetto Wizard ".koran <chapter.verse> -- gets <chapter.verse> from the Koran" url = 'http://quod.lib.umich.edu/cgi/k/koran/koran-idx?type=simple' results = http.get_html(url, q1=inp).xpath('//li') if not results: return 'No results for ' + inp return results[0].text_content()
Fix .bible: v2 was deprecated, the v3 API requires a key.
Fix .bible: v2 was deprecated, the v3 API requires a key.
Python
unlicense
parkrrr/skybot,TeamPeggle/ppp-helpdesk,crisisking/skybot,jmgao/skybot,rmmh/skybot
from util import hook, http @hook.command('god') @hook.command def bible(inp): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('http://www.esvapi.org/v2/rest/passageQuery?key=IP&' 'output-format=plain-text&include-heading-horizontal-lines&' 'include-headings=false&include-passage-horizontal-lines=false&' 'include-passage-references=false&include-short-copyright=false&' 'include-footnotes=false&line-length=0&' 'include-heading-horizontal-lines=false') text = http.get(base_url, passage=inp) text = ' '.join(text.split()) if len(text) > 400: text = text[:text.rfind(' ', 0, 400)] + '...' return text @hook.command('allah') @hook.command def koran(inp): # Koran look-up plugin by Ghetto Wizard ".koran <chapter.verse> -- gets <chapter.verse> from the Koran" url = 'http://quod.lib.umich.edu/cgi/k/koran/koran-idx?type=simple' results = http.get_html(url, q1=inp).xpath('//li') if not results: return 'No results for ' + inp return results[0].text_content() Fix .bible: v2 was deprecated, the v3 API requires a key.
from util import hook, http # https://api.esv.org/account/create-application/ @hook.api_key('bible') @hook.command('god') @hook.command def bible(inp, api_key=None): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('https://api.esv.org/v3/passage/text/?' 'include-headings=false&' 'include-passage-horizontal-lines=false&' 'include-heading-horizontal-lines=false&' 'include-passage-references=false&' 'include-short-copyright=false&' 'include-footnotes=false&' ) text = http.get_json(base_url, q=inp, headers={'Authorization': 'Token ' + api_key}) text = ' '.join(text['passages']).strip() if len(text) > 400: text = text[:text.rfind(' ', 0, 400)] + '...' return text @hook.command('allah') @hook.command def koran(inp): # Koran look-up plugin by Ghetto Wizard ".koran <chapter.verse> -- gets <chapter.verse> from the Koran" url = 'http://quod.lib.umich.edu/cgi/k/koran/koran-idx?type=simple' results = http.get_html(url, q1=inp).xpath('//li') if not results: return 'No results for ' + inp return results[0].text_content()
<commit_before>from util import hook, http @hook.command('god') @hook.command def bible(inp): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('http://www.esvapi.org/v2/rest/passageQuery?key=IP&' 'output-format=plain-text&include-heading-horizontal-lines&' 'include-headings=false&include-passage-horizontal-lines=false&' 'include-passage-references=false&include-short-copyright=false&' 'include-footnotes=false&line-length=0&' 'include-heading-horizontal-lines=false') text = http.get(base_url, passage=inp) text = ' '.join(text.split()) if len(text) > 400: text = text[:text.rfind(' ', 0, 400)] + '...' return text @hook.command('allah') @hook.command def koran(inp): # Koran look-up plugin by Ghetto Wizard ".koran <chapter.verse> -- gets <chapter.verse> from the Koran" url = 'http://quod.lib.umich.edu/cgi/k/koran/koran-idx?type=simple' results = http.get_html(url, q1=inp).xpath('//li') if not results: return 'No results for ' + inp return results[0].text_content() <commit_msg>Fix .bible: v2 was deprecated, the v3 API requires a key.<commit_after>
from util import hook, http # https://api.esv.org/account/create-application/ @hook.api_key('bible') @hook.command('god') @hook.command def bible(inp, api_key=None): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('https://api.esv.org/v3/passage/text/?' 'include-headings=false&' 'include-passage-horizontal-lines=false&' 'include-heading-horizontal-lines=false&' 'include-passage-references=false&' 'include-short-copyright=false&' 'include-footnotes=false&' ) text = http.get_json(base_url, q=inp, headers={'Authorization': 'Token ' + api_key}) text = ' '.join(text['passages']).strip() if len(text) > 400: text = text[:text.rfind(' ', 0, 400)] + '...' return text @hook.command('allah') @hook.command def koran(inp): # Koran look-up plugin by Ghetto Wizard ".koran <chapter.verse> -- gets <chapter.verse> from the Koran" url = 'http://quod.lib.umich.edu/cgi/k/koran/koran-idx?type=simple' results = http.get_html(url, q1=inp).xpath('//li') if not results: return 'No results for ' + inp return results[0].text_content()
from util import hook, http @hook.command('god') @hook.command def bible(inp): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('http://www.esvapi.org/v2/rest/passageQuery?key=IP&' 'output-format=plain-text&include-heading-horizontal-lines&' 'include-headings=false&include-passage-horizontal-lines=false&' 'include-passage-references=false&include-short-copyright=false&' 'include-footnotes=false&line-length=0&' 'include-heading-horizontal-lines=false') text = http.get(base_url, passage=inp) text = ' '.join(text.split()) if len(text) > 400: text = text[:text.rfind(' ', 0, 400)] + '...' return text @hook.command('allah') @hook.command def koran(inp): # Koran look-up plugin by Ghetto Wizard ".koran <chapter.verse> -- gets <chapter.verse> from the Koran" url = 'http://quod.lib.umich.edu/cgi/k/koran/koran-idx?type=simple' results = http.get_html(url, q1=inp).xpath('//li') if not results: return 'No results for ' + inp return results[0].text_content() Fix .bible: v2 was deprecated, the v3 API requires a key.from util import hook, http # https://api.esv.org/account/create-application/ @hook.api_key('bible') @hook.command('god') @hook.command def bible(inp, api_key=None): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('https://api.esv.org/v3/passage/text/?' 'include-headings=false&' 'include-passage-horizontal-lines=false&' 'include-heading-horizontal-lines=false&' 'include-passage-references=false&' 'include-short-copyright=false&' 'include-footnotes=false&' ) text = http.get_json(base_url, q=inp, headers={'Authorization': 'Token ' + api_key}) text = ' '.join(text['passages']).strip() if len(text) > 400: text = text[:text.rfind(' ', 0, 400)] + '...' return text @hook.command('allah') @hook.command def koran(inp): # Koran look-up plugin by Ghetto Wizard ".koran <chapter.verse> -- gets <chapter.verse> from the Koran" url = 'http://quod.lib.umich.edu/cgi/k/koran/koran-idx?type=simple' results = http.get_html(url, q1=inp).xpath('//li') if not results: return 'No results for ' + inp return results[0].text_content()
<commit_before>from util import hook, http @hook.command('god') @hook.command def bible(inp): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('http://www.esvapi.org/v2/rest/passageQuery?key=IP&' 'output-format=plain-text&include-heading-horizontal-lines&' 'include-headings=false&include-passage-horizontal-lines=false&' 'include-passage-references=false&include-short-copyright=false&' 'include-footnotes=false&line-length=0&' 'include-heading-horizontal-lines=false') text = http.get(base_url, passage=inp) text = ' '.join(text.split()) if len(text) > 400: text = text[:text.rfind(' ', 0, 400)] + '...' return text @hook.command('allah') @hook.command def koran(inp): # Koran look-up plugin by Ghetto Wizard ".koran <chapter.verse> -- gets <chapter.verse> from the Koran" url = 'http://quod.lib.umich.edu/cgi/k/koran/koran-idx?type=simple' results = http.get_html(url, q1=inp).xpath('//li') if not results: return 'No results for ' + inp return results[0].text_content() <commit_msg>Fix .bible: v2 was deprecated, the v3 API requires a key.<commit_after>from util import hook, http # https://api.esv.org/account/create-application/ @hook.api_key('bible') @hook.command('god') @hook.command def bible(inp, api_key=None): ".bible <passage> -- gets <passage> from the Bible (ESV)" base_url = ('https://api.esv.org/v3/passage/text/?' 'include-headings=false&' 'include-passage-horizontal-lines=false&' 'include-heading-horizontal-lines=false&' 'include-passage-references=false&' 'include-short-copyright=false&' 'include-footnotes=false&' ) text = http.get_json(base_url, q=inp, headers={'Authorization': 'Token ' + api_key}) text = ' '.join(text['passages']).strip() if len(text) > 400: text = text[:text.rfind(' ', 0, 400)] + '...' return text @hook.command('allah') @hook.command def koran(inp): # Koran look-up plugin by Ghetto Wizard ".koran <chapter.verse> -- gets <chapter.verse> from the Koran" url = 'http://quod.lib.umich.edu/cgi/k/koran/koran-idx?type=simple' results = http.get_html(url, q1=inp).xpath('//li') if not results: return 'No results for ' + inp return results[0].text_content()
3496efef40acc9e204ea9d3129b974ac3e482ca2
direnaj/direnaj_api/celery_app/server_endpoint.py
direnaj/direnaj_api/celery_app/server_endpoint.py
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) @app_object.task def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()
Fix for periodic task scheduler (3)
Fix for periodic task scheduler (3)
Python
mit
boun-cmpe-soslab/drenaj,boun-cmpe-soslab/drenaj,boun-cmpe-soslab/drenaj,boun-cmpe-soslab/drenaj
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()Fix for periodic task scheduler (3)
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) @app_object.task def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()
<commit_before>__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()<commit_msg>Fix for periodic task scheduler (3)<commit_after>
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) @app_object.task def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()
__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()Fix for periodic task scheduler (3)__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) @app_object.task def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()
<commit_before>__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()<commit_msg>Fix for periodic task scheduler (3)<commit_after>__author__ = 'onur' from celery import Celery import direnaj_api.config.server_celeryconfig as celeryconfig app_object = Celery() app_object.config_from_object(celeryconfig) @app_object.task def deneme(x, seconds): print "Sleeping for printing %s for %s seconds.." % (x, seconds) import time time.sleep(seconds) print x #from celery.schedules import crontab #from celery.task import periodic_task from direnaj_api.utils.direnajmongomanager import create_batch_from_watchlist #@periodic_task(run_every=crontab(minute='*/1')) @app_object.task def check_watchlist_and_dispatch_tasks(): batch_size = 10 res_array = create_batch_from_watchlist(app_object, batch_size) if __name__ == "__main__": app_object.start()
9166d51badaca7502638b630b4d0457aaee66142
django_cache_manager/models.py
django_cache_manager/models.py
# -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .backends.sharing.types import ModelCacheInfo from .backends.sharing import sharing_backend from .cache_manager import CacheManager """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when a model does not use manager provide by django-cache-manager. For Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) if type(sender.objects) == CacheManager: logger.info('Ignoring post_save/post_delete signal from sender {0} as model manager is CachingManager'.format(sender)) return model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) sharing_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate)
# -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .model_cache_sharing.types import ModelCacheInfo from .model_cache_sharing import model_cache_backend """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when an update or delete happens on the model. For compatibility with Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) model_cache_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate)
Update to use signals as use_for_related_fields does not work for all cases
Update to use signals as use_for_related_fields does not work for all cases
Python
mit
vijaykatam/django-cache-manager
# -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .backends.sharing.types import ModelCacheInfo from .backends.sharing import sharing_backend from .cache_manager import CacheManager """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when a model does not use manager provide by django-cache-manager. For Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) if type(sender.objects) == CacheManager: logger.info('Ignoring post_save/post_delete signal from sender {0} as model manager is CachingManager'.format(sender)) return model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) sharing_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate) Update to use signals as use_for_related_fields does not work for all cases
# -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .model_cache_sharing.types import ModelCacheInfo from .model_cache_sharing import model_cache_backend """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when an update or delete happens on the model. For compatibility with Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) model_cache_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate)
<commit_before># -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .backends.sharing.types import ModelCacheInfo from .backends.sharing import sharing_backend from .cache_manager import CacheManager """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when a model does not use manager provide by django-cache-manager. For Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) if type(sender.objects) == CacheManager: logger.info('Ignoring post_save/post_delete signal from sender {0} as model manager is CachingManager'.format(sender)) return model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) sharing_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate) <commit_msg>Update to use signals as use_for_related_fields does not work for all cases<commit_after>
# -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .model_cache_sharing.types import ModelCacheInfo from .model_cache_sharing import model_cache_backend """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when an update or delete happens on the model. For compatibility with Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) model_cache_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate)
# -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .backends.sharing.types import ModelCacheInfo from .backends.sharing import sharing_backend from .cache_manager import CacheManager """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when a model does not use manager provide by django-cache-manager. For Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) if type(sender.objects) == CacheManager: logger.info('Ignoring post_save/post_delete signal from sender {0} as model manager is CachingManager'.format(sender)) return model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) sharing_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate) Update to use signals as use_for_related_fields does not work for all cases# -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .model_cache_sharing.types import ModelCacheInfo from .model_cache_sharing import model_cache_backend """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when an update or delete happens on the model. For compatibility with Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) model_cache_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate)
<commit_before># -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .backends.sharing.types import ModelCacheInfo from .backends.sharing import sharing_backend from .cache_manager import CacheManager """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when a model does not use manager provide by django-cache-manager. For Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) if type(sender.objects) == CacheManager: logger.info('Ignoring post_save/post_delete signal from sender {0} as model manager is CachingManager'.format(sender)) return model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) sharing_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate) <commit_msg>Update to use signals as use_for_related_fields does not work for all cases<commit_after># -*- coding: utf-8 -*- import logging import uuid from django.db.models.signals import post_save, post_delete from .model_cache_sharing.types import ModelCacheInfo from .model_cache_sharing import model_cache_backend """ Signal receivers for django model post_save and post_delete. Used to evict a model cache when an update or delete happens on the model. For compatibility with Django 1.5 these receivers live in models.py """ logger = logging.getLogger(__name__) def _invalidate(sender, instance, **kwargs): "Signal receiver for models" logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) model_cache_info = ModelCacheInfo(sender._meta.db_table, uuid.uuid4().hex) model_cache_backend.broadcast_model_cache_info(model_cache_info) post_save.connect(_invalidate) post_delete.connect(_invalidate)
b3f2735923e48958d238e3e20c86ce3090a5eea0
app.py
app.py
from flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml app = Flask(__name__) load_dotenv(find_dotenv()) @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): return 'Echo: ' + message if __name__ == '__main__': app.run(debug=True)
from flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml app = Flask(__name__) load_dotenv(find_dotenv()) directions = ['forward', 'backward'] @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): if message.lower() in directions: return message.lower() try: degree = float(message) except ValueError as e: return 'Invalid command' return str(degree) if __name__ == '__main__': app.run(debug=True)
Add handling for basic twitch controls
Add handling for basic twitch controls
Python
mit
tforrest/twilio-plays-roomba-flask
from flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml app = Flask(__name__) load_dotenv(find_dotenv()) @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): return 'Echo: ' + message if __name__ == '__main__': app.run(debug=True)Add handling for basic twitch controls
from flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml app = Flask(__name__) load_dotenv(find_dotenv()) directions = ['forward', 'backward'] @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): if message.lower() in directions: return message.lower() try: degree = float(message) except ValueError as e: return 'Invalid command' return str(degree) if __name__ == '__main__': app.run(debug=True)
<commit_before>from flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml app = Flask(__name__) load_dotenv(find_dotenv()) @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): return 'Echo: ' + message if __name__ == '__main__': app.run(debug=True)<commit_msg>Add handling for basic twitch controls<commit_after>
from flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml app = Flask(__name__) load_dotenv(find_dotenv()) directions = ['forward', 'backward'] @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): if message.lower() in directions: return message.lower() try: degree = float(message) except ValueError as e: return 'Invalid command' return str(degree) if __name__ == '__main__': app.run(debug=True)
from flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml app = Flask(__name__) load_dotenv(find_dotenv()) @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): return 'Echo: ' + message if __name__ == '__main__': app.run(debug=True)Add handling for basic twitch controlsfrom flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml app = Flask(__name__) load_dotenv(find_dotenv()) directions = ['forward', 'backward'] @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): if message.lower() in directions: return message.lower() try: degree = float(message) except ValueError as e: return 'Invalid command' return str(degree) if __name__ == '__main__': app.run(debug=True)
<commit_before>from flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml app = Flask(__name__) load_dotenv(find_dotenv()) @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): return 'Echo: ' + message if __name__ == '__main__': app.run(debug=True)<commit_msg>Add handling for basic twitch controls<commit_after>from flask import Flask, jsonify, request from dotenv import load_dotenv, find_dotenv from twilio import twiml app = Flask(__name__) load_dotenv(find_dotenv()) directions = ['forward', 'backward'] @app.route('/message', methods=['POST']) def roomba_command(): # twilio text message body = request.form['Body'] resp = handle_twilio_message(body) twilio_resp = twiml.Response() twilio_resp.message(resp) return str(twilio_resp) def handle_twilio_message(message): if message.lower() in directions: return message.lower() try: degree = float(message) except ValueError as e: return 'Invalid command' return str(degree) if __name__ == '__main__': app.run(debug=True)
9649b145bdb6177de203f575762d3ee9ca70d7e1
bot.py
bot.py
import praw import urllib r = praw.Reddit('/u/powderblock Glasses Bot') for post in r.get_subreddit('all').get_new(limit=5): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) urllib.urlretrieve(str(post.url), "image.jpg")
import praw import urllib import cv2, numpy as np DOWNSCALE = 2 r = praw.Reddit('/u/powderblock Glasses Bot') foundImage = False for post in r.get_subreddit('all').get_new(limit=15): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) foundImage = True break if foundImage: urllib.urlretrieve(str(post.url), "image.jpg") # load the image we want to detect features on frame = cv2.imread('image.jpg') minisize = (frame.shape[1]/DOWNSCALE,frame.shape[0]/DOWNSCALE) miniframe = cv2.resize(frame, minisize) cv2.imshow("Loading Images From a Buffer From a URL", miniframe) while True: # key handling (to close window) key = cv2.waitKey(20) if key in [27, ord('Q'), ord('q')]: # exit on ESC cv2.destroyWindow("Facial Features Test") break if not foundImage: print("No Image found.")
Save Image to File, Open Image if found
Save Image to File, Open Image if found Add image checking using urllib and opencv.
Python
mit
porglezomp/PyDankReddit,powderblock/DealWithItReddit,powderblock/PyDankReddit
import praw import urllib r = praw.Reddit('/u/powderblock Glasses Bot') for post in r.get_subreddit('all').get_new(limit=5): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) urllib.urlretrieve(str(post.url), "image.jpg") Save Image to File, Open Image if found Add image checking using urllib and opencv.
import praw import urllib import cv2, numpy as np DOWNSCALE = 2 r = praw.Reddit('/u/powderblock Glasses Bot') foundImage = False for post in r.get_subreddit('all').get_new(limit=15): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) foundImage = True break if foundImage: urllib.urlretrieve(str(post.url), "image.jpg") # load the image we want to detect features on frame = cv2.imread('image.jpg') minisize = (frame.shape[1]/DOWNSCALE,frame.shape[0]/DOWNSCALE) miniframe = cv2.resize(frame, minisize) cv2.imshow("Loading Images From a Buffer From a URL", miniframe) while True: # key handling (to close window) key = cv2.waitKey(20) if key in [27, ord('Q'), ord('q')]: # exit on ESC cv2.destroyWindow("Facial Features Test") break if not foundImage: print("No Image found.")
<commit_before>import praw import urllib r = praw.Reddit('/u/powderblock Glasses Bot') for post in r.get_subreddit('all').get_new(limit=5): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) urllib.urlretrieve(str(post.url), "image.jpg") <commit_msg>Save Image to File, Open Image if found Add image checking using urllib and opencv.<commit_after>
import praw import urllib import cv2, numpy as np DOWNSCALE = 2 r = praw.Reddit('/u/powderblock Glasses Bot') foundImage = False for post in r.get_subreddit('all').get_new(limit=15): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) foundImage = True break if foundImage: urllib.urlretrieve(str(post.url), "image.jpg") # load the image we want to detect features on frame = cv2.imread('image.jpg') minisize = (frame.shape[1]/DOWNSCALE,frame.shape[0]/DOWNSCALE) miniframe = cv2.resize(frame, minisize) cv2.imshow("Loading Images From a Buffer From a URL", miniframe) while True: # key handling (to close window) key = cv2.waitKey(20) if key in [27, ord('Q'), ord('q')]: # exit on ESC cv2.destroyWindow("Facial Features Test") break if not foundImage: print("No Image found.")
import praw import urllib r = praw.Reddit('/u/powderblock Glasses Bot') for post in r.get_subreddit('all').get_new(limit=5): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) urllib.urlretrieve(str(post.url), "image.jpg") Save Image to File, Open Image if found Add image checking using urllib and opencv.import praw import urllib import cv2, numpy as np DOWNSCALE = 2 r = praw.Reddit('/u/powderblock Glasses Bot') foundImage = False for post in r.get_subreddit('all').get_new(limit=15): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) foundImage = True break if foundImage: urllib.urlretrieve(str(post.url), "image.jpg") # load the image we want to detect features on frame = cv2.imread('image.jpg') minisize = (frame.shape[1]/DOWNSCALE,frame.shape[0]/DOWNSCALE) miniframe = cv2.resize(frame, minisize) cv2.imshow("Loading Images From a Buffer From a URL", miniframe) while True: # key handling (to close window) key = cv2.waitKey(20) if key in [27, ord('Q'), ord('q')]: # exit on ESC cv2.destroyWindow("Facial Features Test") break if not foundImage: print("No Image found.")
<commit_before>import praw import urllib r = praw.Reddit('/u/powderblock Glasses Bot') for post in r.get_subreddit('all').get_new(limit=5): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) urllib.urlretrieve(str(post.url), "image.jpg") <commit_msg>Save Image to File, Open Image if found Add image checking using urllib and opencv.<commit_after>import praw import urllib import cv2, numpy as np DOWNSCALE = 2 r = praw.Reddit('/u/powderblock Glasses Bot') foundImage = False for post in r.get_subreddit('all').get_new(limit=15): if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url): print str(post.url) foundImage = True break if foundImage: urllib.urlretrieve(str(post.url), "image.jpg") # load the image we want to detect features on frame = cv2.imread('image.jpg') minisize = (frame.shape[1]/DOWNSCALE,frame.shape[0]/DOWNSCALE) miniframe = cv2.resize(frame, minisize) cv2.imshow("Loading Images From a Buffer From a URL", miniframe) while True: # key handling (to close window) key = cv2.waitKey(20) if key in [27, ord('Q'), ord('q')]: # exit on ESC cv2.destroyWindow("Facial Features Test") break if not foundImage: print("No Image found.")
b73556be31864eca862618d6f0d5dd5d39c70677
lobster/cmssw/actions.py
lobster/cmssw/actions.py
import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): if 'plotdir' not in config: self.plotq = DummyQueue() else: logger.info('plots in {0} will be updated automatically'.format(config['plotdir'])) if 'foremen logs' in config: logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs']))) plotter = Plotter(config['workdir'], config['plotdir']) def plotf(q): while q.get() not in ('stop', None): plotter.make_plots(foremen=config.get('foremen logs')) self.plotq = multiprocessing.Queue() self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,)) self.plotp.start() logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid)) self.__last = datetime.datetime.now() def __del__(self): self.plotq.put('stop') def take(self): now = datetime.datetime.now() if (now - self.__last).seconds > 15 * 60: self.plotq.put('plot') self.__last = now
import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): if 'plotdir' not in config: self.plotq = DummyQueue() else: logger.info('plots in {0} will be updated automatically'.format(config['plotdir'])) if 'foremen logs' in config: logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs']))) plotter = Plotter(config, config['plotdir']) def plotf(q): while q.get() not in ('stop', None): plotter.make_plots(foremen=config.get('foremen logs')) self.plotq = multiprocessing.Queue() self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,)) self.plotp.start() logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid)) self.__last = datetime.datetime.now() def __del__(self): self.plotq.put('stop') def take(self): now = datetime.datetime.now() if (now - self.__last).seconds > 15 * 60: self.plotq.put('plot') self.__last = now
Fix overlooked use case for workdir.
Fix overlooked use case for workdir.
Python
mit
matz-e/lobster,matz-e/lobster,matz-e/lobster
import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): if 'plotdir' not in config: self.plotq = DummyQueue() else: logger.info('plots in {0} will be updated automatically'.format(config['plotdir'])) if 'foremen logs' in config: logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs']))) plotter = Plotter(config['workdir'], config['plotdir']) def plotf(q): while q.get() not in ('stop', None): plotter.make_plots(foremen=config.get('foremen logs')) self.plotq = multiprocessing.Queue() self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,)) self.plotp.start() logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid)) self.__last = datetime.datetime.now() def __del__(self): self.plotq.put('stop') def take(self): now = datetime.datetime.now() if (now - self.__last).seconds > 15 * 60: self.plotq.put('plot') self.__last = now Fix overlooked use case for workdir.
import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): if 'plotdir' not in config: self.plotq = DummyQueue() else: logger.info('plots in {0} will be updated automatically'.format(config['plotdir'])) if 'foremen logs' in config: logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs']))) plotter = Plotter(config, config['plotdir']) def plotf(q): while q.get() not in ('stop', None): plotter.make_plots(foremen=config.get('foremen logs')) self.plotq = multiprocessing.Queue() self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,)) self.plotp.start() logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid)) self.__last = datetime.datetime.now() def __del__(self): self.plotq.put('stop') def take(self): now = datetime.datetime.now() if (now - self.__last).seconds > 15 * 60: self.plotq.put('plot') self.__last = now
<commit_before>import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): if 'plotdir' not in config: self.plotq = DummyQueue() else: logger.info('plots in {0} will be updated automatically'.format(config['plotdir'])) if 'foremen logs' in config: logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs']))) plotter = Plotter(config['workdir'], config['plotdir']) def plotf(q): while q.get() not in ('stop', None): plotter.make_plots(foremen=config.get('foremen logs')) self.plotq = multiprocessing.Queue() self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,)) self.plotp.start() logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid)) self.__last = datetime.datetime.now() def __del__(self): self.plotq.put('stop') def take(self): now = datetime.datetime.now() if (now - self.__last).seconds > 15 * 60: self.plotq.put('plot') self.__last = now <commit_msg>Fix overlooked use case for workdir.<commit_after>
import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): if 'plotdir' not in config: self.plotq = DummyQueue() else: logger.info('plots in {0} will be updated automatically'.format(config['plotdir'])) if 'foremen logs' in config: logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs']))) plotter = Plotter(config, config['plotdir']) def plotf(q): while q.get() not in ('stop', None): plotter.make_plots(foremen=config.get('foremen logs')) self.plotq = multiprocessing.Queue() self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,)) self.plotp.start() logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid)) self.__last = datetime.datetime.now() def __del__(self): self.plotq.put('stop') def take(self): now = datetime.datetime.now() if (now - self.__last).seconds > 15 * 60: self.plotq.put('plot') self.__last = now
import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): if 'plotdir' not in config: self.plotq = DummyQueue() else: logger.info('plots in {0} will be updated automatically'.format(config['plotdir'])) if 'foremen logs' in config: logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs']))) plotter = Plotter(config['workdir'], config['plotdir']) def plotf(q): while q.get() not in ('stop', None): plotter.make_plots(foremen=config.get('foremen logs')) self.plotq = multiprocessing.Queue() self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,)) self.plotp.start() logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid)) self.__last = datetime.datetime.now() def __del__(self): self.plotq.put('stop') def take(self): now = datetime.datetime.now() if (now - self.__last).seconds > 15 * 60: self.plotq.put('plot') self.__last = now Fix overlooked use case for workdir.import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): if 'plotdir' not in config: self.plotq = DummyQueue() else: logger.info('plots in {0} will be updated automatically'.format(config['plotdir'])) if 'foremen logs' in config: logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs']))) plotter = Plotter(config, config['plotdir']) def plotf(q): while q.get() not in ('stop', None): plotter.make_plots(foremen=config.get('foremen logs')) self.plotq = multiprocessing.Queue() self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,)) self.plotp.start() logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid)) self.__last = datetime.datetime.now() def __del__(self): self.plotq.put('stop') def take(self): now = datetime.datetime.now() if (now - self.__last).seconds > 15 * 60: self.plotq.put('plot') self.__last = now
<commit_before>import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): if 'plotdir' not in config: self.plotq = DummyQueue() else: logger.info('plots in {0} will be updated automatically'.format(config['plotdir'])) if 'foremen logs' in config: logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs']))) plotter = Plotter(config['workdir'], config['plotdir']) def plotf(q): while q.get() not in ('stop', None): plotter.make_plots(foremen=config.get('foremen logs')) self.plotq = multiprocessing.Queue() self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,)) self.plotp.start() logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid)) self.__last = datetime.datetime.now() def __del__(self): self.plotq.put('stop') def take(self): now = datetime.datetime.now() if (now - self.__last).seconds > 15 * 60: self.plotq.put('plot') self.__last = now <commit_msg>Fix overlooked use case for workdir.<commit_after>import datetime import multiprocessing from lobster.cmssw.plotting import Plotter logger = multiprocessing.get_logger() class DummyQueue(object): def start(*args): pass def put(*args): pass def get(*args): return None class Actions(object): def __init__(self, config): if 'plotdir' not in config: self.plotq = DummyQueue() else: logger.info('plots in {0} will be updated automatically'.format(config['plotdir'])) if 'foremen logs' in config: logger.info('foremen logs will be included from: {0}'.format(', '.join(config['foremen logs']))) plotter = Plotter(config, config['plotdir']) def plotf(q): while q.get() not in ('stop', None): plotter.make_plots(foremen=config.get('foremen logs')) self.plotq = multiprocessing.Queue() self.plotp = multiprocessing.Process(target=plotf, args=(self.plotq,)) self.plotp.start() logger.info('spawning process for automatic plotting with pid {0}'.format(self.plotp.pid)) self.__last = datetime.datetime.now() def __del__(self): self.plotq.put('stop') def take(self): now = datetime.datetime.now() if (now - self.__last).seconds > 15 * 60: self.plotq.put('plot') self.__last = now
402035dd56261bce17a63b64bed810efdf14869e
exponent/substore.py
exponent/substore.py
from axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore under the given root store with the given path segments. """ storePath = rootStore.filesdir for segment in pathSegments: storePath = storePath.child(segment) withThisPath = substore.SubStore.storepath == storePath return rootStore.findUnique(substore.SubStore, withThisPath).open()
from axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore under the given root store with the given path segments. Raises ``axiom.errors.ItemNotFound`` if no such store exists. """ storePath = rootStore.filesdir for segment in pathSegments: storePath = storePath.child(segment) withThisPath = substore.SubStore.storepath == storePath return rootStore.findUnique(substore.SubStore, withThisPath).open()
Document exception raised when a store does not exist
Document exception raised when a store does not exist
Python
isc
lvh/exponent
from axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore under the given root store with the given path segments. """ storePath = rootStore.filesdir for segment in pathSegments: storePath = storePath.child(segment) withThisPath = substore.SubStore.storepath == storePath return rootStore.findUnique(substore.SubStore, withThisPath).open() Document exception raised when a store does not exist
from axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore under the given root store with the given path segments. Raises ``axiom.errors.ItemNotFound`` if no such store exists. """ storePath = rootStore.filesdir for segment in pathSegments: storePath = storePath.child(segment) withThisPath = substore.SubStore.storepath == storePath return rootStore.findUnique(substore.SubStore, withThisPath).open()
<commit_before>from axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore under the given root store with the given path segments. """ storePath = rootStore.filesdir for segment in pathSegments: storePath = storePath.child(segment) withThisPath = substore.SubStore.storepath == storePath return rootStore.findUnique(substore.SubStore, withThisPath).open() <commit_msg>Document exception raised when a store does not exist<commit_after>
from axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore under the given root store with the given path segments. Raises ``axiom.errors.ItemNotFound`` if no such store exists. """ storePath = rootStore.filesdir for segment in pathSegments: storePath = storePath.child(segment) withThisPath = substore.SubStore.storepath == storePath return rootStore.findUnique(substore.SubStore, withThisPath).open()
from axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore under the given root store with the given path segments. """ storePath = rootStore.filesdir for segment in pathSegments: storePath = storePath.child(segment) withThisPath = substore.SubStore.storepath == storePath return rootStore.findUnique(substore.SubStore, withThisPath).open() Document exception raised when a store does not existfrom axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore under the given root store with the given path segments. Raises ``axiom.errors.ItemNotFound`` if no such store exists. """ storePath = rootStore.filesdir for segment in pathSegments: storePath = storePath.child(segment) withThisPath = substore.SubStore.storepath == storePath return rootStore.findUnique(substore.SubStore, withThisPath).open()
<commit_before>from axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore under the given root store with the given path segments. """ storePath = rootStore.filesdir for segment in pathSegments: storePath = storePath.child(segment) withThisPath = substore.SubStore.storepath == storePath return rootStore.findUnique(substore.SubStore, withThisPath).open() <commit_msg>Document exception raised when a store does not exist<commit_after>from axiom import substore def createStore(rootStore, pathSegments): """ Creates amd returns substore under the given root store with the given path segments. """ return substore.SubStore.createNew(rootStore, pathSegments).open() def getStore(rootStore, pathSegments): """ Gets a substore under the given root store with the given path segments. Raises ``axiom.errors.ItemNotFound`` if no such store exists. """ storePath = rootStore.filesdir for segment in pathSegments: storePath = storePath.child(segment) withThisPath = substore.SubStore.storepath == storePath return rootStore.findUnique(substore.SubStore, withThisPath).open()
f622e11536c4ebf8f82985329d06efc58c2fe60e
blog/tests/test_views.py
blog/tests/test_views.py
from django.test import TestCase class BlogViewsTestCase(TestCase): def setUp(self):
from django import test from django.core.urlresolvers import reverse from blog.models import Post, Category class BlogViewsTestCase(test.TestCase): def setUp(self): # Add parent category and post category parent = Category(name='Writing', parent=None) parent.save() category = Category(name='Thoughts', parent=parent) category.save() # Create a draft _post = Post(title='Random thoughts of the author', body='Thoughts turned to words.', category=category) _post.save() self.draft = _post # Publish a post post = Post(title='New thoughts from without', body='A post fit to be published!', category=category) post.save() post.publish() self.post = post self.client = test.Client() def test_index(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) posts = response.context['posts'] self.assertNotIn(self.draft, posts) self.assertIn(self.post, posts) def test_post_view(self): post_url = reverse('blog:post', kwargs=dict(pid=self.post.id, slug=self.post.slug)) response = self.client.get(post_url) self.assertEqual(response.status_code, 200) post = response.context['post'] posts = response.context['posts'] self.assertEqual(post, self.post) self.assertEqual(posts.count(), 0) def test_draft_view(self): draft_url = reverse('blog:post', kwargs=dict(pid=self.draft.id, slug=self.draft.slug)) response = self.client.get(draft_url) self.assertEqual(response.status_code, 404)
Add tests for blog index view and post view
Add tests for blog index view and post view
Python
mit
ajoyoommen/weblog,ajoyoommen/weblog
from django.test import TestCase class BlogViewsTestCase(TestCase): def setUp(self): Add tests for blog index view and post view
from django import test from django.core.urlresolvers import reverse from blog.models import Post, Category class BlogViewsTestCase(test.TestCase): def setUp(self): # Add parent category and post category parent = Category(name='Writing', parent=None) parent.save() category = Category(name='Thoughts', parent=parent) category.save() # Create a draft _post = Post(title='Random thoughts of the author', body='Thoughts turned to words.', category=category) _post.save() self.draft = _post # Publish a post post = Post(title='New thoughts from without', body='A post fit to be published!', category=category) post.save() post.publish() self.post = post self.client = test.Client() def test_index(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) posts = response.context['posts'] self.assertNotIn(self.draft, posts) self.assertIn(self.post, posts) def test_post_view(self): post_url = reverse('blog:post', kwargs=dict(pid=self.post.id, slug=self.post.slug)) response = self.client.get(post_url) self.assertEqual(response.status_code, 200) post = response.context['post'] posts = response.context['posts'] self.assertEqual(post, self.post) self.assertEqual(posts.count(), 0) def test_draft_view(self): draft_url = reverse('blog:post', kwargs=dict(pid=self.draft.id, slug=self.draft.slug)) response = self.client.get(draft_url) self.assertEqual(response.status_code, 404)
<commit_before>from django.test import TestCase class BlogViewsTestCase(TestCase): def setUp(self): <commit_msg>Add tests for blog index view and post view<commit_after>
from django import test from django.core.urlresolvers import reverse from blog.models import Post, Category class BlogViewsTestCase(test.TestCase): def setUp(self): # Add parent category and post category parent = Category(name='Writing', parent=None) parent.save() category = Category(name='Thoughts', parent=parent) category.save() # Create a draft _post = Post(title='Random thoughts of the author', body='Thoughts turned to words.', category=category) _post.save() self.draft = _post # Publish a post post = Post(title='New thoughts from without', body='A post fit to be published!', category=category) post.save() post.publish() self.post = post self.client = test.Client() def test_index(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) posts = response.context['posts'] self.assertNotIn(self.draft, posts) self.assertIn(self.post, posts) def test_post_view(self): post_url = reverse('blog:post', kwargs=dict(pid=self.post.id, slug=self.post.slug)) response = self.client.get(post_url) self.assertEqual(response.status_code, 200) post = response.context['post'] posts = response.context['posts'] self.assertEqual(post, self.post) self.assertEqual(posts.count(), 0) def test_draft_view(self): draft_url = reverse('blog:post', kwargs=dict(pid=self.draft.id, slug=self.draft.slug)) response = self.client.get(draft_url) self.assertEqual(response.status_code, 404)
from django.test import TestCase class BlogViewsTestCase(TestCase): def setUp(self): Add tests for blog index view and post viewfrom django import test from django.core.urlresolvers import reverse from blog.models import Post, Category class BlogViewsTestCase(test.TestCase): def setUp(self): # Add parent category and post category parent = Category(name='Writing', parent=None) parent.save() category = Category(name='Thoughts', parent=parent) category.save() # Create a draft _post = Post(title='Random thoughts of the author', body='Thoughts turned to words.', category=category) _post.save() self.draft = _post # Publish a post post = Post(title='New thoughts from without', body='A post fit to be published!', category=category) post.save() post.publish() self.post = post self.client = test.Client() def test_index(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) posts = response.context['posts'] self.assertNotIn(self.draft, posts) self.assertIn(self.post, posts) def test_post_view(self): post_url = reverse('blog:post', kwargs=dict(pid=self.post.id, slug=self.post.slug)) response = self.client.get(post_url) self.assertEqual(response.status_code, 200) post = response.context['post'] posts = response.context['posts'] self.assertEqual(post, self.post) self.assertEqual(posts.count(), 0) def test_draft_view(self): draft_url = reverse('blog:post', kwargs=dict(pid=self.draft.id, slug=self.draft.slug)) response = self.client.get(draft_url) self.assertEqual(response.status_code, 404)
<commit_before>from django.test import TestCase class BlogViewsTestCase(TestCase): def setUp(self): <commit_msg>Add tests for blog index view and post view<commit_after>from django import test from django.core.urlresolvers import reverse from blog.models import Post, Category class BlogViewsTestCase(test.TestCase): def setUp(self): # Add parent category and post category parent = Category(name='Writing', parent=None) parent.save() category = Category(name='Thoughts', parent=parent) category.save() # Create a draft _post = Post(title='Random thoughts of the author', body='Thoughts turned to words.', category=category) _post.save() self.draft = _post # Publish a post post = Post(title='New thoughts from without', body='A post fit to be published!', category=category) post.save() post.publish() self.post = post self.client = test.Client() def test_index(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) posts = response.context['posts'] self.assertNotIn(self.draft, posts) self.assertIn(self.post, posts) def test_post_view(self): post_url = reverse('blog:post', kwargs=dict(pid=self.post.id, slug=self.post.slug)) response = self.client.get(post_url) self.assertEqual(response.status_code, 200) post = response.context['post'] posts = response.context['posts'] self.assertEqual(post, self.post) self.assertEqual(posts.count(), 0) def test_draft_view(self): draft_url = reverse('blog:post', kwargs=dict(pid=self.draft.id, slug=self.draft.slug)) response = self.client.get(draft_url) self.assertEqual(response.status_code, 404)
aabbed10e2ed744db71da3f8bb97e7605e315f07
mass/scheduler/worker.py
mass/scheduler/worker.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module define base class of mass worker. """ # built-in modules from functools import wraps import sys import traceback # local modules from mass.exception import TaskError class BaseWorker: """Base class of mass worker. """ role_functions = {} def role(self, name): """Registers a role to execute relative action. """ def decorator(func): self.role_functions[name] = func @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator def execute(self, action): """Execute action by relative registered function. """ role = action['Action'].get('_role', None) if not role: inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()]) print('Action(%s)' % inputs) return else: kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')} try: return self.role_functions[role](**kwargs) except: _, error, _ = sys.exc_info() raise TaskError(repr(error), traceback.format_exc()) def start(self, farm): """Start worker """ raise NotImplementedError
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module define base class of mass worker. """ # built-in modules from functools import wraps import sys import traceback # local modules from mass.exception import TaskError class BaseWorker(object): """Base class of mass worker. """ role_functions = {} def role(self, name): """Registers a role to execute relative action. """ def decorator(func): self.role_functions[name] = func @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator def execute(self, action): """Execute action by relative registered function. """ role = action['Action'].get('_role', None) if not role: inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()]) print('Action(%s)' % inputs) return else: kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')} try: return self.role_functions[role](**kwargs) except: _, error, _ = sys.exc_info() raise TaskError(repr(error), traceback.format_exc()) def start(self, farm): """Start worker """ raise NotImplementedError
Change BaseWorker to new style class.
Change BaseWorker to new style class.
Python
apache-2.0
badboy99tw/mass,KKBOX/mass,KKBOX/mass,badboy99tw/mass,KKBOX/mass,badboy99tw/mass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module define base class of mass worker. """ # built-in modules from functools import wraps import sys import traceback # local modules from mass.exception import TaskError class BaseWorker: """Base class of mass worker. """ role_functions = {} def role(self, name): """Registers a role to execute relative action. """ def decorator(func): self.role_functions[name] = func @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator def execute(self, action): """Execute action by relative registered function. """ role = action['Action'].get('_role', None) if not role: inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()]) print('Action(%s)' % inputs) return else: kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')} try: return self.role_functions[role](**kwargs) except: _, error, _ = sys.exc_info() raise TaskError(repr(error), traceback.format_exc()) def start(self, farm): """Start worker """ raise NotImplementedError Change BaseWorker to new style class.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module define base class of mass worker. """ # built-in modules from functools import wraps import sys import traceback # local modules from mass.exception import TaskError class BaseWorker(object): """Base class of mass worker. """ role_functions = {} def role(self, name): """Registers a role to execute relative action. """ def decorator(func): self.role_functions[name] = func @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator def execute(self, action): """Execute action by relative registered function. """ role = action['Action'].get('_role', None) if not role: inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()]) print('Action(%s)' % inputs) return else: kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')} try: return self.role_functions[role](**kwargs) except: _, error, _ = sys.exc_info() raise TaskError(repr(error), traceback.format_exc()) def start(self, farm): """Start worker """ raise NotImplementedError
<commit_before>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module define base class of mass worker. """ # built-in modules from functools import wraps import sys import traceback # local modules from mass.exception import TaskError class BaseWorker: """Base class of mass worker. """ role_functions = {} def role(self, name): """Registers a role to execute relative action. """ def decorator(func): self.role_functions[name] = func @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator def execute(self, action): """Execute action by relative registered function. """ role = action['Action'].get('_role', None) if not role: inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()]) print('Action(%s)' % inputs) return else: kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')} try: return self.role_functions[role](**kwargs) except: _, error, _ = sys.exc_info() raise TaskError(repr(error), traceback.format_exc()) def start(self, farm): """Start worker """ raise NotImplementedError <commit_msg>Change BaseWorker to new style class.<commit_after>
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module define base class of mass worker. """ # built-in modules from functools import wraps import sys import traceback # local modules from mass.exception import TaskError class BaseWorker(object): """Base class of mass worker. """ role_functions = {} def role(self, name): """Registers a role to execute relative action. """ def decorator(func): self.role_functions[name] = func @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator def execute(self, action): """Execute action by relative registered function. """ role = action['Action'].get('_role', None) if not role: inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()]) print('Action(%s)' % inputs) return else: kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')} try: return self.role_functions[role](**kwargs) except: _, error, _ = sys.exc_info() raise TaskError(repr(error), traceback.format_exc()) def start(self, farm): """Start worker """ raise NotImplementedError
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module define base class of mass worker. """ # built-in modules from functools import wraps import sys import traceback # local modules from mass.exception import TaskError class BaseWorker: """Base class of mass worker. """ role_functions = {} def role(self, name): """Registers a role to execute relative action. """ def decorator(func): self.role_functions[name] = func @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator def execute(self, action): """Execute action by relative registered function. """ role = action['Action'].get('_role', None) if not role: inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()]) print('Action(%s)' % inputs) return else: kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')} try: return self.role_functions[role](**kwargs) except: _, error, _ = sys.exc_info() raise TaskError(repr(error), traceback.format_exc()) def start(self, farm): """Start worker """ raise NotImplementedError Change BaseWorker to new style class.#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module define base class of mass worker. """ # built-in modules from functools import wraps import sys import traceback # local modules from mass.exception import TaskError class BaseWorker(object): """Base class of mass worker. """ role_functions = {} def role(self, name): """Registers a role to execute relative action. """ def decorator(func): self.role_functions[name] = func @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator def execute(self, action): """Execute action by relative registered function. """ role = action['Action'].get('_role', None) if not role: inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()]) print('Action(%s)' % inputs) return else: kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')} try: return self.role_functions[role](**kwargs) except: _, error, _ = sys.exc_info() raise TaskError(repr(error), traceback.format_exc()) def start(self, farm): """Start worker """ raise NotImplementedError
<commit_before>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module define base class of mass worker. """ # built-in modules from functools import wraps import sys import traceback # local modules from mass.exception import TaskError class BaseWorker: """Base class of mass worker. """ role_functions = {} def role(self, name): """Registers a role to execute relative action. """ def decorator(func): self.role_functions[name] = func @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator def execute(self, action): """Execute action by relative registered function. """ role = action['Action'].get('_role', None) if not role: inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()]) print('Action(%s)' % inputs) return else: kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')} try: return self.role_functions[role](**kwargs) except: _, error, _ = sys.exc_info() raise TaskError(repr(error), traceback.format_exc()) def start(self, farm): """Start worker """ raise NotImplementedError <commit_msg>Change BaseWorker to new style class.<commit_after>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module define base class of mass worker. """ # built-in modules from functools import wraps import sys import traceback # local modules from mass.exception import TaskError class BaseWorker(object): """Base class of mass worker. """ role_functions = {} def role(self, name): """Registers a role to execute relative action. """ def decorator(func): self.role_functions[name] = func @wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator def execute(self, action): """Execute action by relative registered function. """ role = action['Action'].get('_role', None) if not role: inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()]) print('Action(%s)' % inputs) return else: kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')} try: return self.role_functions[role](**kwargs) except: _, error, _ = sys.exc_info() raise TaskError(repr(error), traceback.format_exc()) def start(self, farm): """Start worker """ raise NotImplementedError
2022c5485289712b8de22fe551d65cf005442826
massa/domain/__init__.py
massa/domain/__init__.py
# -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(value): if abs(value.as_tuple().exponent) > 1: raise ValidationError('More than one decimal exponent not allowed') return value class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.'
# -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(value): if abs(value.as_tuple().exponent) > 1: raise ValidationError('Only one decimal point is allowed.') return value class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.'
Change error message of the weight validator.
Change error message of the weight validator.
Python
mit
jaapverloop/massa
# -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(value): if abs(value.as_tuple().exponent) > 1: raise ValidationError('More than one decimal exponent not allowed') return value class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.' Change error message of the weight validator.
# -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(value): if abs(value.as_tuple().exponent) > 1: raise ValidationError('Only one decimal point is allowed.') return value class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.'
<commit_before># -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(value): if abs(value.as_tuple().exponent) > 1: raise ValidationError('More than one decimal exponent not allowed') return value class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.' <commit_msg>Change error message of the weight validator.<commit_after>
# -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(value): if abs(value.as_tuple().exponent) > 1: raise ValidationError('Only one decimal point is allowed.') return value class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.'
# -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(value): if abs(value.as_tuple().exponent) > 1: raise ValidationError('More than one decimal exponent not allowed') return value class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.' Change error message of the weight validator.# -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(value): if abs(value.as_tuple().exponent) > 1: raise ValidationError('Only one decimal point is allowed.') return value class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.'
<commit_before># -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(value): if abs(value.as_tuple().exponent) > 1: raise ValidationError('More than one decimal exponent not allowed') return value class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.' <commit_msg>Change error message of the weight validator.<commit_after># -*- coding: utf-8 -*- from schematics.exceptions import ConversionError, ValidationError def validate(schema, data): try: schema.import_data(data) schema.validate() except (ConversionError, ValidationError) as e: raise InvalidInputError(details=e.messages) def weight_validator(value): if abs(value.as_tuple().exponent) > 1: raise ValidationError('Only one decimal point is allowed.') return value class DomainError(Exception): def __init__(self, message=None, details=None): if message: self.message = message if details: self.details = details class EntityNotFoundError(DomainError): """Raised when an entity does not exist.""" message = 'Entity does not exist.' class InvalidInputError(DomainError): """Raised when input data is invalid.""" message = 'Input data is invalid.'
a4808284731ebcc7ae9c29bfeee4db7e943e1b2a
pyinfra/__init__.py
pyinfra/__init__.py
# pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Trigger fact index creation from . import facts # noqa # Trigger module imports from . import modules # noqa
# pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global flag set True by `pyinfra_cli.__main__` is_cli = False # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Trigger fact index creation from . import facts # noqa # Trigger module imports from . import modules # noqa
Add default for `is_cli` to pyinfra.
Add default for `is_cli` to pyinfra.
Python
mit
Fizzadar/pyinfra,Fizzadar/pyinfra
# pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Trigger fact index creation from . import facts # noqa # Trigger module imports from . import modules # noqa Add default for `is_cli` to pyinfra.
# pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global flag set True by `pyinfra_cli.__main__` is_cli = False # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Trigger fact index creation from . import facts # noqa # Trigger module imports from . import modules # noqa
<commit_before># pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Trigger fact index creation from . import facts # noqa # Trigger module imports from . import modules # noqa <commit_msg>Add default for `is_cli` to pyinfra.<commit_after>
# pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global flag set True by `pyinfra_cli.__main__` is_cli = False # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Trigger fact index creation from . import facts # noqa # Trigger module imports from . import modules # noqa
# pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Trigger fact index creation from . import facts # noqa # Trigger module imports from . import modules # noqa Add default for `is_cli` to pyinfra.# pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global flag set True by `pyinfra_cli.__main__` is_cli = False # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Trigger fact index creation from . import facts # noqa # Trigger module imports from . import modules # noqa
<commit_before># pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Trigger fact index creation from . import facts # noqa # Trigger module imports from . import modules # noqa <commit_msg>Add default for `is_cli` to pyinfra.<commit_after># pyinfra # File: pyinfra/__init__.py # Desc: some global state for pyinfra ''' Welcome to pyinfra. ''' import logging # Global flag set True by `pyinfra_cli.__main__` is_cli = False # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Trigger fact index creation from . import facts # noqa # Trigger module imports from . import modules # noqa
27ce88988f22bfb1b3a6ba584da6162b9037b0fa
pony/thirdparty/compiler/__init__.py
pony/thirdparty/compiler/__init__.py
"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ import warnings warnings.warn("The compiler package is deprecated and removed in Python 3.x.", DeprecationWarning, stacklevel=2) from .transformer import parse, parseFile from .visitor import walk from .pycodegen import compile, compileFile
"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ from .transformer import parse, parseFile from .visitor import walk from .pycodegen import compile, compileFile
Remove deprecation warning from compiler package
Remove deprecation warning from compiler package
Python
apache-2.0
gwecho/pony,gwecho/pony,ponyorm/pony,ponyorm/pony,ponyorm/pony,gwecho/pony,ponyorm/pony
"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ import warnings warnings.warn("The compiler package is deprecated and removed in Python 3.x.", DeprecationWarning, stacklevel=2) from .transformer import parse, parseFile from .visitor import walk from .pycodegen import compile, compileFile Remove deprecation warning from compiler package
"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ from .transformer import parse, parseFile from .visitor import walk from .pycodegen import compile, compileFile
<commit_before>"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ import warnings warnings.warn("The compiler package is deprecated and removed in Python 3.x.", DeprecationWarning, stacklevel=2) from .transformer import parse, parseFile from .visitor import walk from .pycodegen import compile, compileFile <commit_msg>Remove deprecation warning from compiler package<commit_after>
"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ from .transformer import parse, parseFile from .visitor import walk from .pycodegen import compile, compileFile
"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ import warnings warnings.warn("The compiler package is deprecated and removed in Python 3.x.", DeprecationWarning, stacklevel=2) from .transformer import parse, parseFile from .visitor import walk from .pycodegen import compile, compileFile Remove deprecation warning from compiler package"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ from .transformer import parse, parseFile from .visitor import walk from .pycodegen import compile, compileFile
<commit_before>"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ import warnings warnings.warn("The compiler package is deprecated and removed in Python 3.x.", DeprecationWarning, stacklevel=2) from .transformer import parse, parseFile from .visitor import walk from .pycodegen import compile, compileFile <commit_msg>Remove deprecation warning from compiler package<commit_after>"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ from .transformer import parse, parseFile from .visitor import walk from .pycodegen import compile, compileFile
768470b75c0256c933f16856a9754302e5c43bc2
db/sql_server/pyodbc.py
db/sql_server/pyodbc.py
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ add_column_string = 'ALTER TABLE %s ADD %s;' def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
Add column support for sql server
Add column support for sql server
Python
apache-2.0
matthiask/south,matthiask/south
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields) Add column support for sql server
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ add_column_string = 'ALTER TABLE %s ADD %s;' def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
<commit_before>from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields) <commit_msg>Add column support for sql server<commit_after>
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ add_column_string = 'ALTER TABLE %s ADD %s;' def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields) Add column support for sql serverfrom django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ add_column_string = 'ALTER TABLE %s ADD %s;' def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
<commit_before>from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields) <commit_msg>Add column support for sql server<commit_after>from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ add_column_string = 'ALTER TABLE %s ADD %s;' def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
7f98aaeda38d7a30ab20ddc1d6ce7ae17d42f358
dduplicated/commands.py
dduplicated/commands.py
from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): fileManager.delete(files) exit(0) # Make the link to first file def link(files): fileManager.link(files) exit(0) # Print the help menu def help(): print("dduplicate is a simple script in python for detect and delete duplicate files in your directory") print("finded duplicated files, is possible delete, link or do nothing.") print("Command:") print("\tdetect\tPATHS\tfor only search and detect duplicated files in directory.") print("\tdelete\tPATHS\tfor delete any duplicated files in directory, not first file.") print("\tlink\tPATHS\tfor link first all duplicates in first file.") print("\thelp\t\tshow this help")
from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): return fileManager.delete(files) # Make the link to first file def link(files): return fileManager.link(files) # Print the help menu def help(): help = """ dduplicate is a simple script in python for detect and delete duplicate files in your directory finded duplicated files, is possible delete, link or do nothing. Command: \tdetect\tPATHS\tfor only search and detect duplicated files in directory. \tdelete\tPATHS\tfor delete any duplicated files in directory, not first file. \tlink\tPATHS\tfor link first all duplicates in first file. \thelp\t\tshow this help """ print(help)
Update the print help and add returns to delete and link methods.
Update the print help and add returns to delete and link methods. Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
Python
mit
messiasthi/dduplicated-cli
from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): fileManager.delete(files) exit(0) # Make the link to first file def link(files): fileManager.link(files) exit(0) # Print the help menu def help(): print("dduplicate is a simple script in python for detect and delete duplicate files in your directory") print("finded duplicated files, is possible delete, link or do nothing.") print("Command:") print("\tdetect\tPATHS\tfor only search and detect duplicated files in directory.") print("\tdelete\tPATHS\tfor delete any duplicated files in directory, not first file.") print("\tlink\tPATHS\tfor link first all duplicates in first file.") print("\thelp\t\tshow this help") Update the print help and add returns to delete and link methods. Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): return fileManager.delete(files) # Make the link to first file def link(files): return fileManager.link(files) # Print the help menu def help(): help = """ dduplicate is a simple script in python for detect and delete duplicate files in your directory finded duplicated files, is possible delete, link or do nothing. Command: \tdetect\tPATHS\tfor only search and detect duplicated files in directory. \tdelete\tPATHS\tfor delete any duplicated files in directory, not first file. \tlink\tPATHS\tfor link first all duplicates in first file. \thelp\t\tshow this help """ print(help)
<commit_before>from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): fileManager.delete(files) exit(0) # Make the link to first file def link(files): fileManager.link(files) exit(0) # Print the help menu def help(): print("dduplicate is a simple script in python for detect and delete duplicate files in your directory") print("finded duplicated files, is possible delete, link or do nothing.") print("Command:") print("\tdetect\tPATHS\tfor only search and detect duplicated files in directory.") print("\tdelete\tPATHS\tfor delete any duplicated files in directory, not first file.") print("\tlink\tPATHS\tfor link first all duplicates in first file.") print("\thelp\t\tshow this help") <commit_msg>Update the print help and add returns to delete and link methods. Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com><commit_after>
from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): return fileManager.delete(files) # Make the link to first file def link(files): return fileManager.link(files) # Print the help menu def help(): help = """ dduplicate is a simple script in python for detect and delete duplicate files in your directory finded duplicated files, is possible delete, link or do nothing. Command: \tdetect\tPATHS\tfor only search and detect duplicated files in directory. \tdelete\tPATHS\tfor delete any duplicated files in directory, not first file. \tlink\tPATHS\tfor link first all duplicates in first file. \thelp\t\tshow this help """ print(help)
from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): fileManager.delete(files) exit(0) # Make the link to first file def link(files): fileManager.link(files) exit(0) # Print the help menu def help(): print("dduplicate is a simple script in python for detect and delete duplicate files in your directory") print("finded duplicated files, is possible delete, link or do nothing.") print("Command:") print("\tdetect\tPATHS\tfor only search and detect duplicated files in directory.") print("\tdelete\tPATHS\tfor delete any duplicated files in directory, not first file.") print("\tlink\tPATHS\tfor link first all duplicates in first file.") print("\thelp\t\tshow this help") Update the print help and add returns to delete and link methods. Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): return fileManager.delete(files) # Make the link to first file def link(files): return fileManager.link(files) # Print the help menu def help(): help = """ dduplicate is a simple script in python for detect and delete duplicate files in your directory finded duplicated files, is possible delete, link or do nothing. Command: \tdetect\tPATHS\tfor only search and detect duplicated files in directory. \tdelete\tPATHS\tfor delete any duplicated files in directory, not first file. \tlink\tPATHS\tfor link first all duplicates in first file. \thelp\t\tshow this help """ print(help)
<commit_before>from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): fileManager.delete(files) exit(0) # Make the link to first file def link(files): fileManager.link(files) exit(0) # Print the help menu def help(): print("dduplicate is a simple script in python for detect and delete duplicate files in your directory") print("finded duplicated files, is possible delete, link or do nothing.") print("Command:") print("\tdetect\tPATHS\tfor only search and detect duplicated files in directory.") print("\tdelete\tPATHS\tfor delete any duplicated files in directory, not first file.") print("\tlink\tPATHS\tfor link first all duplicates in first file.") print("\thelp\t\tshow this help") <commit_msg>Update the print help and add returns to delete and link methods. Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com><commit_after>from dduplicated import scans, fileManager def detect(paths): return scans.scan(paths) # Remove all duplicates def delete(files): return fileManager.delete(files) # Make the link to first file def link(files): return fileManager.link(files) # Print the help menu def help(): help = """ dduplicate is a simple script in python for detect and delete duplicate files in your directory finded duplicated files, is possible delete, link or do nothing. Command: \tdetect\tPATHS\tfor only search and detect duplicated files in directory. \tdelete\tPATHS\tfor delete any duplicated files in directory, not first file. \tlink\tPATHS\tfor link first all duplicates in first file. \thelp\t\tshow this help """ print(help)
b8387222662e54da9c1cabbe5a9df698d25c594f
debug_toolbar/models.py
debug_toolbar/models.py
from __future__ import unicode_literals from django.conf import settings from django.utils.importlib import import_module from debug_toolbar.toolbar.loader import load_panel_classes from debug_toolbar.middleware import DebugToolbarMiddleware loaded = False def is_toolbar(cls): return (issubclass(cls, DebugToolbarMiddleware) or DebugToolbarMiddleware in getattr(cls, '__bases__', ())) def iter_toolbar_middlewares(): global loaded for middleware_path in settings.MIDDLEWARE_CLASSES: try: mod_path, cls_name = middleware_path.rsplit('.', 1) mod = import_module(mod_path) middleware_cls = getattr(mod, cls_name) except (AttributeError, ImportError, ValueError): continue if is_toolbar(middleware_cls) and not loaded: # we have a hit! loaded = True yield middleware_cls for middleware_cls in iter_toolbar_middlewares(): load_panel_classes()
from __future__ import unicode_literals from django.conf import settings from django.utils.importlib import import_module from debug_toolbar.toolbar.loader import load_panel_classes from debug_toolbar.middleware import DebugToolbarMiddleware for middleware_path in settings.MIDDLEWARE_CLASSES: # Replace this with import_by_path in Django >= 1.6. try: mod_path, cls_name = middleware_path.rsplit('.', 1) mod = import_module(mod_path) middleware_cls = getattr(mod, cls_name) except (AttributeError, ImportError, ValueError): continue if issubclass(middleware_cls, DebugToolbarMiddleware): load_panel_classes() break
Simplify code introduced in 7f7ea810.
Simplify code introduced in 7f7ea810.
Python
bsd-3-clause
ChristosChristofidis/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,barseghyanartur/django-debug-toolbar,barseghyanartur/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,jazzband/django-debug-toolbar,sidja/django-debug-toolbar,spookylukey/django-debug-toolbar,guilhermetavares/django-debug-toolbar,jazzband/django-debug-toolbar,stored/django-debug-toolbar,megcunningham/django-debug-toolbar,pevzi/django-debug-toolbar,seperman/django-debug-toolbar,Endika/django-debug-toolbar,ChristosChristofidis/django-debug-toolbar,sidja/django-debug-toolbar,stored/django-debug-toolbar,peap/django-debug-toolbar,guilhermetavares/django-debug-toolbar,calvinpy/django-debug-toolbar,calvinpy/django-debug-toolbar,sidja/django-debug-toolbar,calvinpy/django-debug-toolbar,tim-schilling/django-debug-toolbar,seperman/django-debug-toolbar,Endika/django-debug-toolbar,pevzi/django-debug-toolbar,ivelum/django-debug-toolbar,spookylukey/django-debug-toolbar,megcunningham/django-debug-toolbar,peap/django-debug-toolbar,jazzband/django-debug-toolbar,ivelum/django-debug-toolbar,tim-schilling/django-debug-toolbar,ivelum/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,barseghyanartur/django-debug-toolbar,guilhermetavares/django-debug-toolbar,pevzi/django-debug-toolbar,peap/django-debug-toolbar,stored/django-debug-toolbar,seperman/django-debug-toolbar,tim-schilling/django-debug-toolbar,ChristosChristofidis/django-debug-toolbar,megcunningham/django-debug-toolbar,spookylukey/django-debug-toolbar,Endika/django-debug-toolbar
from __future__ import unicode_literals from django.conf import settings from django.utils.importlib import import_module from debug_toolbar.toolbar.loader import load_panel_classes from debug_toolbar.middleware import DebugToolbarMiddleware loaded = False def is_toolbar(cls): return (issubclass(cls, DebugToolbarMiddleware) or DebugToolbarMiddleware in getattr(cls, '__bases__', ())) def iter_toolbar_middlewares(): global loaded for middleware_path in settings.MIDDLEWARE_CLASSES: try: mod_path, cls_name = middleware_path.rsplit('.', 1) mod = import_module(mod_path) middleware_cls = getattr(mod, cls_name) except (AttributeError, ImportError, ValueError): continue if is_toolbar(middleware_cls) and not loaded: # we have a hit! loaded = True yield middleware_cls for middleware_cls in iter_toolbar_middlewares(): load_panel_classes() Simplify code introduced in 7f7ea810.
from __future__ import unicode_literals from django.conf import settings from django.utils.importlib import import_module from debug_toolbar.toolbar.loader import load_panel_classes from debug_toolbar.middleware import DebugToolbarMiddleware for middleware_path in settings.MIDDLEWARE_CLASSES: # Replace this with import_by_path in Django >= 1.6. try: mod_path, cls_name = middleware_path.rsplit('.', 1) mod = import_module(mod_path) middleware_cls = getattr(mod, cls_name) except (AttributeError, ImportError, ValueError): continue if issubclass(middleware_cls, DebugToolbarMiddleware): load_panel_classes() break
<commit_before>from __future__ import unicode_literals from django.conf import settings from django.utils.importlib import import_module from debug_toolbar.toolbar.loader import load_panel_classes from debug_toolbar.middleware import DebugToolbarMiddleware loaded = False def is_toolbar(cls): return (issubclass(cls, DebugToolbarMiddleware) or DebugToolbarMiddleware in getattr(cls, '__bases__', ())) def iter_toolbar_middlewares(): global loaded for middleware_path in settings.MIDDLEWARE_CLASSES: try: mod_path, cls_name = middleware_path.rsplit('.', 1) mod = import_module(mod_path) middleware_cls = getattr(mod, cls_name) except (AttributeError, ImportError, ValueError): continue if is_toolbar(middleware_cls) and not loaded: # we have a hit! loaded = True yield middleware_cls for middleware_cls in iter_toolbar_middlewares(): load_panel_classes() <commit_msg>Simplify code introduced in 7f7ea810.<commit_after>
from __future__ import unicode_literals from django.conf import settings from django.utils.importlib import import_module from debug_toolbar.toolbar.loader import load_panel_classes from debug_toolbar.middleware import DebugToolbarMiddleware for middleware_path in settings.MIDDLEWARE_CLASSES: # Replace this with import_by_path in Django >= 1.6. try: mod_path, cls_name = middleware_path.rsplit('.', 1) mod = import_module(mod_path) middleware_cls = getattr(mod, cls_name) except (AttributeError, ImportError, ValueError): continue if issubclass(middleware_cls, DebugToolbarMiddleware): load_panel_classes() break
from __future__ import unicode_literals from django.conf import settings from django.utils.importlib import import_module from debug_toolbar.toolbar.loader import load_panel_classes from debug_toolbar.middleware import DebugToolbarMiddleware loaded = False def is_toolbar(cls): return (issubclass(cls, DebugToolbarMiddleware) or DebugToolbarMiddleware in getattr(cls, '__bases__', ())) def iter_toolbar_middlewares(): global loaded for middleware_path in settings.MIDDLEWARE_CLASSES: try: mod_path, cls_name = middleware_path.rsplit('.', 1) mod = import_module(mod_path) middleware_cls = getattr(mod, cls_name) except (AttributeError, ImportError, ValueError): continue if is_toolbar(middleware_cls) and not loaded: # we have a hit! loaded = True yield middleware_cls for middleware_cls in iter_toolbar_middlewares(): load_panel_classes() Simplify code introduced in 7f7ea810.from __future__ import unicode_literals from django.conf import settings from django.utils.importlib import import_module from debug_toolbar.toolbar.loader import load_panel_classes from debug_toolbar.middleware import DebugToolbarMiddleware for middleware_path in settings.MIDDLEWARE_CLASSES: # Replace this with import_by_path in Django >= 1.6. try: mod_path, cls_name = middleware_path.rsplit('.', 1) mod = import_module(mod_path) middleware_cls = getattr(mod, cls_name) except (AttributeError, ImportError, ValueError): continue if issubclass(middleware_cls, DebugToolbarMiddleware): load_panel_classes() break
<commit_before>from __future__ import unicode_literals from django.conf import settings from django.utils.importlib import import_module from debug_toolbar.toolbar.loader import load_panel_classes from debug_toolbar.middleware import DebugToolbarMiddleware loaded = False def is_toolbar(cls): return (issubclass(cls, DebugToolbarMiddleware) or DebugToolbarMiddleware in getattr(cls, '__bases__', ())) def iter_toolbar_middlewares(): global loaded for middleware_path in settings.MIDDLEWARE_CLASSES: try: mod_path, cls_name = middleware_path.rsplit('.', 1) mod = import_module(mod_path) middleware_cls = getattr(mod, cls_name) except (AttributeError, ImportError, ValueError): continue if is_toolbar(middleware_cls) and not loaded: # we have a hit! loaded = True yield middleware_cls for middleware_cls in iter_toolbar_middlewares(): load_panel_classes() <commit_msg>Simplify code introduced in 7f7ea810.<commit_after>from __future__ import unicode_literals from django.conf import settings from django.utils.importlib import import_module from debug_toolbar.toolbar.loader import load_panel_classes from debug_toolbar.middleware import DebugToolbarMiddleware for middleware_path in settings.MIDDLEWARE_CLASSES: # Replace this with import_by_path in Django >= 1.6. try: mod_path, cls_name = middleware_path.rsplit('.', 1) mod = import_module(mod_path) middleware_cls = getattr(mod, cls_name) except (AttributeError, ImportError, ValueError): continue if issubclass(middleware_cls, DebugToolbarMiddleware): load_panel_classes() break
27b9bd22bb43b8b86ae1c40a90c1fae7157dcb86
app/tests.py
app/tests.py
from app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response)
from app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response) def test_login_required(self): self.check_login_required('/scores/add', '/login?next=%2Fscores%2Fadd') self.check_login_required('/judging/presentation/new', '/login?next=%2Fjudging%2Fpresentation%2Fnew') self.check_login_required('/judging/technical/new', '/login?next=%2Fjudging%2Ftechnical%2Fnew') self.check_login_required('/judging/core_values/new', '/login?next=%2Fjudging%2Fcore_values%2Fnew') self.check_login_required('/settings', '/login?next=%2Fsettings') self.check_login_required('/review', '/login?next=%2Freview') self.check_login_required('/teams/new', '/login?next=%2Fteams%2Fnew') self.check_login_required('/scores/playoffs', '/login?next=%2Fscores%2Fplayoffs') def check_login_required(self, attempted_location, redirected_location): response = self.client.get(attempted_location) self.assertTrue(response.status_code in (301, 302)) self.assertEqual(response.location, 'http://' + self.app.config['SERVER_NAME'] + redirected_location)
Add test to verify login required for protected pages
Add test to verify login required for protected pages
Python
mit
rtfoley/scorepy,rtfoley/scorepy,rtfoley/scorepy
from app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response) Add test to verify login required for protected pages
from app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response) def test_login_required(self): self.check_login_required('/scores/add', '/login?next=%2Fscores%2Fadd') self.check_login_required('/judging/presentation/new', '/login?next=%2Fjudging%2Fpresentation%2Fnew') self.check_login_required('/judging/technical/new', '/login?next=%2Fjudging%2Ftechnical%2Fnew') self.check_login_required('/judging/core_values/new', '/login?next=%2Fjudging%2Fcore_values%2Fnew') self.check_login_required('/settings', '/login?next=%2Fsettings') self.check_login_required('/review', '/login?next=%2Freview') self.check_login_required('/teams/new', '/login?next=%2Fteams%2Fnew') self.check_login_required('/scores/playoffs', '/login?next=%2Fscores%2Fplayoffs') def check_login_required(self, attempted_location, redirected_location): response = self.client.get(attempted_location) self.assertTrue(response.status_code in (301, 302)) self.assertEqual(response.location, 'http://' + self.app.config['SERVER_NAME'] + redirected_location)
<commit_before>from app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response) <commit_msg>Add test to verify login required for protected pages<commit_after>
from app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response) def test_login_required(self): self.check_login_required('/scores/add', '/login?next=%2Fscores%2Fadd') self.check_login_required('/judging/presentation/new', '/login?next=%2Fjudging%2Fpresentation%2Fnew') self.check_login_required('/judging/technical/new', '/login?next=%2Fjudging%2Ftechnical%2Fnew') self.check_login_required('/judging/core_values/new', '/login?next=%2Fjudging%2Fcore_values%2Fnew') self.check_login_required('/settings', '/login?next=%2Fsettings') self.check_login_required('/review', '/login?next=%2Freview') self.check_login_required('/teams/new', '/login?next=%2Fteams%2Fnew') self.check_login_required('/scores/playoffs', '/login?next=%2Fscores%2Fplayoffs') def check_login_required(self, attempted_location, redirected_location): response = self.client.get(attempted_location) self.assertTrue(response.status_code in (301, 302)) self.assertEqual(response.location, 'http://' + self.app.config['SERVER_NAME'] + redirected_location)
from app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response) Add test to verify login required for protected pagesfrom app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response) def test_login_required(self): self.check_login_required('/scores/add', '/login?next=%2Fscores%2Fadd') self.check_login_required('/judging/presentation/new', '/login?next=%2Fjudging%2Fpresentation%2Fnew') self.check_login_required('/judging/technical/new', '/login?next=%2Fjudging%2Ftechnical%2Fnew') self.check_login_required('/judging/core_values/new', '/login?next=%2Fjudging%2Fcore_values%2Fnew') self.check_login_required('/settings', '/login?next=%2Fsettings') self.check_login_required('/review', '/login?next=%2Freview') self.check_login_required('/teams/new', '/login?next=%2Fteams%2Fnew') self.check_login_required('/scores/playoffs', '/login?next=%2Fscores%2Fplayoffs') def check_login_required(self, attempted_location, redirected_location): response = self.client.get(attempted_location) self.assertTrue(response.status_code in (301, 302)) self.assertEqual(response.location, 'http://' + self.app.config['SERVER_NAME'] + redirected_location)
<commit_before>from app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response) <commit_msg>Add test to verify login required for protected pages<commit_after>from app.test_base import BaseTestCase class TestTopLevelFunctions(BaseTestCase): def test_index_response(self): response = self.client.get('/') self.assert200(response) def test_login_required(self): self.check_login_required('/scores/add', '/login?next=%2Fscores%2Fadd') self.check_login_required('/judging/presentation/new', '/login?next=%2Fjudging%2Fpresentation%2Fnew') self.check_login_required('/judging/technical/new', '/login?next=%2Fjudging%2Ftechnical%2Fnew') self.check_login_required('/judging/core_values/new', '/login?next=%2Fjudging%2Fcore_values%2Fnew') self.check_login_required('/settings', '/login?next=%2Fsettings') self.check_login_required('/review', '/login?next=%2Freview') self.check_login_required('/teams/new', '/login?next=%2Fteams%2Fnew') self.check_login_required('/scores/playoffs', '/login?next=%2Fscores%2Fplayoffs') def check_login_required(self, attempted_location, redirected_location): response = self.client.get(attempted_location) self.assertTrue(response.status_code in (301, 302)) self.assertEqual(response.location, 'http://' + self.app.config['SERVER_NAME'] + redirected_location)
d0374f256b58ed3cb8194e4b46a62b97aee990e1
tests/test_core_lexer.py
tests/test_core_lexer.py
# -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfsfd", " a") )) def test_clean_line(input_, output_): assert lexer.clean_line(input_) == output_
# -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfsfd", " a") )) def test_clean_line(input_, output_): assert lexer.clean_line(input_) == output_ @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", " "), (" ", " "), (" ", " "), ("\t ", " "), ("\t\t\t", 12 * " "), ("\t \t", " "), ("\t\t\t ", " "), (" \t\t\t ", " ") )) def test_reindent_line(input_, output_): assert lexer.reindent_line(input_) == output_
Add tests for reindenting line
Add tests for reindenting line
Python
mit
9seconds/concierge,9seconds/sshrc
# -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfsfd", " a") )) def test_clean_line(input_, output_): assert lexer.clean_line(input_) == output_ Add tests for reindenting line
# -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfsfd", " a") )) def test_clean_line(input_, output_): assert lexer.clean_line(input_) == output_ @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", " "), (" ", " "), (" ", " "), ("\t ", " "), ("\t\t\t", 12 * " "), ("\t \t", " "), ("\t\t\t ", " "), (" \t\t\t ", " ") )) def test_reindent_line(input_, output_): assert lexer.reindent_line(input_) == output_
<commit_before># -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfsfd", " a") )) def test_clean_line(input_, output_): assert lexer.clean_line(input_) == output_ <commit_msg>Add tests for reindenting line<commit_after>
# -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfsfd", " a") )) def test_clean_line(input_, output_): assert lexer.clean_line(input_) == output_ @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", " "), (" ", " "), (" ", " "), ("\t ", " "), ("\t\t\t", 12 * " "), ("\t \t", " "), ("\t\t\t ", " "), (" \t\t\t ", " ") )) def test_reindent_line(input_, output_): assert lexer.reindent_line(input_) == output_
# -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfsfd", " a") )) def test_clean_line(input_, output_): assert lexer.clean_line(input_) == output_ Add tests for reindenting line# -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfsfd", " a") )) def test_clean_line(input_, output_): assert lexer.clean_line(input_) == output_ @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", " "), (" ", " "), (" ", " "), ("\t ", " "), ("\t\t\t", 12 * " "), ("\t \t", " "), ("\t\t\t ", " "), (" \t\t\t ", " ") )) def test_reindent_line(input_, output_): assert lexer.reindent_line(input_) == output_
<commit_before># -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfsfd", " a") )) def test_clean_line(input_, output_): assert lexer.clean_line(input_) == output_ <commit_msg>Add tests for reindenting line<commit_after># -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfsfd", " a") )) def test_clean_line(input_, output_): assert lexer.clean_line(input_) == output_ @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", " "), (" ", " "), (" ", " "), ("\t ", " "), ("\t\t\t", 12 * " "), ("\t \t", " "), ("\t\t\t ", " "), (" \t\t\t ", " ") )) def test_reindent_line(input_, output_): assert lexer.reindent_line(input_) == output_
2e691cbe1c5ef545968d3b7574b81ce4d55a1dd8
ci/scripts/testserver.py
ci/scripts/testserver.py
# # Hello World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import logging import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:1234") while True: # Wait for next request from client message = socket.recv() print("Received request: %s" % message) # Send reply back to client socket.send('{"responses": [{"codes": [0, 1, 2], "msg": "Thanks!"}, {"codes": [3, 4, 5], "msg": "Not!"}]}')
# # Hello World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import logging import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:1234") while True: # Wait for next request from client message = socket.recv() print("Received request: %s" % message) # Send reply back to client socket.send_string('{"responses": [{"codes": [0, 1, 2], "msg": "Thanks!"}, {"codes": [3, 4, 5], "msg": "Not!"}]}')
Update method call for test server
Update method call for test server
Python
mit
AO-StreetArt/0-Meter,AO-StreetArt/0-Meter
# # Hello World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import logging import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:1234") while True: # Wait for next request from client message = socket.recv() print("Received request: %s" % message) # Send reply back to client socket.send('{"responses": [{"codes": [0, 1, 2], "msg": "Thanks!"}, {"codes": [3, 4, 5], "msg": "Not!"}]}') Update method call for test server
# # Hello World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import logging import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:1234") while True: # Wait for next request from client message = socket.recv() print("Received request: %s" % message) # Send reply back to client socket.send_string('{"responses": [{"codes": [0, 1, 2], "msg": "Thanks!"}, {"codes": [3, 4, 5], "msg": "Not!"}]}')
<commit_before># # Hello World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import logging import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:1234") while True: # Wait for next request from client message = socket.recv() print("Received request: %s" % message) # Send reply back to client socket.send('{"responses": [{"codes": [0, 1, 2], "msg": "Thanks!"}, {"codes": [3, 4, 5], "msg": "Not!"}]}') <commit_msg>Update method call for test server<commit_after>
# # Hello World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import logging import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:1234") while True: # Wait for next request from client message = socket.recv() print("Received request: %s" % message) # Send reply back to client socket.send_string('{"responses": [{"codes": [0, 1, 2], "msg": "Thanks!"}, {"codes": [3, 4, 5], "msg": "Not!"}]}')
# # Hello World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import logging import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:1234") while True: # Wait for next request from client message = socket.recv() print("Received request: %s" % message) # Send reply back to client socket.send('{"responses": [{"codes": [0, 1, 2], "msg": "Thanks!"}, {"codes": [3, 4, 5], "msg": "Not!"}]}') Update method call for test server# # Hello World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import logging import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:1234") while True: # Wait for next request from client message = socket.recv() print("Received request: %s" % message) # Send reply back to client socket.send_string('{"responses": [{"codes": [0, 1, 2], "msg": "Thanks!"}, {"codes": [3, 4, 5], "msg": "Not!"}]}')
<commit_before># # Hello World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import logging import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:1234") while True: # Wait for next request from client message = socket.recv() print("Received request: %s" % message) # Send reply back to client socket.send('{"responses": [{"codes": [0, 1, 2], "msg": "Thanks!"}, {"codes": [3, 4, 5], "msg": "Not!"}]}') <commit_msg>Update method call for test server<commit_after># # Hello World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import logging import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:1234") while True: # Wait for next request from client message = socket.recv() print("Received request: %s" % message) # Send reply back to client socket.send_string('{"responses": [{"codes": [0, 1, 2], "msg": "Thanks!"}, {"codes": [3, 4, 5], "msg": "Not!"}]}')
4f2c3df24a59a7c287e59ec7d9b11922e7c49412
tests/test_search.py
tests/test_search.py
from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations
from sharepa.search import ShareSearch from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations def test_no_title_search(): my_search = ShareSearch() my_search = my_search.query( 'query_string', query='NOT title:*', analyze_wildcard=True ) results = my_search.execute() for result in results: assert not result.get('title')
Add test for no title search
Add test for no title search
Python
mit
CenterForOpenScience/sharepa,erinspace/sharepa,fabianvf/sharepa,samanehsan/sharepa
from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations Add test for no title search
from sharepa.search import ShareSearch from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations def test_no_title_search(): my_search = ShareSearch() my_search = my_search.query( 'query_string', query='NOT title:*', analyze_wildcard=True ) results = my_search.execute() for result in results: assert not result.get('title')
<commit_before>from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations <commit_msg>Add test for no title search<commit_after>
from sharepa.search import ShareSearch from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations def test_no_title_search(): my_search = ShareSearch() my_search = my_search.query( 'query_string', query='NOT title:*', analyze_wildcard=True ) results = my_search.execute() for result in results: assert not result.get('title')
from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations Add test for no title searchfrom sharepa.search import ShareSearch from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations def test_no_title_search(): my_search = ShareSearch() my_search = my_search.query( 'query_string', query='NOT title:*', analyze_wildcard=True ) results = my_search.execute() for result in results: assert not result.get('title')
<commit_before>from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations <commit_msg>Add test for no title search<commit_after>from sharepa.search import ShareSearch from sharepa.search import basic_search def test_basic_search(): results = basic_search.execute() assert results.hits assert results.aggregations def test_no_title_search(): my_search = ShareSearch() my_search = my_search.query( 'query_string', query='NOT title:*', analyze_wildcard=True ) results = my_search.execute() for result in results: assert not result.get('title')
62f96cc41d6a1aca912889664392d30531805a4f
setup.py
setup.py
from distutils.core import setup from setuptools import find_packages __author__ = "Arthur Fortes" setup( name='CaseRecommender', packages=find_packages(), version='0.0.12', license='GPL3 License', description='A recommender systems framework for Python', author='Arthur Fortes', author_email='fortes.arthur@gmail.com', url='https://github.com/ArthurFortes/CaseRecommender', download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.12', keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'], classifiers=[], )
from distutils.core import setup from setuptools import find_packages __author__ = "Arthur Fortes" setup( name='CaseRecommender', packages=find_packages(), version='0.0.13', license='GPL3 License', description='A recommender systems framework for Python', author='Arthur Fortes', author_email='fortes.arthur@gmail.com', url='https://github.com/ArthurFortes/CaseRecommender', download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.13', keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'], classifiers=[], )
Fix bugs in item and user knn
Fix bugs in item and user knn
Python
mit
ArthurFortes/CaseRecommender
from distutils.core import setup from setuptools import find_packages __author__ = "Arthur Fortes" setup( name='CaseRecommender', packages=find_packages(), version='0.0.12', license='GPL3 License', description='A recommender systems framework for Python', author='Arthur Fortes', author_email='fortes.arthur@gmail.com', url='https://github.com/ArthurFortes/CaseRecommender', download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.12', keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'], classifiers=[], ) Fix bugs in item and user knn
from distutils.core import setup from setuptools import find_packages __author__ = "Arthur Fortes" setup( name='CaseRecommender', packages=find_packages(), version='0.0.13', license='GPL3 License', description='A recommender systems framework for Python', author='Arthur Fortes', author_email='fortes.arthur@gmail.com', url='https://github.com/ArthurFortes/CaseRecommender', download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.13', keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'], classifiers=[], )
<commit_before>from distutils.core import setup from setuptools import find_packages __author__ = "Arthur Fortes" setup( name='CaseRecommender', packages=find_packages(), version='0.0.12', license='GPL3 License', description='A recommender systems framework for Python', author='Arthur Fortes', author_email='fortes.arthur@gmail.com', url='https://github.com/ArthurFortes/CaseRecommender', download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.12', keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'], classifiers=[], ) <commit_msg>Fix bugs in item and user knn<commit_after>
from distutils.core import setup from setuptools import find_packages __author__ = "Arthur Fortes" setup( name='CaseRecommender', packages=find_packages(), version='0.0.13', license='GPL3 License', description='A recommender systems framework for Python', author='Arthur Fortes', author_email='fortes.arthur@gmail.com', url='https://github.com/ArthurFortes/CaseRecommender', download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.13', keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'], classifiers=[], )
from distutils.core import setup from setuptools import find_packages __author__ = "Arthur Fortes" setup( name='CaseRecommender', packages=find_packages(), version='0.0.12', license='GPL3 License', description='A recommender systems framework for Python', author='Arthur Fortes', author_email='fortes.arthur@gmail.com', url='https://github.com/ArthurFortes/CaseRecommender', download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.12', keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'], classifiers=[], ) Fix bugs in item and user knnfrom distutils.core import setup from setuptools import find_packages __author__ = "Arthur Fortes" setup( name='CaseRecommender', packages=find_packages(), version='0.0.13', license='GPL3 License', description='A recommender systems framework for Python', author='Arthur Fortes', author_email='fortes.arthur@gmail.com', url='https://github.com/ArthurFortes/CaseRecommender', download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.13', keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'], classifiers=[], )
<commit_before>from distutils.core import setup from setuptools import find_packages __author__ = "Arthur Fortes" setup( name='CaseRecommender', packages=find_packages(), version='0.0.12', license='GPL3 License', description='A recommender systems framework for Python', author='Arthur Fortes', author_email='fortes.arthur@gmail.com', url='https://github.com/ArthurFortes/CaseRecommender', download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.12', keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'], classifiers=[], ) <commit_msg>Fix bugs in item and user knn<commit_after>from distutils.core import setup from setuptools import find_packages __author__ = "Arthur Fortes" setup( name='CaseRecommender', packages=find_packages(), version='0.0.13', license='GPL3 License', description='A recommender systems framework for Python', author='Arthur Fortes', author_email='fortes.arthur@gmail.com', url='https://github.com/ArthurFortes/CaseRecommender', download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.13', keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'], classifiers=[], )
e2d8737f70e973712d9ee2b958f4e45bf4528791
setup.py
setup.py
from setuptools import setup setup( name='django-simpleimages', version='1.2.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=[ 'simpleimages', 'simpleimages.management', 'simpleimages.management.commands', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<=1.8", "six", "Pillow", 'clint', ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries', ], )
from setuptools import setup setup( name='django-simpleimages', version='1.2.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=[ 'simpleimages', 'simpleimages.management', 'simpleimages.management.commands', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<1.8", "six", "Pillow", 'clint', ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries', ], )
Fix required Django version (doesnt support 1.8 yet)
Fix required Django version (doesnt support 1.8 yet)
Python
mit
saulshanabrook/django-simpleimages
from setuptools import setup setup( name='django-simpleimages', version='1.2.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=[ 'simpleimages', 'simpleimages.management', 'simpleimages.management.commands', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<=1.8", "six", "Pillow", 'clint', ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries', ], ) Fix required Django version (doesnt support 1.8 yet)
from setuptools import setup setup( name='django-simpleimages', version='1.2.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=[ 'simpleimages', 'simpleimages.management', 'simpleimages.management.commands', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<1.8", "six", "Pillow", 'clint', ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries', ], )
<commit_before>from setuptools import setup setup( name='django-simpleimages', version='1.2.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=[ 'simpleimages', 'simpleimages.management', 'simpleimages.management.commands', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<=1.8", "six", "Pillow", 'clint', ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries', ], ) <commit_msg>Fix required Django version (doesnt support 1.8 yet)<commit_after>
from setuptools import setup setup( name='django-simpleimages', version='1.2.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=[ 'simpleimages', 'simpleimages.management', 'simpleimages.management.commands', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<1.8", "six", "Pillow", 'clint', ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries', ], )
from setuptools import setup setup( name='django-simpleimages', version='1.2.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=[ 'simpleimages', 'simpleimages.management', 'simpleimages.management.commands', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<=1.8", "six", "Pillow", 'clint', ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries', ], ) Fix required Django version (doesnt support 1.8 yet)from setuptools import setup setup( name='django-simpleimages', version='1.2.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=[ 'simpleimages', 'simpleimages.management', 'simpleimages.management.commands', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<1.8", "six", "Pillow", 'clint', ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries', ], )
<commit_before>from setuptools import setup setup( name='django-simpleimages', version='1.2.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=[ 'simpleimages', 'simpleimages.management', 'simpleimages.management.commands', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<=1.8", "six", "Pillow", 'clint', ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries', ], ) <commit_msg>Fix required Django version (doesnt support 1.8 yet)<commit_after>from setuptools import setup setup( name='django-simpleimages', version='1.2.0', author='Saul Shanabrook', author_email='s.shanabrook@gmail.com', packages=[ 'simpleimages', 'simpleimages.management', 'simpleimages.management.commands', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<1.8", "six", "Pillow", 'clint', ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries', ], )
2640566b45736229cab347b9482a7372488ec53b
eccodes/highlevel/message.py
eccodes/highlevel/message.py
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle)
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle)
Add get/set methods to the Message class
Add get/set methods to the Message class
Python
apache-2.0
ecmwf/eccodes-python,ecmwf/eccodes-python
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) Add get/set methods to the Message class
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle)
<commit_before> import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) <commit_msg>Add get/set methods to the Message class<commit_after>
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle)
import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) Add get/set methods to the Message class import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle)
<commit_before> import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle) <commit_msg>Add get/set methods to the Message class<commit_after> import io import eccodes class Message: def __init__(self, handle): self.handle = handle def __del__(self): eccodes.codes_release(self.handle) def get(self, name): return eccodes.codes_get(self.handle, name) def set(self, name, value): return eccodes.codes_set(self.handle, name, value) def get_array(self, name): return eccodes.codes_get_array(self.handle, name) def set_array(self, name, value): return eccodes.codes_set_array(self.handle, name, value) def write_to(self, fileobj): assert isinstance(fileobj, io.IOBase) eccodes.codes_write(self.handle, fileobj) def get_buffer(self): return eccodes.codes_get_message(self.handle)
d8375d3e3a4a00598ac0cdc38861be9f56fb58c0
edison/tests/sanity_tests.py
edison/tests/sanity_tests.py
from edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True)
from edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True) self.assertFalse(False)
Add another inane test to trigger Landscape
Add another inane test to trigger Landscape
Python
mit
briancline/edison
from edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True) Add another inane test to trigger Landscape
from edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True) self.assertFalse(False)
<commit_before>from edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True) <commit_msg>Add another inane test to trigger Landscape<commit_after>
from edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True) self.assertFalse(False)
from edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True) Add another inane test to trigger Landscapefrom edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True) self.assertFalse(False)
<commit_before>from edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True) <commit_msg>Add another inane test to trigger Landscape<commit_after>from edison.tests import unittest class SanityTests(unittest.TestCase): def test_psych(self): self.assertTrue(True) self.assertFalse(False)
2bbb93a44b76949e34bce3a696a0ad3e3222ad9c
jsonsempai.py
jsonsempai.py
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): return self.get(attr) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader())
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): try: return self[attr] except KeyError: raise AttributeError("'{}'".format(attr)) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader())
Raise AttributeError instead of None
Raise AttributeError instead of None
Python
mit
kragniz/json-sempai
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): return self.get(attr) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader()) Raise AttributeError instead of None
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): try: return self[attr] except KeyError: raise AttributeError("'{}'".format(attr)) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader())
<commit_before>import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): return self.get(attr) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader()) <commit_msg>Raise AttributeError instead of None<commit_after>
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): try: return self[attr] except KeyError: raise AttributeError("'{}'".format(attr)) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader())
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): return self.get(attr) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader()) Raise AttributeError instead of Noneimport imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): try: return self[attr] except KeyError: raise AttributeError("'{}'".format(attr)) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader())
<commit_before>import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): return self.get(attr) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader()) <commit_msg>Raise AttributeError instead of None<commit_after>import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in d.iteritems(): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): try: return self[attr] except KeyError: raise AttributeError("'{}'".format(attr)) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): print self.json_path return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader())
027500ce86d838bae1927fe2590a9ce88cb61db4
troposphere/utils.py
troposphere/utils.py
import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time)
import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5, include_initial=True): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: if include_initial: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time)
Add "include_initial" kwarg to support tailing stack updates
Add "include_initial" kwarg to support tailing stack updates `get_events` will return all events that have occurred for a stack. This is useless if we're tailing an update to a stack.
Python
bsd-2-clause
ikben/troposphere,inetCatapult/troposphere,micahhausler/troposphere,ptoraskar/troposphere,johnctitus/troposphere,cloudtools/troposphere,johnctitus/troposphere,pas256/troposphere,horacio3/troposphere,dmm92/troposphere,craigbruce/troposphere,LouTheBrew/troposphere,xxxVxxx/troposphere,pas256/troposphere,cloudtools/troposphere,Yipit/troposphere,WeAreCloudar/troposphere,7digital/troposphere,ikben/troposphere,horacio3/troposphere,garnaat/troposphere,alonsodomin/troposphere,alonsodomin/troposphere,7digital/troposphere,amosshapira/troposphere,dmm92/troposphere
import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time) Add "include_initial" kwarg to support tailing stack updates `get_events` will return all events that have occurred for a stack. This is useless if we're tailing an update to a stack.
import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5, include_initial=True): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: if include_initial: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time)
<commit_before>import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time) <commit_msg>Add "include_initial" kwarg to support tailing stack updates `get_events` will return all events that have occurred for a stack. This is useless if we're tailing an update to a stack.<commit_after>
import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5, include_initial=True): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: if include_initial: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time)
import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time) Add "include_initial" kwarg to support tailing stack updates `get_events` will return all events that have occurred for a stack. This is useless if we're tailing an update to a stack.import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5, include_initial=True): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: if include_initial: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time)
<commit_before>import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time) <commit_msg>Add "include_initial" kwarg to support tailing stack updates `get_events` will return all events that have occurred for a stack. This is useless if we're tailing an update to a stack.<commit_after>import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5, include_initial=True): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: if include_initial: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time)
eeac557b77a3a63a3497791a2716706801b20e37
kodos/main.py
kodos/main.py
def run(args=None): """Main entry point of the application.""" pass
import sys from PyQt4.QtGui import QApplication, QMainWindow from kodos.ui.ui_main import Ui_MainWindow class KodosMainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(KodosMainWindow, self).__init__(parent) self.setupUi(self) self.connectActions() # Trigger the textChanged signal for widget in [self.regexText, self.searchText, self.replaceText]: widget.setPlainText('') def connectActions(self): # Connect input widgets to update the GUI when their text change for widget in [self.regexText, self.searchText, self.replaceText]: widget.textChanged.connect(self.on_compute_regex) def on_compute_regex(self): regex = self.regexText.toPlainText() search = self.searchText.toPlainText() replace = self.replaceText.toPlainText() if regex == "" or search == "": self.statusbar.showMessage( "Please enter a regex and a search to work on") else: self.statusbar.clearMessage() def run(args=None): """Main entry point of the application.""" app = QApplication(sys.argv) kodos = KodosMainWindow() kodos.show() app.exec_()
Connect the UI to the code and start to connect slots to actions.
Connect the UI to the code and start to connect slots to actions.
Python
bsd-2-clause
multani/kodos-qt4
def run(args=None): """Main entry point of the application.""" pass Connect the UI to the code and start to connect slots to actions.
import sys from PyQt4.QtGui import QApplication, QMainWindow from kodos.ui.ui_main import Ui_MainWindow class KodosMainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(KodosMainWindow, self).__init__(parent) self.setupUi(self) self.connectActions() # Trigger the textChanged signal for widget in [self.regexText, self.searchText, self.replaceText]: widget.setPlainText('') def connectActions(self): # Connect input widgets to update the GUI when their text change for widget in [self.regexText, self.searchText, self.replaceText]: widget.textChanged.connect(self.on_compute_regex) def on_compute_regex(self): regex = self.regexText.toPlainText() search = self.searchText.toPlainText() replace = self.replaceText.toPlainText() if regex == "" or search == "": self.statusbar.showMessage( "Please enter a regex and a search to work on") else: self.statusbar.clearMessage() def run(args=None): """Main entry point of the application.""" app = QApplication(sys.argv) kodos = KodosMainWindow() kodos.show() app.exec_()
<commit_before> def run(args=None): """Main entry point of the application.""" pass <commit_msg>Connect the UI to the code and start to connect slots to actions.<commit_after>
import sys from PyQt4.QtGui import QApplication, QMainWindow from kodos.ui.ui_main import Ui_MainWindow class KodosMainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(KodosMainWindow, self).__init__(parent) self.setupUi(self) self.connectActions() # Trigger the textChanged signal for widget in [self.regexText, self.searchText, self.replaceText]: widget.setPlainText('') def connectActions(self): # Connect input widgets to update the GUI when their text change for widget in [self.regexText, self.searchText, self.replaceText]: widget.textChanged.connect(self.on_compute_regex) def on_compute_regex(self): regex = self.regexText.toPlainText() search = self.searchText.toPlainText() replace = self.replaceText.toPlainText() if regex == "" or search == "": self.statusbar.showMessage( "Please enter a regex and a search to work on") else: self.statusbar.clearMessage() def run(args=None): """Main entry point of the application.""" app = QApplication(sys.argv) kodos = KodosMainWindow() kodos.show() app.exec_()
def run(args=None): """Main entry point of the application.""" pass Connect the UI to the code and start to connect slots to actions.import sys from PyQt4.QtGui import QApplication, QMainWindow from kodos.ui.ui_main import Ui_MainWindow class KodosMainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(KodosMainWindow, self).__init__(parent) self.setupUi(self) self.connectActions() # Trigger the textChanged signal for widget in [self.regexText, self.searchText, self.replaceText]: widget.setPlainText('') def connectActions(self): # Connect input widgets to update the GUI when their text change for widget in [self.regexText, self.searchText, self.replaceText]: widget.textChanged.connect(self.on_compute_regex) def on_compute_regex(self): regex = self.regexText.toPlainText() search = self.searchText.toPlainText() replace = self.replaceText.toPlainText() if regex == "" or search == "": self.statusbar.showMessage( "Please enter a regex and a search to work on") else: self.statusbar.clearMessage() def run(args=None): """Main entry point of the application.""" app = QApplication(sys.argv) kodos = KodosMainWindow() kodos.show() app.exec_()
<commit_before> def run(args=None): """Main entry point of the application.""" pass <commit_msg>Connect the UI to the code and start to connect slots to actions.<commit_after>import sys from PyQt4.QtGui import QApplication, QMainWindow from kodos.ui.ui_main import Ui_MainWindow class KodosMainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(KodosMainWindow, self).__init__(parent) self.setupUi(self) self.connectActions() # Trigger the textChanged signal for widget in [self.regexText, self.searchText, self.replaceText]: widget.setPlainText('') def connectActions(self): # Connect input widgets to update the GUI when their text change for widget in [self.regexText, self.searchText, self.replaceText]: widget.textChanged.connect(self.on_compute_regex) def on_compute_regex(self): regex = self.regexText.toPlainText() search = self.searchText.toPlainText() replace = self.replaceText.toPlainText() if regex == "" or search == "": self.statusbar.showMessage( "Please enter a regex and a search to work on") else: self.statusbar.clearMessage() def run(args=None): """Main entry point of the application.""" app = QApplication(sys.argv) kodos = KodosMainWindow() kodos.show() app.exec_()
c2a69c18085d4f9ee932465e143fe051037d98db
util/output_pipe.py
util/output_pipe.py
import sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than # exitcode def __init__(self, verbose = True, pretty = True, unacceptable_output=[]): self.verbose = verbose self.pretty = pretty self.unacceptable_output = unacceptable_output def put_line(self, line): m_line = MetaLine(line) self.meta_lines.append(m_line) if self.verbose: if self.pretty: output = m_line.str() else: output = line sys.stdout.write(output) for uo in self.unacceptable_output: if re.compile(uo).match(line): raise TestFailureError(line)
import sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than # exitcode def __init__(self, verbose = True, pretty = True, unacceptable_output=[]): self.verbose = verbose self.pretty = pretty self.unacceptable_output = unacceptable_output self.meta_lines = [] def put_line(self, line): m_line = MetaLine(line) self.meta_lines.append(m_line) if self.verbose: if self.pretty: output = m_line.str() else: output = line sys.stdout.write(output) for uo in self.unacceptable_output: if re.compile(uo).match(line): raise TestFailureError(line)
Fix bug where previous instances would populate the new OutputPipe
Fix bug where previous instances would populate the new OutputPipe
Python
mit
JBarberU/strawberry_py
import sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than # exitcode def __init__(self, verbose = True, pretty = True, unacceptable_output=[]): self.verbose = verbose self.pretty = pretty self.unacceptable_output = unacceptable_output def put_line(self, line): m_line = MetaLine(line) self.meta_lines.append(m_line) if self.verbose: if self.pretty: output = m_line.str() else: output = line sys.stdout.write(output) for uo in self.unacceptable_output: if re.compile(uo).match(line): raise TestFailureError(line) Fix bug where previous instances would populate the new OutputPipe
import sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than # exitcode def __init__(self, verbose = True, pretty = True, unacceptable_output=[]): self.verbose = verbose self.pretty = pretty self.unacceptable_output = unacceptable_output self.meta_lines = [] def put_line(self, line): m_line = MetaLine(line) self.meta_lines.append(m_line) if self.verbose: if self.pretty: output = m_line.str() else: output = line sys.stdout.write(output) for uo in self.unacceptable_output: if re.compile(uo).match(line): raise TestFailureError(line)
<commit_before>import sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than # exitcode def __init__(self, verbose = True, pretty = True, unacceptable_output=[]): self.verbose = verbose self.pretty = pretty self.unacceptable_output = unacceptable_output def put_line(self, line): m_line = MetaLine(line) self.meta_lines.append(m_line) if self.verbose: if self.pretty: output = m_line.str() else: output = line sys.stdout.write(output) for uo in self.unacceptable_output: if re.compile(uo).match(line): raise TestFailureError(line) <commit_msg>Fix bug where previous instances would populate the new OutputPipe<commit_after>
import sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than # exitcode def __init__(self, verbose = True, pretty = True, unacceptable_output=[]): self.verbose = verbose self.pretty = pretty self.unacceptable_output = unacceptable_output self.meta_lines = [] def put_line(self, line): m_line = MetaLine(line) self.meta_lines.append(m_line) if self.verbose: if self.pretty: output = m_line.str() else: output = line sys.stdout.write(output) for uo in self.unacceptable_output: if re.compile(uo).match(line): raise TestFailureError(line)
import sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than # exitcode def __init__(self, verbose = True, pretty = True, unacceptable_output=[]): self.verbose = verbose self.pretty = pretty self.unacceptable_output = unacceptable_output def put_line(self, line): m_line = MetaLine(line) self.meta_lines.append(m_line) if self.verbose: if self.pretty: output = m_line.str() else: output = line sys.stdout.write(output) for uo in self.unacceptable_output: if re.compile(uo).match(line): raise TestFailureError(line) Fix bug where previous instances would populate the new OutputPipeimport sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than # exitcode def __init__(self, verbose = True, pretty = True, unacceptable_output=[]): self.verbose = verbose self.pretty = pretty self.unacceptable_output = unacceptable_output self.meta_lines = [] def put_line(self, line): m_line = MetaLine(line) self.meta_lines.append(m_line) if self.verbose: if self.pretty: output = m_line.str() else: output = line sys.stdout.write(output) for uo in self.unacceptable_output: if re.compile(uo).match(line): raise TestFailureError(line)
<commit_before>import sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than # exitcode def __init__(self, verbose = True, pretty = True, unacceptable_output=[]): self.verbose = verbose self.pretty = pretty self.unacceptable_output = unacceptable_output def put_line(self, line): m_line = MetaLine(line) self.meta_lines.append(m_line) if self.verbose: if self.pretty: output = m_line.str() else: output = line sys.stdout.write(output) for uo in self.unacceptable_output: if re.compile(uo).match(line): raise TestFailureError(line) <commit_msg>Fix bug where previous instances would populate the new OutputPipe<commit_after>import sys import re from xc_exception import TestFailureError from colors import Colors from meta_line import MetaLine from line import Line class OutputPipe: meta_lines = [] verbose = True pretty = True unacceptable_output = [] # unacceptable_output is usful for failing based on command output, rather than # exitcode def __init__(self, verbose = True, pretty = True, unacceptable_output=[]): self.verbose = verbose self.pretty = pretty self.unacceptable_output = unacceptable_output self.meta_lines = [] def put_line(self, line): m_line = MetaLine(line) self.meta_lines.append(m_line) if self.verbose: if self.pretty: output = m_line.str() else: output = line sys.stdout.write(output) for uo in self.unacceptable_output: if re.compile(uo).match(line): raise TestFailureError(line)
5c3c681d60a3d747728d337358455cf00b905e43
utils/message_parsing.py
utils/message_parsing.py
from typing import Tuple, List import shlex import discord def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return str def get_args(msg: discord.Message) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = ' '.join(msg.suffix.split(' ', 1)[1:]) clean_suffix = ' '.join(msg.clean_suffix.split(' ', 1)[1:]) args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] clean_args = shlex.split(clean_suffix.replace('\"', '\u009E').replace(r"\'", '\u009F')) clean_args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in clean_args] return suffix, clean_suffix, args, clean_args
from typing import Tuple, List import shlex def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return string def get_args(string: str) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = string.split(' ', 1)[1:] args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] return suffix, args
Change message parsing to not break on prefixes with spaces. May find a way to bring back clean suffix and clean args.
Change message parsing to not break on prefixes with spaces. May find a way to bring back clean suffix and clean args.
Python
mit
HexadecimalPython/Xeili,awau/Amethyst
from typing import Tuple, List import shlex import discord def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return str def get_args(msg: discord.Message) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = ' '.join(msg.suffix.split(' ', 1)[1:]) clean_suffix = ' '.join(msg.clean_suffix.split(' ', 1)[1:]) args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] clean_args = shlex.split(clean_suffix.replace('\"', '\u009E').replace(r"\'", '\u009F')) clean_args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in clean_args] return suffix, clean_suffix, args, clean_args Change message parsing to not break on prefixes with spaces. May find a way to bring back clean suffix and clean args.
from typing import Tuple, List import shlex def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return string def get_args(string: str) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = string.split(' ', 1)[1:] args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] return suffix, args
<commit_before>from typing import Tuple, List import shlex import discord def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return str def get_args(msg: discord.Message) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = ' '.join(msg.suffix.split(' ', 1)[1:]) clean_suffix = ' '.join(msg.clean_suffix.split(' ', 1)[1:]) args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] clean_args = shlex.split(clean_suffix.replace('\"', '\u009E').replace(r"\'", '\u009F')) clean_args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in clean_args] return suffix, clean_suffix, args, clean_args <commit_msg>Change message parsing to not break on prefixes with spaces. May find a way to bring back clean suffix and clean args.<commit_after>
from typing import Tuple, List import shlex def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return string def get_args(string: str) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = string.split(' ', 1)[1:] args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] return suffix, args
from typing import Tuple, List import shlex import discord def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return str def get_args(msg: discord.Message) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = ' '.join(msg.suffix.split(' ', 1)[1:]) clean_suffix = ' '.join(msg.clean_suffix.split(' ', 1)[1:]) args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] clean_args = shlex.split(clean_suffix.replace('\"', '\u009E').replace(r"\'", '\u009F')) clean_args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in clean_args] return suffix, clean_suffix, args, clean_args Change message parsing to not break on prefixes with spaces. May find a way to bring back clean suffix and clean args.from typing import Tuple, List import shlex def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return string def get_args(string: str) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = string.split(' ', 1)[1:] args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] return suffix, args
<commit_before>from typing import Tuple, List import shlex import discord def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return str def get_args(msg: discord.Message) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = ' '.join(msg.suffix.split(' ', 1)[1:]) clean_suffix = ' '.join(msg.clean_suffix.split(' ', 1)[1:]) args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] clean_args = shlex.split(clean_suffix.replace('\"', '\u009E').replace(r"\'", '\u009F')) clean_args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in clean_args] return suffix, clean_suffix, args, clean_args <commit_msg>Change message parsing to not break on prefixes with spaces. May find a way to bring back clean suffix and clean args.<commit_after>from typing import Tuple, List import shlex def get_cmd(string: str) -> str: '''Gets the command name from a string.''' return string.split(' ')[0] def parse_prefixes(string: str, prefixes: List[str]) -> str: '''Cleans the prefixes off a string.''' for prefix in prefixes: if string.startswith(prefix): string = string[len(prefix):] break return string def get_args(string: str) -> Tuple[str, str, Tuple[str, ...], Tuple[str, ...]]: '''Parses a message to get args and suffix.''' suffix = string.split(' ', 1)[1:] args = shlex.split(suffix.replace(r'\"', '\u009E').replace(r"\'", '\u009F')) args = [x.replace('\u009E', '"').replace('\u009F', "'") for x in args] return suffix, args
46573f40e841141e2aa3f813a6938460a92511c1
devtools/scripts/build_cookiecutter_json.py
devtools/scripts/build_cookiecutter_json.py
import sys import json release_tag = sys.argv[1] python_version = sys.argv[2] ci_os = sys.argv[3] platform_mapping = { "ubuntu-latest": "linux-64", "macOS-latest": "osx-64", } data = { "name": "openforcefield", "channel": "omnia", "python": python_version, "platform": platform_mapping[ci_os], "release": release_tag, } with open("new_cookiecutter.json", "w") as fp: json.dump(data, fp)
import sys import json release_tag = sys.argv[1] python_version = sys.argv[2] ci_os = sys.argv[3] platform_mapping = { "ubuntu-latest": "linux-64", "macOS-latest": "osx-64", } data = { "name": "openforcefield", "channel": "omnia", "python": [python_version], "platform": [platform_mapping[ci_os]], "release": release_tag, } with open("new_cookiecutter.json", "w") as fp: json.dump(data, fp)
Change platform and python fields to lists
Change platform and python fields to lists
Python
mit
open-forcefield-group/openforcefield,open-forcefield-group/openforcefield,openforcefield/openff-toolkit,open-forcefield-group/openforcefield,openforcefield/openff-toolkit
import sys import json release_tag = sys.argv[1] python_version = sys.argv[2] ci_os = sys.argv[3] platform_mapping = { "ubuntu-latest": "linux-64", "macOS-latest": "osx-64", } data = { "name": "openforcefield", "channel": "omnia", "python": python_version, "platform": platform_mapping[ci_os], "release": release_tag, } with open("new_cookiecutter.json", "w") as fp: json.dump(data, fp) Change platform and python fields to lists
import sys import json release_tag = sys.argv[1] python_version = sys.argv[2] ci_os = sys.argv[3] platform_mapping = { "ubuntu-latest": "linux-64", "macOS-latest": "osx-64", } data = { "name": "openforcefield", "channel": "omnia", "python": [python_version], "platform": [platform_mapping[ci_os]], "release": release_tag, } with open("new_cookiecutter.json", "w") as fp: json.dump(data, fp)
<commit_before>import sys import json release_tag = sys.argv[1] python_version = sys.argv[2] ci_os = sys.argv[3] platform_mapping = { "ubuntu-latest": "linux-64", "macOS-latest": "osx-64", } data = { "name": "openforcefield", "channel": "omnia", "python": python_version, "platform": platform_mapping[ci_os], "release": release_tag, } with open("new_cookiecutter.json", "w") as fp: json.dump(data, fp) <commit_msg>Change platform and python fields to lists<commit_after>
import sys import json release_tag = sys.argv[1] python_version = sys.argv[2] ci_os = sys.argv[3] platform_mapping = { "ubuntu-latest": "linux-64", "macOS-latest": "osx-64", } data = { "name": "openforcefield", "channel": "omnia", "python": [python_version], "platform": [platform_mapping[ci_os]], "release": release_tag, } with open("new_cookiecutter.json", "w") as fp: json.dump(data, fp)
import sys import json release_tag = sys.argv[1] python_version = sys.argv[2] ci_os = sys.argv[3] platform_mapping = { "ubuntu-latest": "linux-64", "macOS-latest": "osx-64", } data = { "name": "openforcefield", "channel": "omnia", "python": python_version, "platform": platform_mapping[ci_os], "release": release_tag, } with open("new_cookiecutter.json", "w") as fp: json.dump(data, fp) Change platform and python fields to listsimport sys import json release_tag = sys.argv[1] python_version = sys.argv[2] ci_os = sys.argv[3] platform_mapping = { "ubuntu-latest": "linux-64", "macOS-latest": "osx-64", } data = { "name": "openforcefield", "channel": "omnia", "python": [python_version], "platform": [platform_mapping[ci_os]], "release": release_tag, } with open("new_cookiecutter.json", "w") as fp: json.dump(data, fp)
<commit_before>import sys import json release_tag = sys.argv[1] python_version = sys.argv[2] ci_os = sys.argv[3] platform_mapping = { "ubuntu-latest": "linux-64", "macOS-latest": "osx-64", } data = { "name": "openforcefield", "channel": "omnia", "python": python_version, "platform": platform_mapping[ci_os], "release": release_tag, } with open("new_cookiecutter.json", "w") as fp: json.dump(data, fp) <commit_msg>Change platform and python fields to lists<commit_after>import sys import json release_tag = sys.argv[1] python_version = sys.argv[2] ci_os = sys.argv[3] platform_mapping = { "ubuntu-latest": "linux-64", "macOS-latest": "osx-64", } data = { "name": "openforcefield", "channel": "omnia", "python": [python_version], "platform": [platform_mapping[ci_os]], "release": release_tag, } with open("new_cookiecutter.json", "w") as fp: json.dump(data, fp)
c4feb85d3f1f0151b7a64705a555d98221d6d857
setup-utils/data_upgrade_from_0.4.py
setup-utils/data_upgrade_from_0.4.py
# This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db") args = argumentParser.parse_args() storage = None try: storage = shelve.open(args.datafile) except Exception as err: print("Error opening data file: {}".format(err)) sys.exit(1) # SECTION: Upgrade whowas time format from datetime import datetime whowasEntries = storage["whowas"] for whowasEntryList in whowasEntries.itervalues(): for whowasEntry in whowasEntryList: when = whowasEntry["when"] whowasEntry["when"] = datetime.utcfromtimestamp(when) # SHUTDOWN: Close data.db storage.close()
# This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db") args = argumentParser.parse_args() storage = None try: storage = shelve.open(args.datafile) except Exception as err: print("Error opening data file: {}".format(err)) sys.exit(1) # SECTION: Upgrade whowas time format and add real host and IP keys from datetime import datetime whowasEntries = storage["whowas"] for whowasEntryList in whowasEntries.itervalues(): for whowasEntry in whowasEntryList: when = whowasEntry["when"] whowasEntry["when"] = datetime.utcfromtimestamp(when) whowasEntry["realhost"] = whowasEntry["host"] whowasEntry["ip"] = "0.0.0.0" # SHUTDOWN: Close data.db storage.close()
Add new WHOWAS keys when upgrading the data to 0.5
Add new WHOWAS keys when upgrading the data to 0.5
Python
bsd-3-clause
Heufneutje/txircd
# This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db") args = argumentParser.parse_args() storage = None try: storage = shelve.open(args.datafile) except Exception as err: print("Error opening data file: {}".format(err)) sys.exit(1) # SECTION: Upgrade whowas time format from datetime import datetime whowasEntries = storage["whowas"] for whowasEntryList in whowasEntries.itervalues(): for whowasEntry in whowasEntryList: when = whowasEntry["when"] whowasEntry["when"] = datetime.utcfromtimestamp(when) # SHUTDOWN: Close data.db storage.close()Add new WHOWAS keys when upgrading the data to 0.5
# This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db") args = argumentParser.parse_args() storage = None try: storage = shelve.open(args.datafile) except Exception as err: print("Error opening data file: {}".format(err)) sys.exit(1) # SECTION: Upgrade whowas time format and add real host and IP keys from datetime import datetime whowasEntries = storage["whowas"] for whowasEntryList in whowasEntries.itervalues(): for whowasEntry in whowasEntryList: when = whowasEntry["when"] whowasEntry["when"] = datetime.utcfromtimestamp(when) whowasEntry["realhost"] = whowasEntry["host"] whowasEntry["ip"] = "0.0.0.0" # SHUTDOWN: Close data.db storage.close()
<commit_before># This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db") args = argumentParser.parse_args() storage = None try: storage = shelve.open(args.datafile) except Exception as err: print("Error opening data file: {}".format(err)) sys.exit(1) # SECTION: Upgrade whowas time format from datetime import datetime whowasEntries = storage["whowas"] for whowasEntryList in whowasEntries.itervalues(): for whowasEntry in whowasEntryList: when = whowasEntry["when"] whowasEntry["when"] = datetime.utcfromtimestamp(when) # SHUTDOWN: Close data.db storage.close()<commit_msg>Add new WHOWAS keys when upgrading the data to 0.5<commit_after>
# This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db") args = argumentParser.parse_args() storage = None try: storage = shelve.open(args.datafile) except Exception as err: print("Error opening data file: {}".format(err)) sys.exit(1) # SECTION: Upgrade whowas time format and add real host and IP keys from datetime import datetime whowasEntries = storage["whowas"] for whowasEntryList in whowasEntries.itervalues(): for whowasEntry in whowasEntryList: when = whowasEntry["when"] whowasEntry["when"] = datetime.utcfromtimestamp(when) whowasEntry["realhost"] = whowasEntry["host"] whowasEntry["ip"] = "0.0.0.0" # SHUTDOWN: Close data.db storage.close()
# This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db") args = argumentParser.parse_args() storage = None try: storage = shelve.open(args.datafile) except Exception as err: print("Error opening data file: {}".format(err)) sys.exit(1) # SECTION: Upgrade whowas time format from datetime import datetime whowasEntries = storage["whowas"] for whowasEntryList in whowasEntries.itervalues(): for whowasEntry in whowasEntryList: when = whowasEntry["when"] whowasEntry["when"] = datetime.utcfromtimestamp(when) # SHUTDOWN: Close data.db storage.close()Add new WHOWAS keys when upgrading the data to 0.5# This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db") args = argumentParser.parse_args() storage = None try: storage = shelve.open(args.datafile) except Exception as err: print("Error opening data file: {}".format(err)) sys.exit(1) # SECTION: Upgrade whowas time format and add real host and IP keys from datetime import datetime whowasEntries = storage["whowas"] for whowasEntryList in whowasEntries.itervalues(): for whowasEntry in whowasEntryList: when = whowasEntry["when"] whowasEntry["when"] = datetime.utcfromtimestamp(when) whowasEntry["realhost"] = whowasEntry["host"] whowasEntry["ip"] = "0.0.0.0" # SHUTDOWN: Close data.db storage.close()
<commit_before># This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db") args = argumentParser.parse_args() storage = None try: storage = shelve.open(args.datafile) except Exception as err: print("Error opening data file: {}".format(err)) sys.exit(1) # SECTION: Upgrade whowas time format from datetime import datetime whowasEntries = storage["whowas"] for whowasEntryList in whowasEntries.itervalues(): for whowasEntry in whowasEntryList: when = whowasEntry["when"] whowasEntry["when"] = datetime.utcfromtimestamp(when) # SHUTDOWN: Close data.db storage.close()<commit_msg>Add new WHOWAS keys when upgrading the data to 0.5<commit_after># This file upgrades data.db from the 0.4 format data to 0.5 format data. # SETUP: Open data.db import argparse, shelve, sys argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.") argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db") args = argumentParser.parse_args() storage = None try: storage = shelve.open(args.datafile) except Exception as err: print("Error opening data file: {}".format(err)) sys.exit(1) # SECTION: Upgrade whowas time format and add real host and IP keys from datetime import datetime whowasEntries = storage["whowas"] for whowasEntryList in whowasEntries.itervalues(): for whowasEntry in whowasEntryList: when = whowasEntry["when"] whowasEntry["when"] = datetime.utcfromtimestamp(when) whowasEntry["realhost"] = whowasEntry["host"] whowasEntry["ip"] = "0.0.0.0" # SHUTDOWN: Close data.db storage.close()
08b1f3f64580f99ffb18261ab0e9fc691bc3dd67
rpifake/__init__.py
rpifake/__init__.py
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } patcher = mock.patch.dict('sys.modules', modules) patcher.start() # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
Make override more global, not just within patch scope
Make override more global, not just within patch scope
Python
mit
rfarley3/lcd-restful,rfarley3/lcd-restful
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } patcher = mock.patch.dict('sys.modules', modules) patcher.start() # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere Make override more global, not just within patch scope
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
<commit_before># After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } patcher = mock.patch.dict('sys.modules', modules) patcher.start() # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere <commit_msg>Make override more global, not just within patch scope<commit_after>
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } patcher = mock.patch.dict('sys.modules', modules) patcher.start() # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere Make override more global, not just within patch scope# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
<commit_before># After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } patcher = mock.patch.dict('sys.modules', modules) patcher.start() # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere <commit_msg>Make override more global, not just within patch scope<commit_after># After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
5beba531b85d719039c2faf371d83d2957cea5c3
rpifake/__init__.py
rpifake/__init__.py
from __future__ import print_function import sys is_active = False # After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): import sys import mock from .gpio import Gpio as FakeGpio global is_active print('Warning, not in RPi, using mock GPIO', file=sys.stderr) # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Test if we have RPi.GPIO or not rpi_gpio_exists = False if sys.version_info < (3,): import imp try: imp.find_module('RPi') except ImportError: rpi_gpio_exists = False else: import importlib.util if importlib.util.find_spec('RPi') is not None: rpi_gpio_exists = False if not rpi_gpio_exists: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
from __future__ import print_function import sys is_active = False # After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): import sys import mock from .gpio import Gpio as FakeGpio global is_active print('Warning, not in RPi, using mock GPIO', file=sys.stderr) # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Test if we have RPi.GPIO or not rpi_gpio_exists = True if sys.version_info < (3,): import imp try: imp.find_module('RPi') except ImportError: rpi_gpio_exists = False else: import importlib.util if importlib.util.find_spec('RPi') is None: rpi_gpio_exists = False if not rpi_gpio_exists: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
Fix bad logic for missing RPi package
Fix bad logic for missing RPi package
Python
mit
rfarley3/lcd-restful,rfarley3/lcd-restful
from __future__ import print_function import sys is_active = False # After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): import sys import mock from .gpio import Gpio as FakeGpio global is_active print('Warning, not in RPi, using mock GPIO', file=sys.stderr) # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Test if we have RPi.GPIO or not rpi_gpio_exists = False if sys.version_info < (3,): import imp try: imp.find_module('RPi') except ImportError: rpi_gpio_exists = False else: import importlib.util if importlib.util.find_spec('RPi') is not None: rpi_gpio_exists = False if not rpi_gpio_exists: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere Fix bad logic for missing RPi package
from __future__ import print_function import sys is_active = False # After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): import sys import mock from .gpio import Gpio as FakeGpio global is_active print('Warning, not in RPi, using mock GPIO', file=sys.stderr) # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Test if we have RPi.GPIO or not rpi_gpio_exists = True if sys.version_info < (3,): import imp try: imp.find_module('RPi') except ImportError: rpi_gpio_exists = False else: import importlib.util if importlib.util.find_spec('RPi') is None: rpi_gpio_exists = False if not rpi_gpio_exists: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
<commit_before>from __future__ import print_function import sys is_active = False # After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): import sys import mock from .gpio import Gpio as FakeGpio global is_active print('Warning, not in RPi, using mock GPIO', file=sys.stderr) # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Test if we have RPi.GPIO or not rpi_gpio_exists = False if sys.version_info < (3,): import imp try: imp.find_module('RPi') except ImportError: rpi_gpio_exists = False else: import importlib.util if importlib.util.find_spec('RPi') is not None: rpi_gpio_exists = False if not rpi_gpio_exists: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere <commit_msg>Fix bad logic for missing RPi package<commit_after>
from __future__ import print_function import sys is_active = False # After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): import sys import mock from .gpio import Gpio as FakeGpio global is_active print('Warning, not in RPi, using mock GPIO', file=sys.stderr) # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Test if we have RPi.GPIO or not rpi_gpio_exists = True if sys.version_info < (3,): import imp try: imp.find_module('RPi') except ImportError: rpi_gpio_exists = False else: import importlib.util if importlib.util.find_spec('RPi') is None: rpi_gpio_exists = False if not rpi_gpio_exists: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
from __future__ import print_function import sys is_active = False # After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): import sys import mock from .gpio import Gpio as FakeGpio global is_active print('Warning, not in RPi, using mock GPIO', file=sys.stderr) # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Test if we have RPi.GPIO or not rpi_gpio_exists = False if sys.version_info < (3,): import imp try: imp.find_module('RPi') except ImportError: rpi_gpio_exists = False else: import importlib.util if importlib.util.find_spec('RPi') is not None: rpi_gpio_exists = False if not rpi_gpio_exists: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere Fix bad logic for missing RPi packagefrom __future__ import print_function import sys is_active = False # After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): import sys import mock from .gpio import Gpio as FakeGpio global is_active print('Warning, not in RPi, using mock GPIO', file=sys.stderr) # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Test if we have RPi.GPIO or not rpi_gpio_exists = True if sys.version_info < (3,): import imp try: imp.find_module('RPi') except ImportError: rpi_gpio_exists = False else: import importlib.util if importlib.util.find_spec('RPi') is None: rpi_gpio_exists = False if not rpi_gpio_exists: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
<commit_before>from __future__ import print_function import sys is_active = False # After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): import sys import mock from .gpio import Gpio as FakeGpio global is_active print('Warning, not in RPi, using mock GPIO', file=sys.stderr) # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Test if we have RPi.GPIO or not rpi_gpio_exists = False if sys.version_info < (3,): import imp try: imp.find_module('RPi') except ImportError: rpi_gpio_exists = False else: import importlib.util if importlib.util.find_spec('RPi') is not None: rpi_gpio_exists = False if not rpi_gpio_exists: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere <commit_msg>Fix bad logic for missing RPi package<commit_after>from __future__ import print_function import sys is_active = False # After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): import sys import mock from .gpio import Gpio as FakeGpio global is_active print('Warning, not in RPi, using mock GPIO', file=sys.stderr) # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Test if we have RPi.GPIO or not rpi_gpio_exists = True if sys.version_info < (3,): import imp try: imp.find_module('RPi') except ImportError: rpi_gpio_exists = False else: import importlib.util if importlib.util.find_spec('RPi') is None: rpi_gpio_exists = False if not rpi_gpio_exists: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
1d0ac568776798a032906d91c913240dabfd403b
twitter_streaming.py
twitter_streaming.py
# Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream with open('twitter_api_key.txt') as fileHandle: (access_token, access_token_secret, consumer_key, consumer_secret) = \ [item.strip('\n') for item in fileHandle.readlines()] print access_token print access_token_secret print consumer_key print consumer_secret keywords = ['python', 'javascript', 'ruby'] # This is a basic listener that prints received tweets to stdout class StdOutListener(StreamListener): def on_data(self, data): print data return True def on_error(self, status): print status if __name__ == "__main__": # Handle Twitter authentication and connection to Twitter Streaming API listener = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, listener) # Filter Twitter stream according to keywords stream.filter(track = keywords)
# Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. # The details of using Tweepy with the Twitter streaming API is in: # http://docs.tweepy.org/en/v3.4.0/streaming_how_to.html from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream # Read the Twitter API key data from a file (not in the repository) with open('twitter_api_key.txt') as fileHandle: (access_token, access_token_secret, consumer_key, consumer_secret) = \ [item.strip('\n') for item in fileHandle.readlines()] # Set the keywords to filter the Twitter stream for keywords = ['python', 'javascript', 'ruby'] # This is a basic listener that prints received tweets to stdout # Over-ride the tweepy.Stream listener to provide methods class StdOutListener(StreamListener): def on_data(self, data): print data return True def on_error(self, status): print status if status == 420: return False return False sys.exit(1) if __name__ == "__main__": # Handle Twitter authentication and connection to Twitter Streaming API listener = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, listener) # Filter Twitter stream according to keywords stream.filter(track = keywords)
Stop on error from streaming API
Stop on error from streaming API
Python
mit
0x7df/twitter2pocket
# Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream with open('twitter_api_key.txt') as fileHandle: (access_token, access_token_secret, consumer_key, consumer_secret) = \ [item.strip('\n') for item in fileHandle.readlines()] print access_token print access_token_secret print consumer_key print consumer_secret keywords = ['python', 'javascript', 'ruby'] # This is a basic listener that prints received tweets to stdout class StdOutListener(StreamListener): def on_data(self, data): print data return True def on_error(self, status): print status if __name__ == "__main__": # Handle Twitter authentication and connection to Twitter Streaming API listener = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, listener) # Filter Twitter stream according to keywords stream.filter(track = keywords) Stop on error from streaming API
# Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. # The details of using Tweepy with the Twitter streaming API is in: # http://docs.tweepy.org/en/v3.4.0/streaming_how_to.html from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream # Read the Twitter API key data from a file (not in the repository) with open('twitter_api_key.txt') as fileHandle: (access_token, access_token_secret, consumer_key, consumer_secret) = \ [item.strip('\n') for item in fileHandle.readlines()] # Set the keywords to filter the Twitter stream for keywords = ['python', 'javascript', 'ruby'] # This is a basic listener that prints received tweets to stdout # Over-ride the tweepy.Stream listener to provide methods class StdOutListener(StreamListener): def on_data(self, data): print data return True def on_error(self, status): print status if status == 420: return False return False sys.exit(1) if __name__ == "__main__": # Handle Twitter authentication and connection to Twitter Streaming API listener = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, listener) # Filter Twitter stream according to keywords stream.filter(track = keywords)
<commit_before># Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream with open('twitter_api_key.txt') as fileHandle: (access_token, access_token_secret, consumer_key, consumer_secret) = \ [item.strip('\n') for item in fileHandle.readlines()] print access_token print access_token_secret print consumer_key print consumer_secret keywords = ['python', 'javascript', 'ruby'] # This is a basic listener that prints received tweets to stdout class StdOutListener(StreamListener): def on_data(self, data): print data return True def on_error(self, status): print status if __name__ == "__main__": # Handle Twitter authentication and connection to Twitter Streaming API listener = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, listener) # Filter Twitter stream according to keywords stream.filter(track = keywords) <commit_msg>Stop on error from streaming API<commit_after>
# Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. # The details of using Tweepy with the Twitter streaming API is in: # http://docs.tweepy.org/en/v3.4.0/streaming_how_to.html from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream # Read the Twitter API key data from a file (not in the repository) with open('twitter_api_key.txt') as fileHandle: (access_token, access_token_secret, consumer_key, consumer_secret) = \ [item.strip('\n') for item in fileHandle.readlines()] # Set the keywords to filter the Twitter stream for keywords = ['python', 'javascript', 'ruby'] # This is a basic listener that prints received tweets to stdout # Over-ride the tweepy.Stream listener to provide methods class StdOutListener(StreamListener): def on_data(self, data): print data return True def on_error(self, status): print status if status == 420: return False return False sys.exit(1) if __name__ == "__main__": # Handle Twitter authentication and connection to Twitter Streaming API listener = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, listener) # Filter Twitter stream according to keywords stream.filter(track = keywords)
# Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream with open('twitter_api_key.txt') as fileHandle: (access_token, access_token_secret, consumer_key, consumer_secret) = \ [item.strip('\n') for item in fileHandle.readlines()] print access_token print access_token_secret print consumer_key print consumer_secret keywords = ['python', 'javascript', 'ruby'] # This is a basic listener that prints received tweets to stdout class StdOutListener(StreamListener): def on_data(self, data): print data return True def on_error(self, status): print status if __name__ == "__main__": # Handle Twitter authentication and connection to Twitter Streaming API listener = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, listener) # Filter Twitter stream according to keywords stream.filter(track = keywords) Stop on error from streaming API# Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. # The details of using Tweepy with the Twitter streaming API is in: # http://docs.tweepy.org/en/v3.4.0/streaming_how_to.html from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream # Read the Twitter API key data from a file (not in the repository) with open('twitter_api_key.txt') as fileHandle: (access_token, access_token_secret, consumer_key, consumer_secret) = \ [item.strip('\n') for item in fileHandle.readlines()] # Set the keywords to filter the Twitter stream for keywords = ['python', 'javascript', 'ruby'] # This is a basic listener that prints received tweets to stdout # Over-ride the tweepy.Stream listener to provide methods class StdOutListener(StreamListener): def on_data(self, data): print data return True def on_error(self, status): print status if status == 420: return False return False sys.exit(1) if __name__ == "__main__": # Handle Twitter authentication and connection to Twitter Streaming API listener = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, listener) # Filter Twitter stream according to keywords stream.filter(track = keywords)
<commit_before># Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream with open('twitter_api_key.txt') as fileHandle: (access_token, access_token_secret, consumer_key, consumer_secret) = \ [item.strip('\n') for item in fileHandle.readlines()] print access_token print access_token_secret print consumer_key print consumer_secret keywords = ['python', 'javascript', 'ruby'] # This is a basic listener that prints received tweets to stdout class StdOutListener(StreamListener): def on_data(self, data): print data return True def on_error(self, status): print status if __name__ == "__main__": # Handle Twitter authentication and connection to Twitter Streaming API listener = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, listener) # Filter Twitter stream according to keywords stream.filter(track = keywords) <commit_msg>Stop on error from streaming API<commit_after># Pipe the output of this to file, e.g.: # # `python twitter_streaming.py > twitter_data.txt` # # The output is in JSON format. # This uses Tweepy, a Python library for accessing the Twitter API: # http://www.tweepy.org. Install with `pip install tweepy`. # The details of using Tweepy with the Twitter streaming API is in: # http://docs.tweepy.org/en/v3.4.0/streaming_how_to.html from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream # Read the Twitter API key data from a file (not in the repository) with open('twitter_api_key.txt') as fileHandle: (access_token, access_token_secret, consumer_key, consumer_secret) = \ [item.strip('\n') for item in fileHandle.readlines()] # Set the keywords to filter the Twitter stream for keywords = ['python', 'javascript', 'ruby'] # This is a basic listener that prints received tweets to stdout # Over-ride the tweepy.Stream listener to provide methods class StdOutListener(StreamListener): def on_data(self, data): print data return True def on_error(self, status): print status if status == 420: return False return False sys.exit(1) if __name__ == "__main__": # Handle Twitter authentication and connection to Twitter Streaming API listener = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, listener) # Filter Twitter stream according to keywords stream.filter(track = keywords)
a147d7cdd8ff3141ceea0f6902c2f664928f7b65
vocab.py
vocab.py
import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: print json.dumps(result, indent=4, sort_keys=True) else: json.dump(result, sys.stdout) class airtable: """Sync lists to Airtable""" def load(self, list_url, endpoint, key): airtable = Airtable(endpoint, key) words = VocabularyCom().collect(list_url) airtable.load(words) print 'List loaded to Airtable.' if __name__ == '__main__': fire.Fire(CLI)
import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: print json.dumps(result, indent=4, sort_keys=True) else: json.dump(result, sys.stdout) class airtable: """Sync lists to Airtable""" def load(self, list_url, endpoint, key): airtable = Airtable(endpoint, key) words = VocabularyCom().collect(list_url) airtable.load(words) print 'List loaded to Airtable.' def load_from_stdin(self, endpoint, key): words = json.load(sys.stdin) airtable = Airtable(endpoint, key) airtable.load(words) print 'List loaded to Airtable.' if __name__ == '__main__': fire.Fire(CLI)
Allow reading word list from stdin.
Allow reading word list from stdin.
Python
mit
zqureshi/vocab
import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: print json.dumps(result, indent=4, sort_keys=True) else: json.dump(result, sys.stdout) class airtable: """Sync lists to Airtable""" def load(self, list_url, endpoint, key): airtable = Airtable(endpoint, key) words = VocabularyCom().collect(list_url) airtable.load(words) print 'List loaded to Airtable.' if __name__ == '__main__': fire.Fire(CLI) Allow reading word list from stdin.
import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: print json.dumps(result, indent=4, sort_keys=True) else: json.dump(result, sys.stdout) class airtable: """Sync lists to Airtable""" def load(self, list_url, endpoint, key): airtable = Airtable(endpoint, key) words = VocabularyCom().collect(list_url) airtable.load(words) print 'List loaded to Airtable.' def load_from_stdin(self, endpoint, key): words = json.load(sys.stdin) airtable = Airtable(endpoint, key) airtable.load(words) print 'List loaded to Airtable.' if __name__ == '__main__': fire.Fire(CLI)
<commit_before>import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: print json.dumps(result, indent=4, sort_keys=True) else: json.dump(result, sys.stdout) class airtable: """Sync lists to Airtable""" def load(self, list_url, endpoint, key): airtable = Airtable(endpoint, key) words = VocabularyCom().collect(list_url) airtable.load(words) print 'List loaded to Airtable.' if __name__ == '__main__': fire.Fire(CLI) <commit_msg>Allow reading word list from stdin.<commit_after>
import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: print json.dumps(result, indent=4, sort_keys=True) else: json.dump(result, sys.stdout) class airtable: """Sync lists to Airtable""" def load(self, list_url, endpoint, key): airtable = Airtable(endpoint, key) words = VocabularyCom().collect(list_url) airtable.load(words) print 'List loaded to Airtable.' def load_from_stdin(self, endpoint, key): words = json.load(sys.stdin) airtable = Airtable(endpoint, key) airtable.load(words) print 'List loaded to Airtable.' if __name__ == '__main__': fire.Fire(CLI)
import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: print json.dumps(result, indent=4, sort_keys=True) else: json.dump(result, sys.stdout) class airtable: """Sync lists to Airtable""" def load(self, list_url, endpoint, key): airtable = Airtable(endpoint, key) words = VocabularyCom().collect(list_url) airtable.load(words) print 'List loaded to Airtable.' if __name__ == '__main__': fire.Fire(CLI) Allow reading word list from stdin.import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: print json.dumps(result, indent=4, sort_keys=True) else: json.dump(result, sys.stdout) class airtable: """Sync lists to Airtable""" def load(self, list_url, endpoint, key): airtable = Airtable(endpoint, key) words = VocabularyCom().collect(list_url) airtable.load(words) print 'List loaded to Airtable.' def load_from_stdin(self, endpoint, key): words = json.load(sys.stdin) airtable = Airtable(endpoint, key) airtable.load(words) print 'List loaded to Airtable.' if __name__ == '__main__': fire.Fire(CLI)
<commit_before>import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: print json.dumps(result, indent=4, sort_keys=True) else: json.dump(result, sys.stdout) class airtable: """Sync lists to Airtable""" def load(self, list_url, endpoint, key): airtable = Airtable(endpoint, key) words = VocabularyCom().collect(list_url) airtable.load(words) print 'List loaded to Airtable.' if __name__ == '__main__': fire.Fire(CLI) <commit_msg>Allow reading word list from stdin.<commit_after>import fire import json import sys from source import VocabularyCom from airtable import Airtable class CLI: class source: """Import word lists from various sources""" def vocabulary_com(self, list_url, pretty=False): result = VocabularyCom().collect(list_url) if pretty: print json.dumps(result, indent=4, sort_keys=True) else: json.dump(result, sys.stdout) class airtable: """Sync lists to Airtable""" def load(self, list_url, endpoint, key): airtable = Airtable(endpoint, key) words = VocabularyCom().collect(list_url) airtable.load(words) print 'List loaded to Airtable.' def load_from_stdin(self, endpoint, key): words = json.load(sys.stdin) airtable = Airtable(endpoint, key) airtable.load(words) print 'List loaded to Airtable.' if __name__ == '__main__': fire.Fire(CLI)
82a473b6b807a35cafd81d85e2c0bac71f51cb3c
src/sas/qtgui/Plotting/PlotHelper.py
src/sas/qtgui/Plotting/PlotHelper.py
""" `Singleton` plot helper module All its variables are bound to the module, which can not be instantiated repeatedly so IDs are session-specific. """ import sys # TODO Refactor to allow typing without circular import #from sas.qtgui.Plotting.PlotterBase import PlotterBase this = sys.modules[__name__] this._plots = {} this._plot_id = 0 def clear(): """ Reset the plot dictionary """ this._plots = {} #def addPlot(plot: PlotterBase): def addPlot(plot): """ Adds a new plot to the current dictionary of plots """ this._plot_id += 1 this._plots["Graph%s"%str(this._plot_id)] = plot # TODO: Why??? def deletePlot(plot_id): """ Deletes an existing plot from the dictionary """ if plot_id in this._plots: del this._plots[plot_id] def currentPlotIds(): """ Returns a list of IDs for all currently active plots """ return list(this._plots.keys()) def plotById(plot_id): """ Returns the plot referenced by the ID """ return this._plots[plot_id] if plot_id in this._plots else None def idOfPlot(plot): """ Returns the ID of the plot """ plot_id = None for key in list(this._plots.keys()): if this._plots[key] == plot: plot_id = key break return plot_id
""" `Singleton` plot helper module All its variables are bound to the module, which can not be instantiated repeatedly so IDs are session-specific. """ import sys import weakref # TODO Refactor to allow typing without circular import #from sas.qtgui.Plotting.PlotterBase import PlotterBase this = sys.modules[__name__] this._plots = weakref.WeakValueDictionary() this._plot_id = 0 def clear(): """ Reset the plot dictionary """ this._plots = weakref.WeakValueDictionary() #def addPlot(plot: PlotterBase): def addPlot(plot): """ Adds a new plot to the current dictionary of plots """ this._plot_id += 1 this._plots["Graph%s"%str(this._plot_id)] = plot # TODO: Why??? def deletePlot(plot_id): """ Deletes an existing plot from the dictionary """ if plot_id in this._plots: del this._plots[plot_id] def currentPlotIds(): """ Returns a list of IDs for all currently active plots """ return list(this._plots.keys()) def plotById(plot_id): """ Returns the plot referenced by the ID """ return this._plots[plot_id] if plot_id in this._plots else None def idOfPlot(plot): """ Returns the ID of the plot """ plot_id = None for key in list(this._plots.keys()): if this._plots[key] == plot: plot_id = key break return plot_id
Allow plots to be disposed of sooner
Allow plots to be disposed of sooner
Python
bsd-3-clause
SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview
""" `Singleton` plot helper module All its variables are bound to the module, which can not be instantiated repeatedly so IDs are session-specific. """ import sys # TODO Refactor to allow typing without circular import #from sas.qtgui.Plotting.PlotterBase import PlotterBase this = sys.modules[__name__] this._plots = {} this._plot_id = 0 def clear(): """ Reset the plot dictionary """ this._plots = {} #def addPlot(plot: PlotterBase): def addPlot(plot): """ Adds a new plot to the current dictionary of plots """ this._plot_id += 1 this._plots["Graph%s"%str(this._plot_id)] = plot # TODO: Why??? def deletePlot(plot_id): """ Deletes an existing plot from the dictionary """ if plot_id in this._plots: del this._plots[plot_id] def currentPlotIds(): """ Returns a list of IDs for all currently active plots """ return list(this._plots.keys()) def plotById(plot_id): """ Returns the plot referenced by the ID """ return this._plots[plot_id] if plot_id in this._plots else None def idOfPlot(plot): """ Returns the ID of the plot """ plot_id = None for key in list(this._plots.keys()): if this._plots[key] == plot: plot_id = key break return plot_id Allow plots to be disposed of sooner
""" `Singleton` plot helper module All its variables are bound to the module, which can not be instantiated repeatedly so IDs are session-specific. """ import sys import weakref # TODO Refactor to allow typing without circular import #from sas.qtgui.Plotting.PlotterBase import PlotterBase this = sys.modules[__name__] this._plots = weakref.WeakValueDictionary() this._plot_id = 0 def clear(): """ Reset the plot dictionary """ this._plots = weakref.WeakValueDictionary() #def addPlot(plot: PlotterBase): def addPlot(plot): """ Adds a new plot to the current dictionary of plots """ this._plot_id += 1 this._plots["Graph%s"%str(this._plot_id)] = plot # TODO: Why??? def deletePlot(plot_id): """ Deletes an existing plot from the dictionary """ if plot_id in this._plots: del this._plots[plot_id] def currentPlotIds(): """ Returns a list of IDs for all currently active plots """ return list(this._plots.keys()) def plotById(plot_id): """ Returns the plot referenced by the ID """ return this._plots[plot_id] if plot_id in this._plots else None def idOfPlot(plot): """ Returns the ID of the plot """ plot_id = None for key in list(this._plots.keys()): if this._plots[key] == plot: plot_id = key break return plot_id
<commit_before>""" `Singleton` plot helper module All its variables are bound to the module, which can not be instantiated repeatedly so IDs are session-specific. """ import sys # TODO Refactor to allow typing without circular import #from sas.qtgui.Plotting.PlotterBase import PlotterBase this = sys.modules[__name__] this._plots = {} this._plot_id = 0 def clear(): """ Reset the plot dictionary """ this._plots = {} #def addPlot(plot: PlotterBase): def addPlot(plot): """ Adds a new plot to the current dictionary of plots """ this._plot_id += 1 this._plots["Graph%s"%str(this._plot_id)] = plot # TODO: Why??? def deletePlot(plot_id): """ Deletes an existing plot from the dictionary """ if plot_id in this._plots: del this._plots[plot_id] def currentPlotIds(): """ Returns a list of IDs for all currently active plots """ return list(this._plots.keys()) def plotById(plot_id): """ Returns the plot referenced by the ID """ return this._plots[plot_id] if plot_id in this._plots else None def idOfPlot(plot): """ Returns the ID of the plot """ plot_id = None for key in list(this._plots.keys()): if this._plots[key] == plot: plot_id = key break return plot_id <commit_msg>Allow plots to be disposed of sooner<commit_after>
""" `Singleton` plot helper module All its variables are bound to the module, which can not be instantiated repeatedly so IDs are session-specific. """ import sys import weakref # TODO Refactor to allow typing without circular import #from sas.qtgui.Plotting.PlotterBase import PlotterBase this = sys.modules[__name__] this._plots = weakref.WeakValueDictionary() this._plot_id = 0 def clear(): """ Reset the plot dictionary """ this._plots = weakref.WeakValueDictionary() #def addPlot(plot: PlotterBase): def addPlot(plot): """ Adds a new plot to the current dictionary of plots """ this._plot_id += 1 this._plots["Graph%s"%str(this._plot_id)] = plot # TODO: Why??? def deletePlot(plot_id): """ Deletes an existing plot from the dictionary """ if plot_id in this._plots: del this._plots[plot_id] def currentPlotIds(): """ Returns a list of IDs for all currently active plots """ return list(this._plots.keys()) def plotById(plot_id): """ Returns the plot referenced by the ID """ return this._plots[plot_id] if plot_id in this._plots else None def idOfPlot(plot): """ Returns the ID of the plot """ plot_id = None for key in list(this._plots.keys()): if this._plots[key] == plot: plot_id = key break return plot_id
""" `Singleton` plot helper module All its variables are bound to the module, which can not be instantiated repeatedly so IDs are session-specific. """ import sys # TODO Refactor to allow typing without circular import #from sas.qtgui.Plotting.PlotterBase import PlotterBase this = sys.modules[__name__] this._plots = {} this._plot_id = 0 def clear(): """ Reset the plot dictionary """ this._plots = {} #def addPlot(plot: PlotterBase): def addPlot(plot): """ Adds a new plot to the current dictionary of plots """ this._plot_id += 1 this._plots["Graph%s"%str(this._plot_id)] = plot # TODO: Why??? def deletePlot(plot_id): """ Deletes an existing plot from the dictionary """ if plot_id in this._plots: del this._plots[plot_id] def currentPlotIds(): """ Returns a list of IDs for all currently active plots """ return list(this._plots.keys()) def plotById(plot_id): """ Returns the plot referenced by the ID """ return this._plots[plot_id] if plot_id in this._plots else None def idOfPlot(plot): """ Returns the ID of the plot """ plot_id = None for key in list(this._plots.keys()): if this._plots[key] == plot: plot_id = key break return plot_id Allow plots to be disposed of sooner""" `Singleton` plot helper module All its variables are bound to the module, which can not be instantiated repeatedly so IDs are session-specific. """ import sys import weakref # TODO Refactor to allow typing without circular import #from sas.qtgui.Plotting.PlotterBase import PlotterBase this = sys.modules[__name__] this._plots = weakref.WeakValueDictionary() this._plot_id = 0 def clear(): """ Reset the plot dictionary """ this._plots = weakref.WeakValueDictionary() #def addPlot(plot: PlotterBase): def addPlot(plot): """ Adds a new plot to the current dictionary of plots """ this._plot_id += 1 this._plots["Graph%s"%str(this._plot_id)] = plot # TODO: Why??? def deletePlot(plot_id): """ Deletes an existing plot from the dictionary """ if plot_id in this._plots: del this._plots[plot_id] def currentPlotIds(): """ Returns a list of IDs for all currently active plots """ return list(this._plots.keys()) def plotById(plot_id): """ Returns the plot referenced by the ID """ return this._plots[plot_id] if plot_id in this._plots else None def idOfPlot(plot): """ Returns the ID of the plot """ plot_id = None for key in list(this._plots.keys()): if this._plots[key] == plot: plot_id = key break return plot_id
<commit_before>""" `Singleton` plot helper module All its variables are bound to the module, which can not be instantiated repeatedly so IDs are session-specific. """ import sys # TODO Refactor to allow typing without circular import #from sas.qtgui.Plotting.PlotterBase import PlotterBase this = sys.modules[__name__] this._plots = {} this._plot_id = 0 def clear(): """ Reset the plot dictionary """ this._plots = {} #def addPlot(plot: PlotterBase): def addPlot(plot): """ Adds a new plot to the current dictionary of plots """ this._plot_id += 1 this._plots["Graph%s"%str(this._plot_id)] = plot # TODO: Why??? def deletePlot(plot_id): """ Deletes an existing plot from the dictionary """ if plot_id in this._plots: del this._plots[plot_id] def currentPlotIds(): """ Returns a list of IDs for all currently active plots """ return list(this._plots.keys()) def plotById(plot_id): """ Returns the plot referenced by the ID """ return this._plots[plot_id] if plot_id in this._plots else None def idOfPlot(plot): """ Returns the ID of the plot """ plot_id = None for key in list(this._plots.keys()): if this._plots[key] == plot: plot_id = key break return plot_id <commit_msg>Allow plots to be disposed of sooner<commit_after>""" `Singleton` plot helper module All its variables are bound to the module, which can not be instantiated repeatedly so IDs are session-specific. """ import sys import weakref # TODO Refactor to allow typing without circular import #from sas.qtgui.Plotting.PlotterBase import PlotterBase this = sys.modules[__name__] this._plots = weakref.WeakValueDictionary() this._plot_id = 0 def clear(): """ Reset the plot dictionary """ this._plots = weakref.WeakValueDictionary() #def addPlot(plot: PlotterBase): def addPlot(plot): """ Adds a new plot to the current dictionary of plots """ this._plot_id += 1 this._plots["Graph%s"%str(this._plot_id)] = plot # TODO: Why??? def deletePlot(plot_id): """ Deletes an existing plot from the dictionary """ if plot_id in this._plots: del this._plots[plot_id] def currentPlotIds(): """ Returns a list of IDs for all currently active plots """ return list(this._plots.keys()) def plotById(plot_id): """ Returns the plot referenced by the ID """ return this._plots[plot_id] if plot_id in this._plots else None def idOfPlot(plot): """ Returns the ID of the plot """ plot_id = None for key in list(this._plots.keys()): if this._plots[key] == plot: plot_id = key break return plot_id
e70e6c1cccb235efdd426fcf3cfb7b0be8b9efed
fjord/heartbeat/management/commands/hbhealthcheck.py
fjord/heartbeat/management/commands/hbhealthcheck.py
from django.core.management.base import BaseCommand, CommandError from fjord.heartbeat.healthchecks import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks()) print 'Done!'
from django.core.management.base import BaseCommand from fjord.heartbeat.healthcheck import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks()) print 'Done!'
Fix imports after renaming healthcheck module
Fix imports after renaming healthcheck module
Python
bsd-3-clause
mozilla/fjord,hoosteeno/fjord,hoosteeno/fjord,mozilla/fjord,mozilla/fjord,mozilla/fjord,hoosteeno/fjord,hoosteeno/fjord
from django.core.management.base import BaseCommand, CommandError from fjord.heartbeat.healthchecks import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks()) print 'Done!' Fix imports after renaming healthcheck module
from django.core.management.base import BaseCommand from fjord.heartbeat.healthcheck import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks()) print 'Done!'
<commit_before>from django.core.management.base import BaseCommand, CommandError from fjord.heartbeat.healthchecks import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks()) print 'Done!' <commit_msg>Fix imports after renaming healthcheck module<commit_after>
from django.core.management.base import BaseCommand from fjord.heartbeat.healthcheck import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks()) print 'Done!'
from django.core.management.base import BaseCommand, CommandError from fjord.heartbeat.healthchecks import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks()) print 'Done!' Fix imports after renaming healthcheck modulefrom django.core.management.base import BaseCommand from fjord.heartbeat.healthcheck import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks()) print 'Done!'
<commit_before>from django.core.management.base import BaseCommand, CommandError from fjord.heartbeat.healthchecks import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks()) print 'Done!' <commit_msg>Fix imports after renaming healthcheck module<commit_after>from django.core.management.base import BaseCommand from fjord.heartbeat.healthcheck import run_healthchecks, email_healthchecks class Command(BaseCommand): help = 'Runs heartbeat health checks and sends email' def handle(self, *args, **options): email_healthchecks(run_healthchecks()) print 'Done!'
0e1425b9246ae85dbd8bd37244a442662dd205bb
server/auvsi_suas/views/index.py
server/auvsi_suas/views/index.py
"""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.generic import View logger = logging.getLogger(__name__) class Index(View): """Main view for users connecting via web browsers. This view downloads and displays a JS view. This view first logs in the user. If the user is a superuser, it shows the Judging view which is used to manage the competition and evaluate teams. """ # We want a real redirect to the login page rather than a 403, so # we use user_passes_test directly. @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) def get(self, request): return render(request, 'index.html')
"""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic import TemplateView logger = logging.getLogger(__name__) class Index(TemplateView): """Main view for users connecting via web browsers. This view downloads and displays a JS view. This view first logs in the user. If the user is a superuser, it shows the Judging view which is used to manage the competition and evaluate teams. """ template_name = 'index.html' # Use user_passes_test to redirect to login rather than return 403. @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super(Index, self).get_context_data(**kwargs) return context
Use TemplateView to simplify Index view.
Use TemplateView to simplify Index view.
Python
apache-2.0
auvsi-suas/interop,auvsi-suas/interop,auvsi-suas/interop,auvsi-suas/interop
"""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.generic import View logger = logging.getLogger(__name__) class Index(View): """Main view for users connecting via web browsers. This view downloads and displays a JS view. This view first logs in the user. If the user is a superuser, it shows the Judging view which is used to manage the competition and evaluate teams. """ # We want a real redirect to the login page rather than a 403, so # we use user_passes_test directly. @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) def get(self, request): return render(request, 'index.html') Use TemplateView to simplify Index view.
"""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic import TemplateView logger = logging.getLogger(__name__) class Index(TemplateView): """Main view for users connecting via web browsers. This view downloads and displays a JS view. This view first logs in the user. If the user is a superuser, it shows the Judging view which is used to manage the competition and evaluate teams. """ template_name = 'index.html' # Use user_passes_test to redirect to login rather than return 403. @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super(Index, self).get_context_data(**kwargs) return context
<commit_before>"""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.generic import View logger = logging.getLogger(__name__) class Index(View): """Main view for users connecting via web browsers. This view downloads and displays a JS view. This view first logs in the user. If the user is a superuser, it shows the Judging view which is used to manage the competition and evaluate teams. """ # We want a real redirect to the login page rather than a 403, so # we use user_passes_test directly. @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) def get(self, request): return render(request, 'index.html') <commit_msg>Use TemplateView to simplify Index view.<commit_after>
"""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic import TemplateView logger = logging.getLogger(__name__) class Index(TemplateView): """Main view for users connecting via web browsers. This view downloads and displays a JS view. This view first logs in the user. If the user is a superuser, it shows the Judging view which is used to manage the competition and evaluate teams. """ template_name = 'index.html' # Use user_passes_test to redirect to login rather than return 403. @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super(Index, self).get_context_data(**kwargs) return context
"""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.generic import View logger = logging.getLogger(__name__) class Index(View): """Main view for users connecting via web browsers. This view downloads and displays a JS view. This view first logs in the user. If the user is a superuser, it shows the Judging view which is used to manage the competition and evaluate teams. """ # We want a real redirect to the login page rather than a 403, so # we use user_passes_test directly. @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) def get(self, request): return render(request, 'index.html') Use TemplateView to simplify Index view."""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic import TemplateView logger = logging.getLogger(__name__) class Index(TemplateView): """Main view for users connecting via web browsers. This view downloads and displays a JS view. This view first logs in the user. If the user is a superuser, it shows the Judging view which is used to manage the competition and evaluate teams. """ template_name = 'index.html' # Use user_passes_test to redirect to login rather than return 403. @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super(Index, self).get_context_data(**kwargs) return context
<commit_before>"""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.generic import View logger = logging.getLogger(__name__) class Index(View): """Main view for users connecting via web browsers. This view downloads and displays a JS view. This view first logs in the user. If the user is a superuser, it shows the Judging view which is used to manage the competition and evaluate teams. """ # We want a real redirect to the login page rather than a 403, so # we use user_passes_test directly. @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) def get(self, request): return render(request, 'index.html') <commit_msg>Use TemplateView to simplify Index view.<commit_after>"""Index page admin view.""" import logging from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic import TemplateView logger = logging.getLogger(__name__) class Index(TemplateView): """Main view for users connecting via web browsers. This view downloads and displays a JS view. This view first logs in the user. If the user is a superuser, it shows the Judging view which is used to manage the competition and evaluate teams. """ template_name = 'index.html' # Use user_passes_test to redirect to login rather than return 403. @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super(Index, self).get_context_data(**kwargs) return context
5837df594f9c18ffe62e90dd4d6ba30fdde98dde
flaskbb/utils/database.py
flaskbb/utils/database.py
# -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite if dialect.name == "sqlite": return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name == "sqlite" and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value
# -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite and mysql if dialect.name in ("sqlite", "mysql"): return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name in ("sqlite", "mysql") and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value
Use the naive datetime format for MySQL as well
Use the naive datetime format for MySQL as well See the SQLAlchemy docs for more information: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#sqlalchemy.dial ects.mysql.DATETIME
Python
bsd-3-clause
realityone/flaskbb,realityone/flaskbb,realityone/flaskbb
# -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite if dialect.name == "sqlite": return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name == "sqlite" and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value Use the naive datetime format for MySQL as well See the SQLAlchemy docs for more information: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#sqlalchemy.dial ects.mysql.DATETIME
# -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite and mysql if dialect.name in ("sqlite", "mysql"): return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name in ("sqlite", "mysql") and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value
<commit_before># -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite if dialect.name == "sqlite": return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name == "sqlite" and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value <commit_msg>Use the naive datetime format for MySQL as well See the SQLAlchemy docs for more information: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#sqlalchemy.dial ects.mysql.DATETIME<commit_after>
# -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite and mysql if dialect.name in ("sqlite", "mysql"): return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name in ("sqlite", "mysql") and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value
# -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite if dialect.name == "sqlite": return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name == "sqlite" and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value Use the naive datetime format for MySQL as well See the SQLAlchemy docs for more information: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#sqlalchemy.dial ects.mysql.DATETIME# -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite and mysql if dialect.name in ("sqlite", "mysql"): return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name in ("sqlite", "mysql") and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value
<commit_before># -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite if dialect.name == "sqlite": return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name == "sqlite" and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value <commit_msg>Use the naive datetime format for MySQL as well See the SQLAlchemy docs for more information: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#sqlalchemy.dial ects.mysql.DATETIME<commit_after># -*- coding: utf-8 -*- """ flaskbb.utils.database ~~~~~~~~~~~~~~~~~~~~~~ Some database helpers such as a CRUD mixin. :copyright: (c) 2015 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import pytz from flaskbb.extensions import db class CRUDMixin(object): def __repr__(self): return "<{}>".format(self.__class__.__name__) def save(self): """Saves the object to the database.""" db.session.add(self) db.session.commit() return self def delete(self): """Delete the object from the database.""" db.session.delete(self) db.session.commit() return self class UTCDateTime(db.TypeDecorator): impl = db.DateTime def process_bind_param(self, value, dialect): """Way into the database.""" if value is not None: # store naive datetime for sqlite and mysql if dialect.name in ("sqlite", "mysql"): return value.replace(tzinfo=None) return value.astimezone(pytz.UTC) def process_result_value(self, value, dialect): """Way out of the database.""" # convert naive datetime to non naive datetime if dialect.name in ("sqlite", "mysql") and value is not None: return value.replace(tzinfo=pytz.UTC) # other dialects are already non-naive return value
6b89bf340c7afd6f3fff680287e9f2156fe6cfdc
xylem/specs/__init__.py
xylem/specs/__init__.py
from __future__ import unicode_literals from .impl import verify_spec_name from .impl import get_spec_plugin_list from .impl import Spec from .rules import SpecParsingError __all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name', 'Spec']
from __future__ import unicode_literals from .impl import verify_spec_name from .impl import get_spec_plugin_list from .impl import Spec from .plugins.rules import SpecParsingError __all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name', 'Spec']
Fix type causing import error.
Fix type causing import error.
Python
apache-2.0
catkin/xylem,catkin/xylem
from __future__ import unicode_literals from .impl import verify_spec_name from .impl import get_spec_plugin_list from .impl import Spec from .rules import SpecParsingError __all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name', 'Spec'] Fix type causing import error.
from __future__ import unicode_literals from .impl import verify_spec_name from .impl import get_spec_plugin_list from .impl import Spec from .plugins.rules import SpecParsingError __all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name', 'Spec']
<commit_before>from __future__ import unicode_literals from .impl import verify_spec_name from .impl import get_spec_plugin_list from .impl import Spec from .rules import SpecParsingError __all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name', 'Spec'] <commit_msg>Fix type causing import error.<commit_after>
from __future__ import unicode_literals from .impl import verify_spec_name from .impl import get_spec_plugin_list from .impl import Spec from .plugins.rules import SpecParsingError __all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name', 'Spec']
from __future__ import unicode_literals from .impl import verify_spec_name from .impl import get_spec_plugin_list from .impl import Spec from .rules import SpecParsingError __all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name', 'Spec'] Fix type causing import error.from __future__ import unicode_literals from .impl import verify_spec_name from .impl import get_spec_plugin_list from .impl import Spec from .plugins.rules import SpecParsingError __all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name', 'Spec']
<commit_before>from __future__ import unicode_literals from .impl import verify_spec_name from .impl import get_spec_plugin_list from .impl import Spec from .rules import SpecParsingError __all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name', 'Spec'] <commit_msg>Fix type causing import error.<commit_after>from __future__ import unicode_literals from .impl import verify_spec_name from .impl import get_spec_plugin_list from .impl import Spec from .plugins.rules import SpecParsingError __all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name', 'Spec']
1ed5a4fc595031099c44c2ade3dfe2d5610308c8
plugins/lock_the_chat.py
plugins/lock_the_chat.py
""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")
""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == update.message.from_user.username: return update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")
Update lock plugin so admins could write messages
Update lock plugin so admins could write messages
Python
mit
ProtoxiDe22/Octeon
""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")Update lock plugin so admins could write messages
""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == update.message.from_user.username: return update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")
<commit_before>""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")<commit_msg>Update lock plugin so admins could write messages<commit_after>
""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == update.message.from_user.username: return update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")
""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")Update lock plugin so admins could write messages""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == update.message.from_user.username: return update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")
<commit_before>""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")<commit_msg>Update lock plugin so admins could write messages<commit_after>""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == update.message.from_user.username: return update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")
7f411fd01c931b73f717b114934662ebb2739555
spacy/sv/tokenizer_exceptions.py
spacy/sv/tokenizer_exceptions.py
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "ca", "cm", "dl", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc.", "exkl.", "f.d.", "fid.", "f.Kr.", "forts.", "fr.o.m.", "f.ö.", "förf.", "ha", "hg", "inkl.", "i sht", "i st", "jmf", "jur.", "kcal", "kg", "kl.", "km", "kr.", "l", "lat.", "m", "m.a.o.", "max.", "m.fl.", "min.", "mm", "m.m.", "ngn", "ngt", "nr", "obs.", "o.d.", "osv.", "p.g.a.", "ref.", "resp.", "s.", "s.a.s.", "s.k.", "st.", "s:t", "t.ex.", "t.o.m.", "tfn", "ung.", "äv.", "övers." ]
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc.", "exkl.", "f.d.", "fid.", "f.Kr.", "forts.", "fr.o.m.", "f.ö.", "förf.", "inkl.", "jur.", "kl.", "kr.", "lat.", "m.a.o.", "max.", "m.fl.", "min.", "m.m.", "obs.", "o.d.", "osv.", "p.g.a.", "ref.", "resp.", "s.", "s.a.s.", "s.k.", "st.", "s:t", "t.ex.", "t.o.m.", "ung.", "äv.", "övers." ]
Remove exceptions containing whitespace / no special chars
Remove exceptions containing whitespace / no special chars
Python
mit
honnibal/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,raphael0202/spaCy,explosion/spaCy,Gregory-Howard/spaCy,explosion/spaCy,aikramer2/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,honnibal/spaCy,raphael0202/spaCy,banglakit/spaCy,explosion/spaCy,explosion/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,recognai/spaCy,spacy-io/spaCy,aikramer2/spaCy,raphael0202/spaCy,raphael0202/spaCy,honnibal/spaCy,raphael0202/spaCy,recognai/spaCy,raphael0202/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,recognai/spaCy,aikramer2/spaCy,banglakit/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,honnibal/spaCy,recognai/spaCy,banglakit/spaCy,oroszgy/spaCy.hu,banglakit/spaCy,oroszgy/spaCy.hu,recognai/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "ca", "cm", "dl", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc.", "exkl.", "f.d.", "fid.", "f.Kr.", "forts.", "fr.o.m.", "f.ö.", "förf.", "ha", "hg", "inkl.", "i sht", "i st", "jmf", "jur.", "kcal", "kg", "kl.", "km", "kr.", "l", "lat.", "m", "m.a.o.", "max.", "m.fl.", "min.", "mm", "m.m.", "ngn", "ngt", "nr", "obs.", "o.d.", "osv.", "p.g.a.", "ref.", "resp.", "s.", "s.a.s.", "s.k.", "st.", "s:t", "t.ex.", "t.o.m.", "tfn", "ung.", "äv.", "övers." ] Remove exceptions containing whitespace / no special chars
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc.", "exkl.", "f.d.", "fid.", "f.Kr.", "forts.", "fr.o.m.", "f.ö.", "förf.", "inkl.", "jur.", "kl.", "kr.", "lat.", "m.a.o.", "max.", "m.fl.", "min.", "m.m.", "obs.", "o.d.", "osv.", "p.g.a.", "ref.", "resp.", "s.", "s.a.s.", "s.k.", "st.", "s:t", "t.ex.", "t.o.m.", "ung.", "äv.", "övers." ]
<commit_before># encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "ca", "cm", "dl", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc.", "exkl.", "f.d.", "fid.", "f.Kr.", "forts.", "fr.o.m.", "f.ö.", "förf.", "ha", "hg", "inkl.", "i sht", "i st", "jmf", "jur.", "kcal", "kg", "kl.", "km", "kr.", "l", "lat.", "m", "m.a.o.", "max.", "m.fl.", "min.", "mm", "m.m.", "ngn", "ngt", "nr", "obs.", "o.d.", "osv.", "p.g.a.", "ref.", "resp.", "s.", "s.a.s.", "s.k.", "st.", "s:t", "t.ex.", "t.o.m.", "tfn", "ung.", "äv.", "övers." ] <commit_msg>Remove exceptions containing whitespace / no special chars<commit_after>
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc.", "exkl.", "f.d.", "fid.", "f.Kr.", "forts.", "fr.o.m.", "f.ö.", "förf.", "inkl.", "jur.", "kl.", "kr.", "lat.", "m.a.o.", "max.", "m.fl.", "min.", "m.m.", "obs.", "o.d.", "osv.", "p.g.a.", "ref.", "resp.", "s.", "s.a.s.", "s.k.", "st.", "s:t", "t.ex.", "t.o.m.", "ung.", "äv.", "övers." ]
# encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "ca", "cm", "dl", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc.", "exkl.", "f.d.", "fid.", "f.Kr.", "forts.", "fr.o.m.", "f.ö.", "förf.", "ha", "hg", "inkl.", "i sht", "i st", "jmf", "jur.", "kcal", "kg", "kl.", "km", "kr.", "l", "lat.", "m", "m.a.o.", "max.", "m.fl.", "min.", "mm", "m.m.", "ngn", "ngt", "nr", "obs.", "o.d.", "osv.", "p.g.a.", "ref.", "resp.", "s.", "s.a.s.", "s.k.", "st.", "s:t", "t.ex.", "t.o.m.", "tfn", "ung.", "äv.", "övers." ] Remove exceptions containing whitespace / no special chars# encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc.", "exkl.", "f.d.", "fid.", "f.Kr.", "forts.", "fr.o.m.", "f.ö.", "förf.", "inkl.", "jur.", "kl.", "kr.", "lat.", "m.a.o.", "max.", "m.fl.", "min.", "m.m.", "obs.", "o.d.", "osv.", "p.g.a.", "ref.", "resp.", "s.", "s.a.s.", "s.k.", "st.", "s:t", "t.ex.", "t.o.m.", "ung.", "äv.", "övers." ]
<commit_before># encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "ca", "cm", "dl", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc.", "exkl.", "f.d.", "fid.", "f.Kr.", "forts.", "fr.o.m.", "f.ö.", "förf.", "ha", "hg", "inkl.", "i sht", "i st", "jmf", "jur.", "kcal", "kg", "kl.", "km", "kr.", "l", "lat.", "m", "m.a.o.", "max.", "m.fl.", "min.", "mm", "m.m.", "ngn", "ngt", "nr", "obs.", "o.d.", "osv.", "p.g.a.", "ref.", "resp.", "s.", "s.a.s.", "s.k.", "st.", "s:t", "t.ex.", "t.o.m.", "tfn", "ung.", "äv.", "övers." ] <commit_msg>Remove exceptions containing whitespace / no special chars<commit_after># encoding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA TOKENIZER_EXCEPTIONS = { } ORTH_ONLY = [ "ang.", "anm.", "bil.", "bl.a.", "dvs.", "e.Kr.", "el.", "e.d.", "eng.", "etc.", "exkl.", "f.d.", "fid.", "f.Kr.", "forts.", "fr.o.m.", "f.ö.", "förf.", "inkl.", "jur.", "kl.", "kr.", "lat.", "m.a.o.", "max.", "m.fl.", "min.", "m.m.", "obs.", "o.d.", "osv.", "p.g.a.", "ref.", "resp.", "s.", "s.a.s.", "s.k.", "st.", "s:t", "t.ex.", "t.o.m.", "ung.", "äv.", "övers." ]
b4498f6dfe26dc0e858d4af5e26cfff9fab3f0cb
prompt_toolkit/layout/dummy.py
prompt_toolkit/layout/dummy.py
""" Dummy layout. Used when somebody creates an `Application` without specifying a `Layout`. """ from __future__ import unicode_literals from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings from .containers import Window from .controls import FormattedTextControl from .dimension import D from .layout import Layout __all__ = ( 'create_dummy_layout', ) def create_dummy_layout(): """ Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. """ kb = KeyBindings() @kb.add('enter') def enter(event): event.app.set_result(None) control = FormattedTextControl( HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'), key_bindings=kb) window = Window(content=control, height=D(min=1)) return Layout(container=window, focussed_window=window)
""" Dummy layout. Used when somebody creates an `Application` without specifying a `Layout`. """ from __future__ import unicode_literals from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings from .containers import Window from .controls import FormattedTextControl from .dimension import D from .layout import Layout __all__ = ( 'create_dummy_layout', ) def create_dummy_layout(): """ Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. """ kb = KeyBindings() @kb.add('enter') def enter(event): event.app.set_result(None) control = FormattedTextControl( HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'), key_bindings=kb) window = Window(content=control, height=D(min=1)) return Layout(container=window, focussed_element=window)
Fix for DummyLayout: pass 'focussed_element' instead of 'focussed_window'.
Fix for DummyLayout: pass 'focussed_element' instead of 'focussed_window'.
Python
bsd-3-clause
jonathanslenders/python-prompt-toolkit
""" Dummy layout. Used when somebody creates an `Application` without specifying a `Layout`. """ from __future__ import unicode_literals from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings from .containers import Window from .controls import FormattedTextControl from .dimension import D from .layout import Layout __all__ = ( 'create_dummy_layout', ) def create_dummy_layout(): """ Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. """ kb = KeyBindings() @kb.add('enter') def enter(event): event.app.set_result(None) control = FormattedTextControl( HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'), key_bindings=kb) window = Window(content=control, height=D(min=1)) return Layout(container=window, focussed_window=window) Fix for DummyLayout: pass 'focussed_element' instead of 'focussed_window'.
""" Dummy layout. Used when somebody creates an `Application` without specifying a `Layout`. """ from __future__ import unicode_literals from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings from .containers import Window from .controls import FormattedTextControl from .dimension import D from .layout import Layout __all__ = ( 'create_dummy_layout', ) def create_dummy_layout(): """ Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. """ kb = KeyBindings() @kb.add('enter') def enter(event): event.app.set_result(None) control = FormattedTextControl( HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'), key_bindings=kb) window = Window(content=control, height=D(min=1)) return Layout(container=window, focussed_element=window)
<commit_before>""" Dummy layout. Used when somebody creates an `Application` without specifying a `Layout`. """ from __future__ import unicode_literals from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings from .containers import Window from .controls import FormattedTextControl from .dimension import D from .layout import Layout __all__ = ( 'create_dummy_layout', ) def create_dummy_layout(): """ Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. """ kb = KeyBindings() @kb.add('enter') def enter(event): event.app.set_result(None) control = FormattedTextControl( HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'), key_bindings=kb) window = Window(content=control, height=D(min=1)) return Layout(container=window, focussed_window=window) <commit_msg>Fix for DummyLayout: pass 'focussed_element' instead of 'focussed_window'.<commit_after>
""" Dummy layout. Used when somebody creates an `Application` without specifying a `Layout`. """ from __future__ import unicode_literals from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings from .containers import Window from .controls import FormattedTextControl from .dimension import D from .layout import Layout __all__ = ( 'create_dummy_layout', ) def create_dummy_layout(): """ Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. """ kb = KeyBindings() @kb.add('enter') def enter(event): event.app.set_result(None) control = FormattedTextControl( HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'), key_bindings=kb) window = Window(content=control, height=D(min=1)) return Layout(container=window, focussed_element=window)
""" Dummy layout. Used when somebody creates an `Application` without specifying a `Layout`. """ from __future__ import unicode_literals from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings from .containers import Window from .controls import FormattedTextControl from .dimension import D from .layout import Layout __all__ = ( 'create_dummy_layout', ) def create_dummy_layout(): """ Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. """ kb = KeyBindings() @kb.add('enter') def enter(event): event.app.set_result(None) control = FormattedTextControl( HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'), key_bindings=kb) window = Window(content=control, height=D(min=1)) return Layout(container=window, focussed_window=window) Fix for DummyLayout: pass 'focussed_element' instead of 'focussed_window'.""" Dummy layout. Used when somebody creates an `Application` without specifying a `Layout`. """ from __future__ import unicode_literals from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings from .containers import Window from .controls import FormattedTextControl from .dimension import D from .layout import Layout __all__ = ( 'create_dummy_layout', ) def create_dummy_layout(): """ Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. """ kb = KeyBindings() @kb.add('enter') def enter(event): event.app.set_result(None) control = FormattedTextControl( HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'), key_bindings=kb) window = Window(content=control, height=D(min=1)) return Layout(container=window, focussed_element=window)
<commit_before>""" Dummy layout. Used when somebody creates an `Application` without specifying a `Layout`. """ from __future__ import unicode_literals from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings from .containers import Window from .controls import FormattedTextControl from .dimension import D from .layout import Layout __all__ = ( 'create_dummy_layout', ) def create_dummy_layout(): """ Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. """ kb = KeyBindings() @kb.add('enter') def enter(event): event.app.set_result(None) control = FormattedTextControl( HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'), key_bindings=kb) window = Window(content=control, height=D(min=1)) return Layout(container=window, focussed_window=window) <commit_msg>Fix for DummyLayout: pass 'focussed_element' instead of 'focussed_window'.<commit_after>""" Dummy layout. Used when somebody creates an `Application` without specifying a `Layout`. """ from __future__ import unicode_literals from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings from .containers import Window from .controls import FormattedTextControl from .dimension import D from .layout import Layout __all__ = ( 'create_dummy_layout', ) def create_dummy_layout(): """ Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. """ kb = KeyBindings() @kb.add('enter') def enter(event): event.app.set_result(None) control = FormattedTextControl( HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'), key_bindings=kb) window = Window(content=control, height=D(min=1)) return Layout(container=window, focussed_element=window)
e1efe5d9c07799c7ddb666b06782589dff791f23
kpi/utils/ss_structure_to_mdtable.py
kpi/utils/ss_structure_to_mdtable.py
# coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) is 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """ receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """ import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt="orgtbl")) return '\n\n'.join(output)
# coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) == 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """ receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """ import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt="orgtbl")) return '\n\n'.join(output)
Resolve `SyntaxWarning: "is" with a literal`
Resolve `SyntaxWarning: "is" with a literal`
Python
agpl-3.0
kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi
# coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) is 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """ receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """ import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt="orgtbl")) return '\n\n'.join(output) Resolve `SyntaxWarning: "is" with a literal`
# coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) == 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """ receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """ import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt="orgtbl")) return '\n\n'.join(output)
<commit_before># coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) is 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """ receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """ import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt="orgtbl")) return '\n\n'.join(output) <commit_msg>Resolve `SyntaxWarning: "is" with a literal`<commit_after>
# coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) == 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """ receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """ import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt="orgtbl")) return '\n\n'.join(output)
# coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) is 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """ receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """ import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt="orgtbl")) return '\n\n'.join(output) Resolve `SyntaxWarning: "is" with a literal`# coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) == 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """ receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """ import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt="orgtbl")) return '\n\n'.join(output)
<commit_before># coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) is 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """ receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """ import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt="orgtbl")) return '\n\n'.join(output) <commit_msg>Resolve `SyntaxWarning: "is" with a literal`<commit_after># coding: utf-8 from collections import OrderedDict def _convert_sheets_to_lists(content): cols = OrderedDict() if not content or len(content) == 0: return [], None if isinstance(content[0], list): cols.update(OrderedDict.fromkeys(content[0])) for row in content: if isinstance(row, dict): cols.update(OrderedDict.fromkeys(row.keys())) cols = cols.keys() out_content = [] _valid = False for row in content: out_row = [] for col in cols: _val = row.get(col, '') if _val is None: _val = '' out_row.append(_val) if len(out_row) > 0: _valid = True out_content.append(out_row) return cols, out_content if _valid else None def ss_structure_to_mdtable(content): """ receives a dict or OrderedDict with arrays of arrays representing a spreadsheet, and returns a markdown document with tables """ import tabulate out_sheets = OrderedDict() output = [] def cell_to_str(cell): return '' if cell is None else str(cell) for (sheet_name, contents) in content.items(): out_sheets[sheet_name] = output (headers, content) = _convert_sheets_to_lists(contents) if content: output.append('#{}'.format(sheet_name)) output.append(tabulate.tabulate(content, headers=headers, tablefmt="orgtbl")) return '\n\n'.join(output)
497d82e353bfc2db1246982616bf39ec26ba27f8
utilities/__init__.py
utilities/__init__.py
#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout """ return launch(cmd)[0]
#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout """ return launch(cmd)[0] def get_stderr(cmd): """ Fork the specified command, returning stderr """ return launch(cmd)[1]
Add function to get just stderr from subprocess command
Add function to get just stderr from subprocess command
Python
mit
IanLee1521/utilities
#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout """ return launch(cmd)[0] Add function to get just stderr from subprocess command
#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout """ return launch(cmd)[0] def get_stderr(cmd): """ Fork the specified command, returning stderr """ return launch(cmd)[1]
<commit_before>#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout """ return launch(cmd)[0] <commit_msg>Add function to get just stderr from subprocess command<commit_after>
#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout """ return launch(cmd)[0] def get_stderr(cmd): """ Fork the specified command, returning stderr """ return launch(cmd)[1]
#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout """ return launch(cmd)[0] Add function to get just stderr from subprocess command#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout """ return launch(cmd)[0] def get_stderr(cmd): """ Fork the specified command, returning stderr """ return launch(cmd)[1]
<commit_before>#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout """ return launch(cmd)[0] <commit_msg>Add function to get just stderr from subprocess command<commit_after>#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout """ return launch(cmd)[0] def get_stderr(cmd): """ Fork the specified command, returning stderr """ return launch(cmd)[1]
fa9f4ca0bae63b17937c676800fcf80889c70030
cura/CuraSplashScreen.py
cura/CuraSplashScreen.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QColor, QFont from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Application class CuraSplashScreen(QSplashScreen): def __init__(self): super().__init__() self.setPixmap(QPixmap(Resources.getPath(Resources.Images, "cura.png"))) def drawContents(self, painter): painter.save() painter.setPen(QColor(0, 0, 0, 255)) version = Application.getInstance().getVersion().split("-") painter.setFont(QFont("Proxima Nova Rg", 20)) painter.drawText(0, 0, 203, 230, Qt.AlignRight | Qt.AlignBottom, version[0]) if len(version) > 1: painter.setFont(QFont("Proxima Nova Rg", 12)) painter.drawText(0, 0, 203, 255, Qt.AlignRight | Qt.AlignBottom, version[1]) painter.restore() super().drawContents(painter)
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt, QCoreApplication from PyQt5.QtGui import QPixmap, QColor, QFont, QFontMetrics from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Application class CuraSplashScreen(QSplashScreen): def __init__(self): super().__init__() self._scale = round(QFontMetrics(QCoreApplication.instance().font()).ascent() / 12) splash_image = QPixmap(Resources.getPath(Resources.Images, "cura.png")) self.setPixmap(splash_image.scaled(splash_image.size() * self._scale)) def drawContents(self, painter): painter.save() painter.setPen(QColor(0, 0, 0, 255)) version = Application.getInstance().getVersion().split("-") painter.setFont(QFont("Proxima Nova Rg", 20 )) painter.drawText(0, 0, 330 * self._scale, 230 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[0]) if len(version) > 1: painter.setFont(QFont("Proxima Nova Rg", 12 )) painter.drawText(0, 0, 330 * self._scale, 255 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[1]) painter.restore() super().drawContents(painter)
Fix splashscreen size on HiDPI (windows) screens
Fix splashscreen size on HiDPI (windows) screens
Python
agpl-3.0
fieldOfView/Cura,ynotstartups/Wanhao,ynotstartups/Wanhao,Curahelper/Cura,totalretribution/Cura,Curahelper/Cura,totalretribution/Cura,senttech/Cura,fieldOfView/Cura,hmflash/Cura,senttech/Cura,hmflash/Cura
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QColor, QFont from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Application class CuraSplashScreen(QSplashScreen): def __init__(self): super().__init__() self.setPixmap(QPixmap(Resources.getPath(Resources.Images, "cura.png"))) def drawContents(self, painter): painter.save() painter.setPen(QColor(0, 0, 0, 255)) version = Application.getInstance().getVersion().split("-") painter.setFont(QFont("Proxima Nova Rg", 20)) painter.drawText(0, 0, 203, 230, Qt.AlignRight | Qt.AlignBottom, version[0]) if len(version) > 1: painter.setFont(QFont("Proxima Nova Rg", 12)) painter.drawText(0, 0, 203, 255, Qt.AlignRight | Qt.AlignBottom, version[1]) painter.restore() super().drawContents(painter) Fix splashscreen size on HiDPI (windows) screens
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt, QCoreApplication from PyQt5.QtGui import QPixmap, QColor, QFont, QFontMetrics from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Application class CuraSplashScreen(QSplashScreen): def __init__(self): super().__init__() self._scale = round(QFontMetrics(QCoreApplication.instance().font()).ascent() / 12) splash_image = QPixmap(Resources.getPath(Resources.Images, "cura.png")) self.setPixmap(splash_image.scaled(splash_image.size() * self._scale)) def drawContents(self, painter): painter.save() painter.setPen(QColor(0, 0, 0, 255)) version = Application.getInstance().getVersion().split("-") painter.setFont(QFont("Proxima Nova Rg", 20 )) painter.drawText(0, 0, 330 * self._scale, 230 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[0]) if len(version) > 1: painter.setFont(QFont("Proxima Nova Rg", 12 )) painter.drawText(0, 0, 330 * self._scale, 255 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[1]) painter.restore() super().drawContents(painter)
<commit_before># Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QColor, QFont from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Application class CuraSplashScreen(QSplashScreen): def __init__(self): super().__init__() self.setPixmap(QPixmap(Resources.getPath(Resources.Images, "cura.png"))) def drawContents(self, painter): painter.save() painter.setPen(QColor(0, 0, 0, 255)) version = Application.getInstance().getVersion().split("-") painter.setFont(QFont("Proxima Nova Rg", 20)) painter.drawText(0, 0, 203, 230, Qt.AlignRight | Qt.AlignBottom, version[0]) if len(version) > 1: painter.setFont(QFont("Proxima Nova Rg", 12)) painter.drawText(0, 0, 203, 255, Qt.AlignRight | Qt.AlignBottom, version[1]) painter.restore() super().drawContents(painter) <commit_msg>Fix splashscreen size on HiDPI (windows) screens<commit_after>
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt, QCoreApplication from PyQt5.QtGui import QPixmap, QColor, QFont, QFontMetrics from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Application class CuraSplashScreen(QSplashScreen): def __init__(self): super().__init__() self._scale = round(QFontMetrics(QCoreApplication.instance().font()).ascent() / 12) splash_image = QPixmap(Resources.getPath(Resources.Images, "cura.png")) self.setPixmap(splash_image.scaled(splash_image.size() * self._scale)) def drawContents(self, painter): painter.save() painter.setPen(QColor(0, 0, 0, 255)) version = Application.getInstance().getVersion().split("-") painter.setFont(QFont("Proxima Nova Rg", 20 )) painter.drawText(0, 0, 330 * self._scale, 230 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[0]) if len(version) > 1: painter.setFont(QFont("Proxima Nova Rg", 12 )) painter.drawText(0, 0, 330 * self._scale, 255 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[1]) painter.restore() super().drawContents(painter)
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QColor, QFont from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Application class CuraSplashScreen(QSplashScreen): def __init__(self): super().__init__() self.setPixmap(QPixmap(Resources.getPath(Resources.Images, "cura.png"))) def drawContents(self, painter): painter.save() painter.setPen(QColor(0, 0, 0, 255)) version = Application.getInstance().getVersion().split("-") painter.setFont(QFont("Proxima Nova Rg", 20)) painter.drawText(0, 0, 203, 230, Qt.AlignRight | Qt.AlignBottom, version[0]) if len(version) > 1: painter.setFont(QFont("Proxima Nova Rg", 12)) painter.drawText(0, 0, 203, 255, Qt.AlignRight | Qt.AlignBottom, version[1]) painter.restore() super().drawContents(painter) Fix splashscreen size on HiDPI (windows) screens# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt, QCoreApplication from PyQt5.QtGui import QPixmap, QColor, QFont, QFontMetrics from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Application class CuraSplashScreen(QSplashScreen): def __init__(self): super().__init__() self._scale = round(QFontMetrics(QCoreApplication.instance().font()).ascent() / 12) splash_image = QPixmap(Resources.getPath(Resources.Images, "cura.png")) self.setPixmap(splash_image.scaled(splash_image.size() * self._scale)) def drawContents(self, painter): painter.save() painter.setPen(QColor(0, 0, 0, 255)) version = Application.getInstance().getVersion().split("-") painter.setFont(QFont("Proxima Nova Rg", 20 )) painter.drawText(0, 0, 330 * self._scale, 230 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[0]) if len(version) > 1: painter.setFont(QFont("Proxima Nova Rg", 12 )) painter.drawText(0, 0, 330 * self._scale, 255 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[1]) painter.restore() super().drawContents(painter)
<commit_before># Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QColor, QFont from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Application class CuraSplashScreen(QSplashScreen): def __init__(self): super().__init__() self.setPixmap(QPixmap(Resources.getPath(Resources.Images, "cura.png"))) def drawContents(self, painter): painter.save() painter.setPen(QColor(0, 0, 0, 255)) version = Application.getInstance().getVersion().split("-") painter.setFont(QFont("Proxima Nova Rg", 20)) painter.drawText(0, 0, 203, 230, Qt.AlignRight | Qt.AlignBottom, version[0]) if len(version) > 1: painter.setFont(QFont("Proxima Nova Rg", 12)) painter.drawText(0, 0, 203, 255, Qt.AlignRight | Qt.AlignBottom, version[1]) painter.restore() super().drawContents(painter) <commit_msg>Fix splashscreen size on HiDPI (windows) screens<commit_after># Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from PyQt5.QtCore import Qt, QCoreApplication from PyQt5.QtGui import QPixmap, QColor, QFont, QFontMetrics from PyQt5.QtWidgets import QSplashScreen from UM.Resources import Resources from UM.Application import Application class CuraSplashScreen(QSplashScreen): def __init__(self): super().__init__() self._scale = round(QFontMetrics(QCoreApplication.instance().font()).ascent() / 12) splash_image = QPixmap(Resources.getPath(Resources.Images, "cura.png")) self.setPixmap(splash_image.scaled(splash_image.size() * self._scale)) def drawContents(self, painter): painter.save() painter.setPen(QColor(0, 0, 0, 255)) version = Application.getInstance().getVersion().split("-") painter.setFont(QFont("Proxima Nova Rg", 20 )) painter.drawText(0, 0, 330 * self._scale, 230 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[0]) if len(version) > 1: painter.setFont(QFont("Proxima Nova Rg", 12 )) painter.drawText(0, 0, 330 * self._scale, 255 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[1]) painter.restore() super().drawContents(painter)
29cde856d41fc8654735aa5233e5983178a8e08e
wp2github/_version.py
wp2github/_version.py
__version_info__ = (1, 0, 2) __version__ = '.'.join(map(str, __version_info__))
__version_info__ = (1, 0, 3) __version__ = '.'.join(map(str, __version_info__))
Replace Markdown README with reStructured text
Replace Markdown README with reStructured text
Python
mit
r8/wp2github.py
__version_info__ = (1, 0, 2) __version__ = '.'.join(map(str, __version_info__)) Replace Markdown README with reStructured text
__version_info__ = (1, 0, 3) __version__ = '.'.join(map(str, __version_info__))
<commit_before>__version_info__ = (1, 0, 2) __version__ = '.'.join(map(str, __version_info__)) <commit_msg>Replace Markdown README with reStructured text<commit_after>
__version_info__ = (1, 0, 3) __version__ = '.'.join(map(str, __version_info__))
__version_info__ = (1, 0, 2) __version__ = '.'.join(map(str, __version_info__)) Replace Markdown README with reStructured text__version_info__ = (1, 0, 3) __version__ = '.'.join(map(str, __version_info__))
<commit_before>__version_info__ = (1, 0, 2) __version__ = '.'.join(map(str, __version_info__)) <commit_msg>Replace Markdown README with reStructured text<commit_after>__version_info__ = (1, 0, 3) __version__ = '.'.join(map(str, __version_info__))
629333cc6e302ef19330a459b787bcce7e9f2fa8
bartercheckout/models.py
bartercheckout/models.py
from django.db import models # Create your models here. class BarterEvent(models.Model): barter_account = models.ForeignKey( 'BarterAccount', #on_delete=models.CASCADE, ) ADD = 'Add' SUBTRACT = 'Subtract' NOTE = 'Note' EVENT_TYPE_CHOICES = ( (ADD, 'Add'), (SUBTRACT, 'Subtract'), (NOTE, 'Note'), ) event_type = models.CharField( max_length=20, choices = EVENT_TYPE_CHOICES, default = SUBTRACT, ) event_time = models.DateTimeField(auto_now_add=True) #staff_id = models.ForeignKey() class BarterAccount(models.Model): patron_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=5, decimal_places=2)
from django.db import models # Create your models here. class BarterEvent(models.Model): barter_account = models.ForeignKey( 'BarterAccount', #on_delete=models.CASCADE, ) ADD = 'Add' SUBTRACT = 'Subtract' NOTE = 'Note' EVENT_TYPE_CHOICES = ( (ADD, 'Add'), (SUBTRACT, 'Subtract'), (NOTE, 'Note'), ) event_type = models.CharField( max_length=20, choices = EVENT_TYPE_CHOICES, default = SUBTRACT, ) event_time = models.DateTimeField(auto_now_add=True) #staff_id = models.ForeignKey() class BarterAccount(models.Model): customer_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=5, decimal_places=2)
Change 'patron' to 'customer' in BarterAccount
Change 'patron' to 'customer' in BarterAccount
Python
agpl-3.0
codeforgoodconf/sisters-of-the-road-admin,codeforgoodconf/sisters-of-the-road-admin,codeforgoodconf/sisters-of-the-road-admin
from django.db import models # Create your models here. class BarterEvent(models.Model): barter_account = models.ForeignKey( 'BarterAccount', #on_delete=models.CASCADE, ) ADD = 'Add' SUBTRACT = 'Subtract' NOTE = 'Note' EVENT_TYPE_CHOICES = ( (ADD, 'Add'), (SUBTRACT, 'Subtract'), (NOTE, 'Note'), ) event_type = models.CharField( max_length=20, choices = EVENT_TYPE_CHOICES, default = SUBTRACT, ) event_time = models.DateTimeField(auto_now_add=True) #staff_id = models.ForeignKey() class BarterAccount(models.Model): patron_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=5, decimal_places=2) Change 'patron' to 'customer' in BarterAccount
from django.db import models # Create your models here. class BarterEvent(models.Model): barter_account = models.ForeignKey( 'BarterAccount', #on_delete=models.CASCADE, ) ADD = 'Add' SUBTRACT = 'Subtract' NOTE = 'Note' EVENT_TYPE_CHOICES = ( (ADD, 'Add'), (SUBTRACT, 'Subtract'), (NOTE, 'Note'), ) event_type = models.CharField( max_length=20, choices = EVENT_TYPE_CHOICES, default = SUBTRACT, ) event_time = models.DateTimeField(auto_now_add=True) #staff_id = models.ForeignKey() class BarterAccount(models.Model): customer_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=5, decimal_places=2)
<commit_before>from django.db import models # Create your models here. class BarterEvent(models.Model): barter_account = models.ForeignKey( 'BarterAccount', #on_delete=models.CASCADE, ) ADD = 'Add' SUBTRACT = 'Subtract' NOTE = 'Note' EVENT_TYPE_CHOICES = ( (ADD, 'Add'), (SUBTRACT, 'Subtract'), (NOTE, 'Note'), ) event_type = models.CharField( max_length=20, choices = EVENT_TYPE_CHOICES, default = SUBTRACT, ) event_time = models.DateTimeField(auto_now_add=True) #staff_id = models.ForeignKey() class BarterAccount(models.Model): patron_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=5, decimal_places=2) <commit_msg>Change 'patron' to 'customer' in BarterAccount<commit_after>
from django.db import models # Create your models here. class BarterEvent(models.Model): barter_account = models.ForeignKey( 'BarterAccount', #on_delete=models.CASCADE, ) ADD = 'Add' SUBTRACT = 'Subtract' NOTE = 'Note' EVENT_TYPE_CHOICES = ( (ADD, 'Add'), (SUBTRACT, 'Subtract'), (NOTE, 'Note'), ) event_type = models.CharField( max_length=20, choices = EVENT_TYPE_CHOICES, default = SUBTRACT, ) event_time = models.DateTimeField(auto_now_add=True) #staff_id = models.ForeignKey() class BarterAccount(models.Model): customer_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=5, decimal_places=2)
from django.db import models # Create your models here. class BarterEvent(models.Model): barter_account = models.ForeignKey( 'BarterAccount', #on_delete=models.CASCADE, ) ADD = 'Add' SUBTRACT = 'Subtract' NOTE = 'Note' EVENT_TYPE_CHOICES = ( (ADD, 'Add'), (SUBTRACT, 'Subtract'), (NOTE, 'Note'), ) event_type = models.CharField( max_length=20, choices = EVENT_TYPE_CHOICES, default = SUBTRACT, ) event_time = models.DateTimeField(auto_now_add=True) #staff_id = models.ForeignKey() class BarterAccount(models.Model): patron_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=5, decimal_places=2) Change 'patron' to 'customer' in BarterAccountfrom django.db import models # Create your models here. class BarterEvent(models.Model): barter_account = models.ForeignKey( 'BarterAccount', #on_delete=models.CASCADE, ) ADD = 'Add' SUBTRACT = 'Subtract' NOTE = 'Note' EVENT_TYPE_CHOICES = ( (ADD, 'Add'), (SUBTRACT, 'Subtract'), (NOTE, 'Note'), ) event_type = models.CharField( max_length=20, choices = EVENT_TYPE_CHOICES, default = SUBTRACT, ) event_time = models.DateTimeField(auto_now_add=True) #staff_id = models.ForeignKey() class BarterAccount(models.Model): customer_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=5, decimal_places=2)
<commit_before>from django.db import models # Create your models here. class BarterEvent(models.Model): barter_account = models.ForeignKey( 'BarterAccount', #on_delete=models.CASCADE, ) ADD = 'Add' SUBTRACT = 'Subtract' NOTE = 'Note' EVENT_TYPE_CHOICES = ( (ADD, 'Add'), (SUBTRACT, 'Subtract'), (NOTE, 'Note'), ) event_type = models.CharField( max_length=20, choices = EVENT_TYPE_CHOICES, default = SUBTRACT, ) event_time = models.DateTimeField(auto_now_add=True) #staff_id = models.ForeignKey() class BarterAccount(models.Model): patron_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=5, decimal_places=2) <commit_msg>Change 'patron' to 'customer' in BarterAccount<commit_after>from django.db import models # Create your models here. class BarterEvent(models.Model): barter_account = models.ForeignKey( 'BarterAccount', #on_delete=models.CASCADE, ) ADD = 'Add' SUBTRACT = 'Subtract' NOTE = 'Note' EVENT_TYPE_CHOICES = ( (ADD, 'Add'), (SUBTRACT, 'Subtract'), (NOTE, 'Note'), ) event_type = models.CharField( max_length=20, choices = EVENT_TYPE_CHOICES, default = SUBTRACT, ) event_time = models.DateTimeField(auto_now_add=True) #staff_id = models.ForeignKey() class BarterAccount(models.Model): customer_name = models.CharField(max_length=100) balance = models.DecimalField(max_digits=5, decimal_places=2)
b8feefe615457809e3583782d5d3a202e63974af
ksurobot/process_setup.py
ksurobot/process_setup.py
import logging.config from setproctitle import setproctitle def process_setup(): setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, })
import logging.config from setproctitle import setproctitle import signal def process_setup(): exitcmd = lambda *_: exit(0) signal.signal(signal.SIGINT, exitcmd) signal.signal(signal.SIGTERM, exitcmd) setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, })
Add signal handler for sigterm.
Add signal handler for sigterm.
Python
apache-2.0
ksurct/MercuryRoboticsEmbedded2016,ksurct/MercuryRoboticsEmbedded2016,ksurct/MercuryRoboticsEmbedded2016
import logging.config from setproctitle import setproctitle def process_setup(): setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, }) Add signal handler for sigterm.
import logging.config from setproctitle import setproctitle import signal def process_setup(): exitcmd = lambda *_: exit(0) signal.signal(signal.SIGINT, exitcmd) signal.signal(signal.SIGTERM, exitcmd) setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, })
<commit_before>import logging.config from setproctitle import setproctitle def process_setup(): setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, }) <commit_msg>Add signal handler for sigterm.<commit_after>
import logging.config from setproctitle import setproctitle import signal def process_setup(): exitcmd = lambda *_: exit(0) signal.signal(signal.SIGINT, exitcmd) signal.signal(signal.SIGTERM, exitcmd) setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, })
import logging.config from setproctitle import setproctitle def process_setup(): setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, }) Add signal handler for sigterm.import logging.config from setproctitle import setproctitle import signal def process_setup(): exitcmd = lambda *_: exit(0) signal.signal(signal.SIGINT, exitcmd) signal.signal(signal.SIGTERM, exitcmd) setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, })
<commit_before>import logging.config from setproctitle import setproctitle def process_setup(): setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, }) <commit_msg>Add signal handler for sigterm.<commit_after>import logging.config from setproctitle import setproctitle import signal def process_setup(): exitcmd = lambda *_: exit(0) signal.signal(signal.SIGINT, exitcmd) signal.signal(signal.SIGTERM, exitcmd) setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, })
181318bbb9f2e4458b1188bfc8a8ada7f3b4b196
moderation_queue/urls.py
moderation_queue/urls.py
from django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/success/(?P<popit_person_id>\d+)$', PhotoUploadSuccess.as_view(), name="photo-upload-success"), )
from django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/(?P<popit_person_id>\d+)/success$', PhotoUploadSuccess.as_view(), name="photo-upload-success"), )
Rearrange the photo upload success URL for consistency
Rearrange the photo upload success URL for consistency
Python
agpl-3.0
datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,mysociety/yournextmp-popit,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,datamade/yournextmp-popit,openstate/yournextrepresentative,DemocracyClub/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextrepresentative,YoQuieroSaber/yournextrepresentative,datamade/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,openstate/yournextrepresentative,neavouli/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit
from django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/success/(?P<popit_person_id>\d+)$', PhotoUploadSuccess.as_view(), name="photo-upload-success"), ) Rearrange the photo upload success URL for consistency
from django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/(?P<popit_person_id>\d+)/success$', PhotoUploadSuccess.as_view(), name="photo-upload-success"), )
<commit_before>from django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/success/(?P<popit_person_id>\d+)$', PhotoUploadSuccess.as_view(), name="photo-upload-success"), ) <commit_msg>Rearrange the photo upload success URL for consistency<commit_after>
from django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/(?P<popit_person_id>\d+)/success$', PhotoUploadSuccess.as_view(), name="photo-upload-success"), )
from django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/success/(?P<popit_person_id>\d+)$', PhotoUploadSuccess.as_view(), name="photo-upload-success"), ) Rearrange the photo upload success URL for consistencyfrom django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/(?P<popit_person_id>\d+)/success$', PhotoUploadSuccess.as_view(), name="photo-upload-success"), )
<commit_before>from django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/success/(?P<popit_person_id>\d+)$', PhotoUploadSuccess.as_view(), name="photo-upload-success"), ) <commit_msg>Rearrange the photo upload success URL for consistency<commit_after>from django.conf.urls import patterns, url from .views import upload_photo, PhotoUploadSuccess urlpatterns = patterns('', url(r'^photo/upload/(?P<popit_person_id>\d+)$', upload_photo, name="photo-upload"), url(r'^photo/upload/(?P<popit_person_id>\d+)/success$', PhotoUploadSuccess.as_view(), name="photo-upload-success"), )
34f83765d850fbc97cc3512eac4c2ebab551b5f7
db_logger.py
db_logger.py
import mysql.connector import config import threading enabled = False db_lock = threading.Lock() conn = mysql.connector.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database')) cur = conn.cursor() def log(message, kind): if enabled: with db_lock: cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW())', (message, kind)) conn.commit()
import mysql.connector import config import threading enabled = False connected = False db_lock = threading.Lock() def log(message, kind): if enabled: with db_lock: global conn, cur, connected if not connected: conn = mysql.connector.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database')) cur = conn.cursor() connected = True cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW())', (message, kind)) conn.commit()
Connect to MySQL only when needed
Connect to MySQL only when needed
Python
mit
kalinochkind/vkbot,kalinochkind/vkbot,kalinochkind/vkbot
import mysql.connector import config import threading enabled = False db_lock = threading.Lock() conn = mysql.connector.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database')) cur = conn.cursor() def log(message, kind): if enabled: with db_lock: cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW())', (message, kind)) conn.commit() Connect to MySQL only when needed
import mysql.connector import config import threading enabled = False connected = False db_lock = threading.Lock() def log(message, kind): if enabled: with db_lock: global conn, cur, connected if not connected: conn = mysql.connector.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database')) cur = conn.cursor() connected = True cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW())', (message, kind)) conn.commit()
<commit_before>import mysql.connector import config import threading enabled = False db_lock = threading.Lock() conn = mysql.connector.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database')) cur = conn.cursor() def log(message, kind): if enabled: with db_lock: cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW())', (message, kind)) conn.commit() <commit_msg>Connect to MySQL only when needed<commit_after>
import mysql.connector import config import threading enabled = False connected = False db_lock = threading.Lock() def log(message, kind): if enabled: with db_lock: global conn, cur, connected if not connected: conn = mysql.connector.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database')) cur = conn.cursor() connected = True cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW())', (message, kind)) conn.commit()
import mysql.connector import config import threading enabled = False db_lock = threading.Lock() conn = mysql.connector.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database')) cur = conn.cursor() def log(message, kind): if enabled: with db_lock: cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW())', (message, kind)) conn.commit() Connect to MySQL only when neededimport mysql.connector import config import threading enabled = False connected = False db_lock = threading.Lock() def log(message, kind): if enabled: with db_lock: global conn, cur, connected if not connected: conn = mysql.connector.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database')) cur = conn.cursor() connected = True cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW())', (message, kind)) conn.commit()
<commit_before>import mysql.connector import config import threading enabled = False db_lock = threading.Lock() conn = mysql.connector.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database')) cur = conn.cursor() def log(message, kind): if enabled: with db_lock: cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW())', (message, kind)) conn.commit() <commit_msg>Connect to MySQL only when needed<commit_after>import mysql.connector import config import threading enabled = False connected = False db_lock = threading.Lock() def log(message, kind): if enabled: with db_lock: global conn, cur, connected if not connected: conn = mysql.connector.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database')) cur = conn.cursor() connected = True cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW())', (message, kind)) conn.commit()
39b6bec6159d147be802e8975ae68fef904d8d19
logger/__init__.py
logger/__init__.py
#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = ["loggers"] from . import loggers from .loggers import * __all__.extend(loggers.__all__)
#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = [] from .loggers import * __all__.extend(loggers.__all__)
Remove redundant import and fix package's __all__
Remove redundant import and fix package's __all__
Python
bsd-2-clause
Vgr255/logging
#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = ["loggers"] from . import loggers from .loggers import * __all__.extend(loggers.__all__) Remove redundant import and fix package's __all__
#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = [] from .loggers import * __all__.extend(loggers.__all__)
<commit_before>#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = ["loggers"] from . import loggers from .loggers import * __all__.extend(loggers.__all__) <commit_msg>Remove redundant import and fix package's __all__<commit_after>
#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = [] from .loggers import * __all__.extend(loggers.__all__)
#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = ["loggers"] from . import loggers from .loggers import * __all__.extend(loggers.__all__) Remove redundant import and fix package's __all__#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = [] from .loggers import * __all__.extend(loggers.__all__)
<commit_before>#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = ["loggers"] from . import loggers from .loggers import * __all__.extend(loggers.__all__) <commit_msg>Remove redundant import and fix package's __all__<commit_after>#!/usr/bin/env python3 """Logging package for specific and general needs. This exposes all the defined loggers, and a generic ready-to-use Logger for general needs, which can be used right away. """ __author__ = "Emanuel 'Vgr' Barry" __version__ = "0.2.3" __status__ = "Mass Refactor [Unstable]" __all__ = [] from .loggers import * __all__.extend(loggers.__all__)
3418b1ef4ade19ccddef92ec059d1629969d8cef
src/lander/ext/parser/_parser.py
src/lander/ext/parser/_parser.py
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.normalize import read_tex_file if TYPE_CHECKING: from pathlib import Path __all__ = ["Parser"] class Parser(metaclass=ABCMeta): """Base class for TeX document metadata parsing extensions. Parameters ---------- tex_path Path to the root tex document. """ def __init__(self, tex_path: Path) -> None: self._tex_path = tex_path self._tex_source = read_tex_file(self.tex_path) self._metadata = self.extract_metadata(self.tex_source) @property def tex_path(self) -> Path: """"Path to the root TeX source file.""" return self._tex_path @property def tex_source(self) -> str: """TeX source, which has been normalized.""" return self._tex_source @property def metadata(self) -> DocumentMetadata: """Metadata about the document.""" return self._metadata @abstractmethod def extract_metadata(self, tex_source: str) -> DocumentMetadata: """Hook for implementing metadata extraction.""" raise NotImplementedError
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.extract import get_macros from lander.ext.parser.texutils.normalize import read_tex_file, replace_macros if TYPE_CHECKING: from pathlib import Path __all__ = ["Parser"] class Parser(metaclass=ABCMeta): """Base class for TeX document metadata parsing extensions. Parameters ---------- tex_path Path to the root tex document. """ def __init__(self, tex_path: Path) -> None: self._tex_path = tex_path self._tex_source = self.normalize_source(read_tex_file(self.tex_path)) self._metadata = self.extract_metadata(self.tex_source) @property def tex_path(self) -> Path: """"Path to the root TeX source file.""" return self._tex_path @property def tex_source(self) -> str: """TeX source, which has been normalized.""" return self._tex_source @property def metadata(self) -> DocumentMetadata: """Metadata about the document.""" return self._metadata def normalize_source(self, tex_source: str) -> str: """Process the TeX source after it is read, but before metadata is extracted. Parameters ---------- tex_source TeX source content. Returns ------- tex_source Normalized TeX source content. """ macros = get_macros(tex_source) return replace_macros(tex_source, macros) @abstractmethod def extract_metadata(self, tex_source: str) -> DocumentMetadata: """Hook for implementing metadata extraction. Parameters ---------- tex_source TeX source content. Returns ------- metadata The metadata parsed from the document source. """ raise NotImplementedError
Add normalize_source hook for parsers
Add normalize_source hook for parsers By default, this hook will replace macros (such as \newcommand) with their content. Parser implementations can do additional work to normalize/resolve TeX content.
Python
mit
lsst-sqre/lander,lsst-sqre/lander
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.normalize import read_tex_file if TYPE_CHECKING: from pathlib import Path __all__ = ["Parser"] class Parser(metaclass=ABCMeta): """Base class for TeX document metadata parsing extensions. Parameters ---------- tex_path Path to the root tex document. """ def __init__(self, tex_path: Path) -> None: self._tex_path = tex_path self._tex_source = read_tex_file(self.tex_path) self._metadata = self.extract_metadata(self.tex_source) @property def tex_path(self) -> Path: """"Path to the root TeX source file.""" return self._tex_path @property def tex_source(self) -> str: """TeX source, which has been normalized.""" return self._tex_source @property def metadata(self) -> DocumentMetadata: """Metadata about the document.""" return self._metadata @abstractmethod def extract_metadata(self, tex_source: str) -> DocumentMetadata: """Hook for implementing metadata extraction.""" raise NotImplementedError Add normalize_source hook for parsers By default, this hook will replace macros (such as \newcommand) with their content. Parser implementations can do additional work to normalize/resolve TeX content.
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.extract import get_macros from lander.ext.parser.texutils.normalize import read_tex_file, replace_macros if TYPE_CHECKING: from pathlib import Path __all__ = ["Parser"] class Parser(metaclass=ABCMeta): """Base class for TeX document metadata parsing extensions. Parameters ---------- tex_path Path to the root tex document. """ def __init__(self, tex_path: Path) -> None: self._tex_path = tex_path self._tex_source = self.normalize_source(read_tex_file(self.tex_path)) self._metadata = self.extract_metadata(self.tex_source) @property def tex_path(self) -> Path: """"Path to the root TeX source file.""" return self._tex_path @property def tex_source(self) -> str: """TeX source, which has been normalized.""" return self._tex_source @property def metadata(self) -> DocumentMetadata: """Metadata about the document.""" return self._metadata def normalize_source(self, tex_source: str) -> str: """Process the TeX source after it is read, but before metadata is extracted. Parameters ---------- tex_source TeX source content. Returns ------- tex_source Normalized TeX source content. """ macros = get_macros(tex_source) return replace_macros(tex_source, macros) @abstractmethod def extract_metadata(self, tex_source: str) -> DocumentMetadata: """Hook for implementing metadata extraction. Parameters ---------- tex_source TeX source content. Returns ------- metadata The metadata parsed from the document source. """ raise NotImplementedError
<commit_before>from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.normalize import read_tex_file if TYPE_CHECKING: from pathlib import Path __all__ = ["Parser"] class Parser(metaclass=ABCMeta): """Base class for TeX document metadata parsing extensions. Parameters ---------- tex_path Path to the root tex document. """ def __init__(self, tex_path: Path) -> None: self._tex_path = tex_path self._tex_source = read_tex_file(self.tex_path) self._metadata = self.extract_metadata(self.tex_source) @property def tex_path(self) -> Path: """"Path to the root TeX source file.""" return self._tex_path @property def tex_source(self) -> str: """TeX source, which has been normalized.""" return self._tex_source @property def metadata(self) -> DocumentMetadata: """Metadata about the document.""" return self._metadata @abstractmethod def extract_metadata(self, tex_source: str) -> DocumentMetadata: """Hook for implementing metadata extraction.""" raise NotImplementedError <commit_msg>Add normalize_source hook for parsers By default, this hook will replace macros (such as \newcommand) with their content. Parser implementations can do additional work to normalize/resolve TeX content.<commit_after>
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.extract import get_macros from lander.ext.parser.texutils.normalize import read_tex_file, replace_macros if TYPE_CHECKING: from pathlib import Path __all__ = ["Parser"] class Parser(metaclass=ABCMeta): """Base class for TeX document metadata parsing extensions. Parameters ---------- tex_path Path to the root tex document. """ def __init__(self, tex_path: Path) -> None: self._tex_path = tex_path self._tex_source = self.normalize_source(read_tex_file(self.tex_path)) self._metadata = self.extract_metadata(self.tex_source) @property def tex_path(self) -> Path: """"Path to the root TeX source file.""" return self._tex_path @property def tex_source(self) -> str: """TeX source, which has been normalized.""" return self._tex_source @property def metadata(self) -> DocumentMetadata: """Metadata about the document.""" return self._metadata def normalize_source(self, tex_source: str) -> str: """Process the TeX source after it is read, but before metadata is extracted. Parameters ---------- tex_source TeX source content. Returns ------- tex_source Normalized TeX source content. """ macros = get_macros(tex_source) return replace_macros(tex_source, macros) @abstractmethod def extract_metadata(self, tex_source: str) -> DocumentMetadata: """Hook for implementing metadata extraction. Parameters ---------- tex_source TeX source content. Returns ------- metadata The metadata parsed from the document source. """ raise NotImplementedError
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.normalize import read_tex_file if TYPE_CHECKING: from pathlib import Path __all__ = ["Parser"] class Parser(metaclass=ABCMeta): """Base class for TeX document metadata parsing extensions. Parameters ---------- tex_path Path to the root tex document. """ def __init__(self, tex_path: Path) -> None: self._tex_path = tex_path self._tex_source = read_tex_file(self.tex_path) self._metadata = self.extract_metadata(self.tex_source) @property def tex_path(self) -> Path: """"Path to the root TeX source file.""" return self._tex_path @property def tex_source(self) -> str: """TeX source, which has been normalized.""" return self._tex_source @property def metadata(self) -> DocumentMetadata: """Metadata about the document.""" return self._metadata @abstractmethod def extract_metadata(self, tex_source: str) -> DocumentMetadata: """Hook for implementing metadata extraction.""" raise NotImplementedError Add normalize_source hook for parsers By default, this hook will replace macros (such as \newcommand) with their content. Parser implementations can do additional work to normalize/resolve TeX content.from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.extract import get_macros from lander.ext.parser.texutils.normalize import read_tex_file, replace_macros if TYPE_CHECKING: from pathlib import Path __all__ = ["Parser"] class Parser(metaclass=ABCMeta): """Base class for TeX document metadata parsing extensions. Parameters ---------- tex_path Path to the root tex document. """ def __init__(self, tex_path: Path) -> None: self._tex_path = tex_path self._tex_source = self.normalize_source(read_tex_file(self.tex_path)) self._metadata = self.extract_metadata(self.tex_source) @property def tex_path(self) -> Path: """"Path to the root TeX source file.""" return self._tex_path @property def tex_source(self) -> str: """TeX source, which has been normalized.""" return self._tex_source @property def metadata(self) -> DocumentMetadata: """Metadata about the document.""" return self._metadata def normalize_source(self, tex_source: str) -> str: """Process the TeX source after it is read, but before metadata is extracted. Parameters ---------- tex_source TeX source content. Returns ------- tex_source Normalized TeX source content. """ macros = get_macros(tex_source) return replace_macros(tex_source, macros) @abstractmethod def extract_metadata(self, tex_source: str) -> DocumentMetadata: """Hook for implementing metadata extraction. Parameters ---------- tex_source TeX source content. Returns ------- metadata The metadata parsed from the document source. """ raise NotImplementedError
<commit_before>from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.normalize import read_tex_file if TYPE_CHECKING: from pathlib import Path __all__ = ["Parser"] class Parser(metaclass=ABCMeta): """Base class for TeX document metadata parsing extensions. Parameters ---------- tex_path Path to the root tex document. """ def __init__(self, tex_path: Path) -> None: self._tex_path = tex_path self._tex_source = read_tex_file(self.tex_path) self._metadata = self.extract_metadata(self.tex_source) @property def tex_path(self) -> Path: """"Path to the root TeX source file.""" return self._tex_path @property def tex_source(self) -> str: """TeX source, which has been normalized.""" return self._tex_source @property def metadata(self) -> DocumentMetadata: """Metadata about the document.""" return self._metadata @abstractmethod def extract_metadata(self, tex_source: str) -> DocumentMetadata: """Hook for implementing metadata extraction.""" raise NotImplementedError <commit_msg>Add normalize_source hook for parsers By default, this hook will replace macros (such as \newcommand) with their content. Parser implementations can do additional work to normalize/resolve TeX content.<commit_after>from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from lander.ext.parser._datamodel import DocumentMetadata from lander.ext.parser.texutils.extract import get_macros from lander.ext.parser.texutils.normalize import read_tex_file, replace_macros if TYPE_CHECKING: from pathlib import Path __all__ = ["Parser"] class Parser(metaclass=ABCMeta): """Base class for TeX document metadata parsing extensions. Parameters ---------- tex_path Path to the root tex document. """ def __init__(self, tex_path: Path) -> None: self._tex_path = tex_path self._tex_source = self.normalize_source(read_tex_file(self.tex_path)) self._metadata = self.extract_metadata(self.tex_source) @property def tex_path(self) -> Path: """"Path to the root TeX source file.""" return self._tex_path @property def tex_source(self) -> str: """TeX source, which has been normalized.""" return self._tex_source @property def metadata(self) -> DocumentMetadata: """Metadata about the document.""" return self._metadata def normalize_source(self, tex_source: str) -> str: """Process the TeX source after it is read, but before metadata is extracted. Parameters ---------- tex_source TeX source content. Returns ------- tex_source Normalized TeX source content. """ macros = get_macros(tex_source) return replace_macros(tex_source, macros) @abstractmethod def extract_metadata(self, tex_source: str) -> DocumentMetadata: """Hook for implementing metadata extraction. Parameters ---------- tex_source TeX source content. Returns ------- metadata The metadata parsed from the document source. """ raise NotImplementedError
668f175fcff4414c6c01de31b8f8d703e9588c5f
Optimization.py
Optimization.py
import copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout def fmin_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout def leastsq_log_params(m, params, *args, **kwargs): func = m.res_log_params pmin, msg = scipy.optimize.leastsq(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout
import copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin) def fmin_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin) def leastsq_log_params(m, params, *args, **kwargs): func = m.res_log_params pmin, msg = scipy.optimize.leastsq(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin)
Fix to handle case where parameters are not passed-in as a KL
Fix to handle case where parameters are not passed-in as a KL
Python
bsd-3-clause
GutenkunstLab/SloppyCell,GutenkunstLab/SloppyCell
import copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout def fmin_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout def leastsq_log_params(m, params, *args, **kwargs): func = m.res_log_params pmin, msg = scipy.optimize.leastsq(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout Fix to handle case where parameters are not passed-in as a KL
import copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin) def fmin_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin) def leastsq_log_params(m, params, *args, **kwargs): func = m.res_log_params pmin, msg = scipy.optimize.leastsq(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin)
<commit_before>import copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout def fmin_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout def leastsq_log_params(m, params, *args, **kwargs): func = m.res_log_params pmin, msg = scipy.optimize.leastsq(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout <commit_msg>Fix to handle case where parameters are not passed-in as a KL<commit_after>
import copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin) def fmin_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin) def leastsq_log_params(m, params, *args, **kwargs): func = m.res_log_params pmin, msg = scipy.optimize.leastsq(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin)
import copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout def fmin_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout def leastsq_log_params(m, params, *args, **kwargs): func = m.res_log_params pmin, msg = scipy.optimize.leastsq(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout Fix to handle case where parameters are not passed-in as a KLimport copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin) def fmin_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin) def leastsq_log_params(m, params, *args, **kwargs): func = m.res_log_params pmin, msg = scipy.optimize.leastsq(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin)
<commit_before>import copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout def fmin_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout def leastsq_log_params(m, params, *args, **kwargs): func = m.res_log_params pmin, msg = scipy.optimize.leastsq(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout <commit_msg>Fix to handle case where parameters are not passed-in as a KL<commit_after>import copy import sys import scipy import SloppyCell.KeyedList_mod as KeyedList_mod KeyedList = KeyedList_mod.KeyedList def fmin_powell_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin_powell(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin) def fmin_log_params(m, params, *args, **kwargs): func = m.cost_log_params pmin = scipy.optimize.fmin(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin) def leastsq_log_params(m, params, *args, **kwargs): func = m.res_log_params pmin, msg = scipy.optimize.leastsq(func, scipy.log(params), *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(pmin)) return pout else: return scipy.exp(pmin)
c9553679d64ea9fe3db40c4c12ca5833c504ab91
mainapp/documents/file.py
mainapp/documents/file.py
from django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', 'name', 'description', 'displayed_filename', 'created', ]
from django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', 'name', 'description', 'displayed_filename', 'parsed_text', 'created', ]
Put parsed_text into the full-text search index
Put parsed_text into the full-text search index
Python
mit
meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent
from django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', 'name', 'description', 'displayed_filename', 'created', ] Put parsed_text into the full-text search index
from django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', 'name', 'description', 'displayed_filename', 'parsed_text', 'created', ]
<commit_before>from django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', 'name', 'description', 'displayed_filename', 'created', ] <commit_msg>Put parsed_text into the full-text search index<commit_after>
from django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', 'name', 'description', 'displayed_filename', 'parsed_text', 'created', ]
from django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', 'name', 'description', 'displayed_filename', 'created', ] Put parsed_text into the full-text search indexfrom django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', 'name', 'description', 'displayed_filename', 'parsed_text', 'created', ]
<commit_before>from django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', 'name', 'description', 'displayed_filename', 'created', ] <commit_msg>Put parsed_text into the full-text search index<commit_after>from django_elasticsearch_dsl import DocType, GeoPointField from mainapp.documents.utils import mainIndex from mainapp.models import File @mainIndex.doc_type class FileDocument(DocType): coordinates = GeoPointField(attr="coordinates") class Meta: model = File fields = [ 'id', 'name', 'description', 'displayed_filename', 'parsed_text', 'created', ]
8280b9d2f9a88e3b52e76405a6a978e85da2b680
oscar/apps/customer/auth_backends.py
oscar/apps/customer/auth_backends.py
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if not email: if not 'username' in kwargs: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if not 'username' in kwargs or kwargs['username'] is None: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user
Correct bug in auth where username=None
Correct bug in auth where username=None
Python
bsd-3-clause
kapt/django-oscar,bschuon/django-oscar,lijoantony/django-oscar,bnprk/django-oscar,pdonadeo/django-oscar,jinnykoo/wuyisj.com,jinnykoo/christmas,monikasulik/django-oscar,machtfit/django-oscar,sonofatailor/django-oscar,marcoantoniooliveira/labweb,spartonia/django-oscar,spartonia/django-oscar,Jannes123/django-oscar,bschuon/django-oscar,taedori81/django-oscar,manevant/django-oscar,elliotthill/django-oscar,dongguangming/django-oscar,saadatqadri/django-oscar,pasqualguerrero/django-oscar,mexeniz/django-oscar,thechampanurag/django-oscar,jinnykoo/wuyisj,saadatqadri/django-oscar,eddiep1101/django-oscar,Jannes123/django-oscar,QLGu/django-oscar,bschuon/django-oscar,sasha0/django-oscar,itbabu/django-oscar,Idematica/django-oscar,taedori81/django-oscar,itbabu/django-oscar,ahmetdaglarbas/e-commerce,Bogh/django-oscar,WillisXChen/django-oscar,mexeniz/django-oscar,amirrpp/django-oscar,ahmetdaglarbas/e-commerce,jinnykoo/wuyisj,ahmetdaglarbas/e-commerce,spartonia/django-oscar,Idematica/django-oscar,WillisXChen/django-oscar,django-oscar/django-oscar,monikasulik/django-oscar,makielab/django-oscar,nickpack/django-oscar,vovanbo/django-oscar,nickpack/django-oscar,django-oscar/django-oscar,binarydud/django-oscar,okfish/django-oscar,solarissmoke/django-oscar,binarydud/django-oscar,dongguangming/django-oscar,bnprk/django-oscar,john-parton/django-oscar,rocopartners/django-oscar,DrOctogon/unwash_ecom,jinnykoo/christmas,thechampanurag/django-oscar,jinnykoo/christmas,Idematica/django-oscar,jinnykoo/wuyisj.com,bschuon/django-oscar,Jannes123/django-oscar,MatthewWilkes/django-oscar,django-oscar/django-oscar,okfish/django-oscar,sasha0/django-oscar,josesanch/django-oscar,nfletton/django-oscar,machtfit/django-oscar,faratro/django-oscar,Jannes123/django-oscar,makielab/django-oscar,manevant/django-oscar,jmt4/django-oscar,spartonia/django-oscar,kapari/django-oscar,QLGu/django-oscar,okfish/django-oscar,kapt/django-oscar,anentropic/django-oscar,WadeYuChen/django-oscar,jlmadurga/django-oscar,eddiep1101/django-oscar,kapt/django-oscar,jinnykoo/wuyisj.com,sasha0/django-oscar,pdonadeo/django-oscar,josesanch/django-oscar,QLGu/django-oscar,solarissmoke/django-oscar,amirrpp/django-oscar,Bogh/django-oscar,faratro/django-oscar,anentropic/django-oscar,josesanch/django-oscar,sasha0/django-oscar,Bogh/django-oscar,taedori81/django-oscar,machtfit/django-oscar,pdonadeo/django-oscar,vovanbo/django-oscar,lijoantony/django-oscar,rocopartners/django-oscar,binarydud/django-oscar,Bogh/django-oscar,adamend/django-oscar,solarissmoke/django-oscar,lijoantony/django-oscar,makielab/django-oscar,makielab/django-oscar,thechampanurag/django-oscar,okfish/django-oscar,MatthewWilkes/django-oscar,kapari/django-oscar,itbabu/django-oscar,lijoantony/django-oscar,adamend/django-oscar,pasqualguerrero/django-oscar,elliotthill/django-oscar,itbabu/django-oscar,ademuk/django-oscar,jinnykoo/wuyisj.com,kapari/django-oscar,marcoantoniooliveira/labweb,sonofatailor/django-oscar,MatthewWilkes/django-oscar,amirrpp/django-oscar,faratro/django-oscar,jmt4/django-oscar,pasqualguerrero/django-oscar,DrOctogon/unwash_ecom,thechampanurag/django-oscar,eddiep1101/django-oscar,django-oscar/django-oscar,michaelkuty/django-oscar,jinnykoo/wuyisj,bnprk/django-oscar,pdonadeo/django-oscar,michaelkuty/django-oscar,nfletton/django-oscar,nfletton/django-oscar,jinnykoo/wuyisj,WadeYuChen/django-oscar,adamend/django-oscar,ka7eh/django-oscar,ka7eh/django-oscar,monikasulik/django-oscar,saadatqadri/django-oscar,WadeYuChen/django-oscar,adamend/django-oscar,michaelkuty/django-oscar,jmt4/django-oscar,manevant/django-oscar,rocopartners/django-oscar,MatthewWilkes/django-oscar,john-parton/django-oscar,nickpack/django-oscar,dongguangming/django-oscar,marcoantoniooliveira/labweb,vovanbo/django-oscar,ka7eh/django-oscar,ademuk/django-oscar,WillisXChen/django-oscar,sonofatailor/django-oscar,anentropic/django-oscar,mexeniz/django-oscar,ademuk/django-oscar,vovanbo/django-oscar,ademuk/django-oscar,bnprk/django-oscar,mexeniz/django-oscar,jlmadurga/django-oscar,WillisXChen/django-oscar,john-parton/django-oscar,rocopartners/django-oscar,faratro/django-oscar,QLGu/django-oscar,monikasulik/django-oscar,solarissmoke/django-oscar,dongguangming/django-oscar,ka7eh/django-oscar,jlmadurga/django-oscar,amirrpp/django-oscar,jlmadurga/django-oscar,WadeYuChen/django-oscar,elliotthill/django-oscar,sonofatailor/django-oscar,saadatqadri/django-oscar,anentropic/django-oscar,DrOctogon/unwash_ecom,michaelkuty/django-oscar,jmt4/django-oscar,WillisXChen/django-oscar,kapari/django-oscar,john-parton/django-oscar,taedori81/django-oscar,nfletton/django-oscar,eddiep1101/django-oscar,manevant/django-oscar,nickpack/django-oscar,marcoantoniooliveira/labweb,WillisXChen/django-oscar,ahmetdaglarbas/e-commerce,pasqualguerrero/django-oscar,binarydud/django-oscar
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if not email: if not 'username' in kwargs: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user Correct bug in auth where username=None
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if not 'username' in kwargs or kwargs['username'] is None: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user
<commit_before>from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if not email: if not 'username' in kwargs: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user <commit_msg>Correct bug in auth where username=None<commit_after>
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if not 'username' in kwargs or kwargs['username'] is None: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user
from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if not email: if not 'username' in kwargs: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user Correct bug in auth where username=Nonefrom django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if not 'username' in kwargs or kwargs['username'] is None: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user
<commit_before>from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if not email: if not 'username' in kwargs: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user <commit_msg>Correct bug in auth where username=None<commit_after>from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class Emailbackend(ModelBackend): def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if not 'username' in kwargs or kwargs['username'] is None: return None email = kwargs['username'] email = email.lower() try: user = User.objects.get(email=email) except User.DoesNotExist: return None if user.check_password(password): return user
d99cedc62dc0e424d676e791eb0d43d92112587a
app/status/views.py
app/status/views.py
from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_wot_got_errors = [] if api_response is None or api_response.status_code is not 200: apis_wot_got_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code is not 200: apis_wot_got_errors.append("Search API") # if no errors found, return everything if not apis_wot_got_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_wot_got_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500
from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_with_errors = [] if api_response is None or api_response.status_code != 200: apis_with_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code != 200: apis_with_errors.append("Search API") # if no errors found, return everything if not apis_with_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_with_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500
Change variable name & int comparison.
Change variable name & int comparison.
Python
mit
alphagov/digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,mtekel/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend
from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_wot_got_errors = [] if api_response is None or api_response.status_code is not 200: apis_wot_got_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code is not 200: apis_wot_got_errors.append("Search API") # if no errors found, return everything if not apis_wot_got_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_wot_got_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500 Change variable name & int comparison.
from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_with_errors = [] if api_response is None or api_response.status_code != 200: apis_with_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code != 200: apis_with_errors.append("Search API") # if no errors found, return everything if not apis_with_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_with_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500
<commit_before>from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_wot_got_errors = [] if api_response is None or api_response.status_code is not 200: apis_wot_got_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code is not 200: apis_wot_got_errors.append("Search API") # if no errors found, return everything if not apis_wot_got_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_wot_got_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500 <commit_msg>Change variable name & int comparison.<commit_after>
from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_with_errors = [] if api_response is None or api_response.status_code != 200: apis_with_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code != 200: apis_with_errors.append("Search API") # if no errors found, return everything if not apis_with_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_with_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500
from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_wot_got_errors = [] if api_response is None or api_response.status_code is not 200: apis_wot_got_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code is not 200: apis_wot_got_errors.append("Search API") # if no errors found, return everything if not apis_wot_got_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_wot_got_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500 Change variable name & int comparison.from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_with_errors = [] if api_response is None or api_response.status_code != 200: apis_with_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code != 200: apis_with_errors.append("Search API") # if no errors found, return everything if not apis_with_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_with_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500
<commit_before>from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_wot_got_errors = [] if api_response is None or api_response.status_code is not 200: apis_wot_got_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code is not 200: apis_wot_got_errors.append("Search API") # if no errors found, return everything if not apis_wot_got_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_wot_got_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500 <commit_msg>Change variable name & int comparison.<commit_after>from flask import jsonify, current_app import json from . import status from . import utils from .. import models @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( models.get_api_status ) search_api_response = utils.return_response_from_api_status_call( models.get_search_api_status ) apis_with_errors = [] if api_response is None or api_response.status_code != 200: apis_with_errors.append("(Data) API") if search_api_response is None \ or search_api_response.status_code != 200: apis_with_errors.append("Search API") # if no errors found, return everything if not apis_with_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), search_api_status=search_api_response.json() ) message = "Error connecting to the " \ + (" and the ".join(apis_with_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), search_api_status=utils.return_json_or_none(search_api_response), message=message, ), 500
9c2bee9fe8442cad0761d196d78baaff37c9cb08
mff_rams_plugin/config.py
mff_rams_plugin/config.py
from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) c.DEALER_BADGE_PRICE = c.BADGE_PRICE
from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) @Config.mixin class ExtraConfig: @property def DEALER_BADGE_PRICE(self): return self.get_attendee_price()
Fix DB errors on stop/re-up Due to the fact that this code was being run before everything else, it would cause server-stopping errors -- but only when starting the server for the first time. It took a little bit to track down, but this is the correct way to override this variable.
Fix DB errors on stop/re-up Due to the fact that this code was being run before everything else, it would cause server-stopping errors -- but only when starting the server for the first time. It took a little bit to track down, but this is the correct way to override this variable.
Python
agpl-3.0
MidwestFurryFandom/mff-rams-plugin,MidwestFurryFandom/mff-rams-plugin
from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) c.DEALER_BADGE_PRICE = c.BADGE_PRICEFix DB errors on stop/re-up Due to the fact that this code was being run before everything else, it would cause server-stopping errors -- but only when starting the server for the first time. It took a little bit to track down, but this is the correct way to override this variable.
from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) @Config.mixin class ExtraConfig: @property def DEALER_BADGE_PRICE(self): return self.get_attendee_price()
<commit_before>from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) c.DEALER_BADGE_PRICE = c.BADGE_PRICE<commit_msg>Fix DB errors on stop/re-up Due to the fact that this code was being run before everything else, it would cause server-stopping errors -- but only when starting the server for the first time. It took a little bit to track down, but this is the correct way to override this variable.<commit_after>
from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) @Config.mixin class ExtraConfig: @property def DEALER_BADGE_PRICE(self): return self.get_attendee_price()
from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) c.DEALER_BADGE_PRICE = c.BADGE_PRICEFix DB errors on stop/re-up Due to the fact that this code was being run before everything else, it would cause server-stopping errors -- but only when starting the server for the first time. It took a little bit to track down, but this is the correct way to override this variable.from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) @Config.mixin class ExtraConfig: @property def DEALER_BADGE_PRICE(self): return self.get_attendee_price()
<commit_before>from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) c.DEALER_BADGE_PRICE = c.BADGE_PRICE<commit_msg>Fix DB errors on stop/re-up Due to the fact that this code was being run before everything else, it would cause server-stopping errors -- but only when starting the server for the first time. It took a little bit to track down, but this is the correct way to override this variable.<commit_after>from uber.common import * config = parse_config(__file__) c.include_plugin_config(config) @Config.mixin class ExtraConfig: @property def DEALER_BADGE_PRICE(self): return self.get_attendee_price()
31a9afb135cc5ffcf634e638e88232b71444d975
modules/raycast/config.py
modules/raycast/config.py
def can_build(env, platform): if platform == "android": return env["android_arch"] in ["arm64v8", "x86", "x86_64"] if platform == "javascript": return False # No SIMD support yet return True def configure(env): pass
def can_build(env, platform): # Depends on Embree library, which supports only x86_64 (originally) # and aarch64 (thanks to the embree-aarch64 fork). if platform == "android": return env["android_arch"] in ["arm64v8", "x86_64"] if platform == "javascript": return False # No SIMD support yet if env["bits"] == "32": return False return True def configure(env): pass
Disable embree-based modules on x86 (32-bit)
SCons: Disable embree-based modules on x86 (32-bit) Fixes #48482. (cherry picked from commit e53422c8f96770c9a9b7497955c84f4b742fdd73)
Python
mit
vkbsb/godot,guilhermefelipecgs/godot,ZuBsPaCe/godot,akien-mga/godot,vkbsb/godot,pkowal1982/godot,godotengine/godot,BastiaanOlij/godot,BastiaanOlij/godot,Zylann/godot,Faless/godot,ZuBsPaCe/godot,ZuBsPaCe/godot,godotengine/godot,josempans/godot,akien-mga/godot,Faless/godot,Valentactive/godot,pkowal1982/godot,godotengine/godot,josempans/godot,josempans/godot,godotengine/godot,ZuBsPaCe/godot,guilhermefelipecgs/godot,BastiaanOlij/godot,akien-mga/godot,godotengine/godot,Zylann/godot,BastiaanOlij/godot,sanikoyes/godot,vnen/godot,guilhermefelipecgs/godot,honix/godot,DmitriySalnikov/godot,Valentactive/godot,DmitriySalnikov/godot,vkbsb/godot,firefly2442/godot,akien-mga/godot,Faless/godot,BastiaanOlij/godot,Zylann/godot,pkowal1982/godot,sanikoyes/godot,vkbsb/godot,BastiaanOlij/godot,vnen/godot,honix/godot,godotengine/godot,vkbsb/godot,Shockblast/godot,Shockblast/godot,Faless/godot,sanikoyes/godot,pkowal1982/godot,Faless/godot,pkowal1982/godot,sanikoyes/godot,akien-mga/godot,josempans/godot,josempans/godot,guilhermefelipecgs/godot,pkowal1982/godot,DmitriySalnikov/godot,BastiaanOlij/godot,vnen/godot,sanikoyes/godot,godotengine/godot,Zylann/godot,akien-mga/godot,vkbsb/godot,firefly2442/godot,honix/godot,Shockblast/godot,pkowal1982/godot,Shockblast/godot,josempans/godot,vkbsb/godot,josempans/godot,Valentactive/godot,vnen/godot,Faless/godot,sanikoyes/godot,Valentactive/godot,guilhermefelipecgs/godot,Shockblast/godot,vnen/godot,sanikoyes/godot,DmitriySalnikov/godot,guilhermefelipecgs/godot,DmitriySalnikov/godot,Faless/godot,DmitriySalnikov/godot,ZuBsPaCe/godot,honix/godot,akien-mga/godot,honix/godot,Valentactive/godot,Zylann/godot,josempans/godot,firefly2442/godot,ZuBsPaCe/godot,firefly2442/godot,Faless/godot,vnen/godot,ZuBsPaCe/godot,akien-mga/godot,ZuBsPaCe/godot,pkowal1982/godot,firefly2442/godot,vnen/godot,guilhermefelipecgs/godot,Zylann/godot,firefly2442/godot,vkbsb/godot,Shockblast/godot,guilhermefelipecgs/godot,firefly2442/godot,Valentactive/godot,Shockblast/godot,sanikoyes/godot,Zylann/godot,DmitriySalnikov/godot,Valentactive/godot,vnen/godot,Valentactive/godot,godotengine/godot,honix/godot,Zylann/godot,firefly2442/godot,Shockblast/godot,BastiaanOlij/godot
def can_build(env, platform): if platform == "android": return env["android_arch"] in ["arm64v8", "x86", "x86_64"] if platform == "javascript": return False # No SIMD support yet return True def configure(env): pass SCons: Disable embree-based modules on x86 (32-bit) Fixes #48482. (cherry picked from commit e53422c8f96770c9a9b7497955c84f4b742fdd73)
def can_build(env, platform): # Depends on Embree library, which supports only x86_64 (originally) # and aarch64 (thanks to the embree-aarch64 fork). if platform == "android": return env["android_arch"] in ["arm64v8", "x86_64"] if platform == "javascript": return False # No SIMD support yet if env["bits"] == "32": return False return True def configure(env): pass
<commit_before>def can_build(env, platform): if platform == "android": return env["android_arch"] in ["arm64v8", "x86", "x86_64"] if platform == "javascript": return False # No SIMD support yet return True def configure(env): pass <commit_msg>SCons: Disable embree-based modules on x86 (32-bit) Fixes #48482. (cherry picked from commit e53422c8f96770c9a9b7497955c84f4b742fdd73)<commit_after>
def can_build(env, platform): # Depends on Embree library, which supports only x86_64 (originally) # and aarch64 (thanks to the embree-aarch64 fork). if platform == "android": return env["android_arch"] in ["arm64v8", "x86_64"] if platform == "javascript": return False # No SIMD support yet if env["bits"] == "32": return False return True def configure(env): pass
def can_build(env, platform): if platform == "android": return env["android_arch"] in ["arm64v8", "x86", "x86_64"] if platform == "javascript": return False # No SIMD support yet return True def configure(env): pass SCons: Disable embree-based modules on x86 (32-bit) Fixes #48482. (cherry picked from commit e53422c8f96770c9a9b7497955c84f4b742fdd73)def can_build(env, platform): # Depends on Embree library, which supports only x86_64 (originally) # and aarch64 (thanks to the embree-aarch64 fork). if platform == "android": return env["android_arch"] in ["arm64v8", "x86_64"] if platform == "javascript": return False # No SIMD support yet if env["bits"] == "32": return False return True def configure(env): pass
<commit_before>def can_build(env, platform): if platform == "android": return env["android_arch"] in ["arm64v8", "x86", "x86_64"] if platform == "javascript": return False # No SIMD support yet return True def configure(env): pass <commit_msg>SCons: Disable embree-based modules on x86 (32-bit) Fixes #48482. (cherry picked from commit e53422c8f96770c9a9b7497955c84f4b742fdd73)<commit_after>def can_build(env, platform): # Depends on Embree library, which supports only x86_64 (originally) # and aarch64 (thanks to the embree-aarch64 fork). if platform == "android": return env["android_arch"] in ["arm64v8", "x86_64"] if platform == "javascript": return False # No SIMD support yet if env["bits"] == "32": return False return True def configure(env): pass
4f9e70866e688ce29096586c8abcf23ef633084f
mqtt/tests/test_client.py
mqtt/tests/test_client.py
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(MQTTTestCase): def test_mqttseed(self): self.assertEqual(True, True)
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTT1(MQTTTestCase): def test(self): self.assertEqual(True, True) class TestMQTT2(MQTTTestCase): def test(self): self.assertEqual(True, True)
Add more time to mqtt.test.client
Add more time to mqtt.test.client
Python
bsd-3-clause
EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(MQTTTestCase): def test_mqttseed(self): self.assertEqual(True, True) Add more time to mqtt.test.client
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTT1(MQTTTestCase): def test(self): self.assertEqual(True, True) class TestMQTT2(MQTTTestCase): def test(self): self.assertEqual(True, True)
<commit_before>import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(MQTTTestCase): def test_mqttseed(self): self.assertEqual(True, True) <commit_msg>Add more time to mqtt.test.client<commit_after>
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTT1(MQTTTestCase): def test(self): self.assertEqual(True, True) class TestMQTT2(MQTTTestCase): def test(self): self.assertEqual(True, True)
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(MQTTTestCase): def test_mqttseed(self): self.assertEqual(True, True) Add more time to mqtt.test.clientimport time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTT1(MQTTTestCase): def test(self): self.assertEqual(True, True) class TestMQTT2(MQTTTestCase): def test(self): self.assertEqual(True, True)
<commit_before>import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTTSeed(MQTTTestCase): def test_mqttseed(self): self.assertEqual(True, True) <commit_msg>Add more time to mqtt.test.client<commit_after>import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalPermission from login.serializers import ExtendedProfileSerializer from ambulance.models import Ambulance, \ AmbulanceStatus, AmbulanceCapability from ambulance.serializers import AmbulanceSerializer from hospital.models import Hospital, \ Equipment, HospitalEquipment, EquipmentType from hospital.serializers import EquipmentSerializer, \ HospitalSerializer, HospitalEquipmentSerializer from django.test import Client from .client import MQTTTestCase, MQTTTestClient from ..client import MQTTException from ..subscribe import SubscribeClient class TestMQTT1(MQTTTestCase): def test(self): self.assertEqual(True, True) class TestMQTT2(MQTTTestCase): def test(self): self.assertEqual(True, True)
9fb89f885dd26b530b4cc95427373f06ddc7d13d
emptiness.py
emptiness.py
#!/bin/python import argparse import requests import timetable if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=True, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=True, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(args.day, args.time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el)
#!/bin/python import argparse import requests import timetable import datetime import time if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=False, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=False, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() time = args.time day = args.day if args.time == '': time = datetime.datetime.now().strftime("%H:%M") if args.day == '': day = datetime.datetime.now().strftime("%A") # print('Using ' + day + ' - ' + time) htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(day, time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el)
Use current time if no arguments given
Use current time if no arguments given
Python
mit
egeldenhuys/emptiness,egeldenhuys/emptiness,egeldenhuys/emptiness
#!/bin/python import argparse import requests import timetable if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=True, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=True, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(args.day, args.time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el) Use current time if no arguments given
#!/bin/python import argparse import requests import timetable import datetime import time if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=False, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=False, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() time = args.time day = args.day if args.time == '': time = datetime.datetime.now().strftime("%H:%M") if args.day == '': day = datetime.datetime.now().strftime("%A") # print('Using ' + day + ' - ' + time) htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(day, time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el)
<commit_before>#!/bin/python import argparse import requests import timetable if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=True, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=True, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(args.day, args.time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el) <commit_msg>Use current time if no arguments given<commit_after>
#!/bin/python import argparse import requests import timetable import datetime import time if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=False, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=False, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() time = args.time day = args.day if args.time == '': time = datetime.datetime.now().strftime("%H:%M") if args.day == '': day = datetime.datetime.now().strftime("%A") # print('Using ' + day + ' - ' + time) htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(day, time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el)
#!/bin/python import argparse import requests import timetable if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=True, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=True, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(args.day, args.time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el) Use current time if no arguments given#!/bin/python import argparse import requests import timetable import datetime import time if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=False, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=False, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() time = args.time day = args.day if args.time == '': time = datetime.datetime.now().strftime("%H:%M") if args.day == '': day = datetime.datetime.now().strftime("%A") # print('Using ' + day + ' - ' + time) htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(day, time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el)
<commit_before>#!/bin/python import argparse import requests import timetable if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=True, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=True, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(args.day, args.time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el) <commit_msg>Use current time if no arguments given<commit_after>#!/bin/python import argparse import requests import timetable import datetime import time if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--day", default='', required=False, help="Day to check the timetable on. eg: Thursday") parser.add_argument("-t", "--time", default='', required=False, help="The time the block must be empty (HH:MM (24h))") args = parser.parse_args() time = args.time day = args.day if args.time == '': time = datetime.datetime.now().strftime("%H:%M") if args.day == '': day = datetime.datetime.now().strftime("%A") # print('Using ' + day + ' - ' + time) htmlRequest = requests.get("http://upnet.up.ac.za/tt/hatfield_timetable.html") timeTableObject = timetable.parseHTMLFile(htmlRequest.text) # Method 1 ; Elimination venueList = timetable.getVenueList(timeTableObject) filteredTimetable = timetable.getFilteredTimetable(day, time, timeTableObject, venueList) #for el in filteredTimetable: # print(el.venue) empty = timetable.getEmptyVenues(filteredTimetable, venueList) for el in empty: print(el)
37b426a869d1dad5d3ad8c83fc8d3cb3c655dbbd
src/olympia/discovery/serializers.py
src/olympia/discovery/serializers.py
from rest_framework import serializers from olympia.addons.models import Addon from olympia.addons.serializers import AddonSerializer, VersionSerializer from olympia.versions.models import Version class DiscoveryVersionSerializer(VersionSerializer): class Meta: fields = ('compatibility', 'files',) model = Version class DiscoveryAddonSerializer(AddonSerializer): current_version = DiscoveryVersionSerializer() class Meta: fields = ('id', 'current_version', 'icon_url', 'theme_data', 'type', 'url',) model = Addon class DiscoverySerializer(serializers.Serializer): heading = serializers.CharField() description = serializers.CharField() addon = DiscoveryAddonSerializer() def to_representation(self, instance): data = super(DiscoverySerializer, self).to_representation(instance) if data['heading'] is None: if instance.addon.listed_authors: data['heading'] = u'%s by %s' % ( unicode(instance.addon.name), instance.addon.listed_authors[0].name) else: data['heading'] = unicode(instance.addon.name) return data
from rest_framework import serializers from olympia.addons.models import Addon from olympia.addons.serializers import AddonSerializer, VersionSerializer from olympia.versions.models import Version class DiscoveryVersionSerializer(VersionSerializer): class Meta: fields = ('compatibility', 'files',) model = Version class DiscoveryAddonSerializer(AddonSerializer): current_version = DiscoveryVersionSerializer() class Meta: fields = ('id', 'current_version', 'guid', 'icon_url', 'theme_data', 'type', 'url',) model = Addon class DiscoverySerializer(serializers.Serializer): heading = serializers.CharField() description = serializers.CharField() addon = DiscoveryAddonSerializer() def to_representation(self, instance): data = super(DiscoverySerializer, self).to_representation(instance) if data['heading'] is None: if instance.addon.listed_authors: data['heading'] = u'%s by %s' % ( unicode(instance.addon.name), instance.addon.listed_authors[0].name) else: data['heading'] = unicode(instance.addon.name) return data
Add back guid in the discovery pane API
Add back guid in the discovery pane API
Python
bsd-3-clause
harry-7/addons-server,kumar303/olympia,harry-7/addons-server,eviljeff/olympia,harikishen/addons-server,mstriemer/addons-server,aviarypl/mozilla-l10n-addons-server,wagnerand/olympia,mozilla/olympia,wagnerand/addons-server,wagnerand/olympia,psiinon/addons-server,atiqueahmedziad/addons-server,mstriemer/olympia,Revanth47/addons-server,bqbn/addons-server,mstriemer/addons-server,mstriemer/olympia,mozilla/addons-server,diox/olympia,tsl143/addons-server,Prashant-Surya/addons-server,harikishen/addons-server,Prashant-Surya/addons-server,eviljeff/olympia,kumar303/olympia,kumar303/addons-server,Prashant-Surya/addons-server,wagnerand/addons-server,mstriemer/addons-server,diox/olympia,harikishen/addons-server,lavish205/olympia,harikishen/addons-server,atiqueahmedziad/addons-server,lavish205/olympia,Revanth47/addons-server,Revanth47/addons-server,mstriemer/addons-server,mozilla/olympia,psiinon/addons-server,mozilla/olympia,wagnerand/addons-server,mozilla/addons-server,kumar303/olympia,mozilla/addons-server,mstriemer/olympia,lavish205/olympia,eviljeff/olympia,mstriemer/olympia,psiinon/addons-server,bqbn/addons-server,mozilla/addons-server,kumar303/olympia,Revanth47/addons-server,kumar303/addons-server,kumar303/addons-server,diox/olympia,wagnerand/olympia,psiinon/addons-server,bqbn/addons-server,wagnerand/olympia,atiqueahmedziad/addons-server,harry-7/addons-server,aviarypl/mozilla-l10n-addons-server,wagnerand/addons-server,tsl143/addons-server,aviarypl/mozilla-l10n-addons-server,eviljeff/olympia,Prashant-Surya/addons-server,kumar303/addons-server,aviarypl/mozilla-l10n-addons-server,atiqueahmedziad/addons-server,tsl143/addons-server,lavish205/olympia,bqbn/addons-server,tsl143/addons-server,diox/olympia,harry-7/addons-server,mozilla/olympia
from rest_framework import serializers from olympia.addons.models import Addon from olympia.addons.serializers import AddonSerializer, VersionSerializer from olympia.versions.models import Version class DiscoveryVersionSerializer(VersionSerializer): class Meta: fields = ('compatibility', 'files',) model = Version class DiscoveryAddonSerializer(AddonSerializer): current_version = DiscoveryVersionSerializer() class Meta: fields = ('id', 'current_version', 'icon_url', 'theme_data', 'type', 'url',) model = Addon class DiscoverySerializer(serializers.Serializer): heading = serializers.CharField() description = serializers.CharField() addon = DiscoveryAddonSerializer() def to_representation(self, instance): data = super(DiscoverySerializer, self).to_representation(instance) if data['heading'] is None: if instance.addon.listed_authors: data['heading'] = u'%s by %s' % ( unicode(instance.addon.name), instance.addon.listed_authors[0].name) else: data['heading'] = unicode(instance.addon.name) return data Add back guid in the discovery pane API
from rest_framework import serializers from olympia.addons.models import Addon from olympia.addons.serializers import AddonSerializer, VersionSerializer from olympia.versions.models import Version class DiscoveryVersionSerializer(VersionSerializer): class Meta: fields = ('compatibility', 'files',) model = Version class DiscoveryAddonSerializer(AddonSerializer): current_version = DiscoveryVersionSerializer() class Meta: fields = ('id', 'current_version', 'guid', 'icon_url', 'theme_data', 'type', 'url',) model = Addon class DiscoverySerializer(serializers.Serializer): heading = serializers.CharField() description = serializers.CharField() addon = DiscoveryAddonSerializer() def to_representation(self, instance): data = super(DiscoverySerializer, self).to_representation(instance) if data['heading'] is None: if instance.addon.listed_authors: data['heading'] = u'%s by %s' % ( unicode(instance.addon.name), instance.addon.listed_authors[0].name) else: data['heading'] = unicode(instance.addon.name) return data
<commit_before>from rest_framework import serializers from olympia.addons.models import Addon from olympia.addons.serializers import AddonSerializer, VersionSerializer from olympia.versions.models import Version class DiscoveryVersionSerializer(VersionSerializer): class Meta: fields = ('compatibility', 'files',) model = Version class DiscoveryAddonSerializer(AddonSerializer): current_version = DiscoveryVersionSerializer() class Meta: fields = ('id', 'current_version', 'icon_url', 'theme_data', 'type', 'url',) model = Addon class DiscoverySerializer(serializers.Serializer): heading = serializers.CharField() description = serializers.CharField() addon = DiscoveryAddonSerializer() def to_representation(self, instance): data = super(DiscoverySerializer, self).to_representation(instance) if data['heading'] is None: if instance.addon.listed_authors: data['heading'] = u'%s by %s' % ( unicode(instance.addon.name), instance.addon.listed_authors[0].name) else: data['heading'] = unicode(instance.addon.name) return data <commit_msg>Add back guid in the discovery pane API<commit_after>
from rest_framework import serializers from olympia.addons.models import Addon from olympia.addons.serializers import AddonSerializer, VersionSerializer from olympia.versions.models import Version class DiscoveryVersionSerializer(VersionSerializer): class Meta: fields = ('compatibility', 'files',) model = Version class DiscoveryAddonSerializer(AddonSerializer): current_version = DiscoveryVersionSerializer() class Meta: fields = ('id', 'current_version', 'guid', 'icon_url', 'theme_data', 'type', 'url',) model = Addon class DiscoverySerializer(serializers.Serializer): heading = serializers.CharField() description = serializers.CharField() addon = DiscoveryAddonSerializer() def to_representation(self, instance): data = super(DiscoverySerializer, self).to_representation(instance) if data['heading'] is None: if instance.addon.listed_authors: data['heading'] = u'%s by %s' % ( unicode(instance.addon.name), instance.addon.listed_authors[0].name) else: data['heading'] = unicode(instance.addon.name) return data
from rest_framework import serializers from olympia.addons.models import Addon from olympia.addons.serializers import AddonSerializer, VersionSerializer from olympia.versions.models import Version class DiscoveryVersionSerializer(VersionSerializer): class Meta: fields = ('compatibility', 'files',) model = Version class DiscoveryAddonSerializer(AddonSerializer): current_version = DiscoveryVersionSerializer() class Meta: fields = ('id', 'current_version', 'icon_url', 'theme_data', 'type', 'url',) model = Addon class DiscoverySerializer(serializers.Serializer): heading = serializers.CharField() description = serializers.CharField() addon = DiscoveryAddonSerializer() def to_representation(self, instance): data = super(DiscoverySerializer, self).to_representation(instance) if data['heading'] is None: if instance.addon.listed_authors: data['heading'] = u'%s by %s' % ( unicode(instance.addon.name), instance.addon.listed_authors[0].name) else: data['heading'] = unicode(instance.addon.name) return data Add back guid in the discovery pane APIfrom rest_framework import serializers from olympia.addons.models import Addon from olympia.addons.serializers import AddonSerializer, VersionSerializer from olympia.versions.models import Version class DiscoveryVersionSerializer(VersionSerializer): class Meta: fields = ('compatibility', 'files',) model = Version class DiscoveryAddonSerializer(AddonSerializer): current_version = DiscoveryVersionSerializer() class Meta: fields = ('id', 'current_version', 'guid', 'icon_url', 'theme_data', 'type', 'url',) model = Addon class DiscoverySerializer(serializers.Serializer): heading = serializers.CharField() description = serializers.CharField() addon = DiscoveryAddonSerializer() def to_representation(self, instance): data = super(DiscoverySerializer, self).to_representation(instance) if data['heading'] is None: if instance.addon.listed_authors: data['heading'] = u'%s by %s' % ( unicode(instance.addon.name), instance.addon.listed_authors[0].name) else: data['heading'] = unicode(instance.addon.name) return data
<commit_before>from rest_framework import serializers from olympia.addons.models import Addon from olympia.addons.serializers import AddonSerializer, VersionSerializer from olympia.versions.models import Version class DiscoveryVersionSerializer(VersionSerializer): class Meta: fields = ('compatibility', 'files',) model = Version class DiscoveryAddonSerializer(AddonSerializer): current_version = DiscoveryVersionSerializer() class Meta: fields = ('id', 'current_version', 'icon_url', 'theme_data', 'type', 'url',) model = Addon class DiscoverySerializer(serializers.Serializer): heading = serializers.CharField() description = serializers.CharField() addon = DiscoveryAddonSerializer() def to_representation(self, instance): data = super(DiscoverySerializer, self).to_representation(instance) if data['heading'] is None: if instance.addon.listed_authors: data['heading'] = u'%s by %s' % ( unicode(instance.addon.name), instance.addon.listed_authors[0].name) else: data['heading'] = unicode(instance.addon.name) return data <commit_msg>Add back guid in the discovery pane API<commit_after>from rest_framework import serializers from olympia.addons.models import Addon from olympia.addons.serializers import AddonSerializer, VersionSerializer from olympia.versions.models import Version class DiscoveryVersionSerializer(VersionSerializer): class Meta: fields = ('compatibility', 'files',) model = Version class DiscoveryAddonSerializer(AddonSerializer): current_version = DiscoveryVersionSerializer() class Meta: fields = ('id', 'current_version', 'guid', 'icon_url', 'theme_data', 'type', 'url',) model = Addon class DiscoverySerializer(serializers.Serializer): heading = serializers.CharField() description = serializers.CharField() addon = DiscoveryAddonSerializer() def to_representation(self, instance): data = super(DiscoverySerializer, self).to_representation(instance) if data['heading'] is None: if instance.addon.listed_authors: data['heading'] = u'%s by %s' % ( unicode(instance.addon.name), instance.addon.listed_authors[0].name) else: data['heading'] = unicode(instance.addon.name) return data
bf7f2c90f171efb3a631956a15f2c3ed50b5202e
lc0172_factorial_trailing_zeroes.py
lc0172_factorial_trailing_zeroes.py
"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int Time complexity: O(log_5 n). Space complexity: O(1). """ zeros = 0 temp = n while temp // 5 > 0: temp = temp // 5 zeros += temp return zeros def main(): # Ans: 0 n = 3 print Solution().trailingZeroes(n) # Ans: 1 n = 5 print Solution().trailingZeroes(n) if __name__ == '__main__': main()
"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int Time complexity: O(log_5 n). Space complexity: O(1). """ zeros = 0 current = n while current // 5 > 0: current = current // 5 zeros += current return zeros def main(): # Ans: 0 n = 3 print Solution().trailingZeroes(n) # Ans: 6 n = 25 print Solution().trailingZeroes(n) if __name__ == '__main__': main()
Refactor codes and revise main
Refactor codes and revise main
Python
bsd-2-clause
bowen0701/algorithms_data_structures
"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int Time complexity: O(log_5 n). Space complexity: O(1). """ zeros = 0 temp = n while temp // 5 > 0: temp = temp // 5 zeros += temp return zeros def main(): # Ans: 0 n = 3 print Solution().trailingZeroes(n) # Ans: 1 n = 5 print Solution().trailingZeroes(n) if __name__ == '__main__': main() Refactor codes and revise main
"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int Time complexity: O(log_5 n). Space complexity: O(1). """ zeros = 0 current = n while current // 5 > 0: current = current // 5 zeros += current return zeros def main(): # Ans: 0 n = 3 print Solution().trailingZeroes(n) # Ans: 6 n = 25 print Solution().trailingZeroes(n) if __name__ == '__main__': main()
<commit_before>"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int Time complexity: O(log_5 n). Space complexity: O(1). """ zeros = 0 temp = n while temp // 5 > 0: temp = temp // 5 zeros += temp return zeros def main(): # Ans: 0 n = 3 print Solution().trailingZeroes(n) # Ans: 1 n = 5 print Solution().trailingZeroes(n) if __name__ == '__main__': main() <commit_msg>Refactor codes and revise main<commit_after>
"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int Time complexity: O(log_5 n). Space complexity: O(1). """ zeros = 0 current = n while current // 5 > 0: current = current // 5 zeros += current return zeros def main(): # Ans: 0 n = 3 print Solution().trailingZeroes(n) # Ans: 6 n = 25 print Solution().trailingZeroes(n) if __name__ == '__main__': main()
"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int Time complexity: O(log_5 n). Space complexity: O(1). """ zeros = 0 temp = n while temp // 5 > 0: temp = temp // 5 zeros += temp return zeros def main(): # Ans: 0 n = 3 print Solution().trailingZeroes(n) # Ans: 1 n = 5 print Solution().trailingZeroes(n) if __name__ == '__main__': main() Refactor codes and revise main"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int Time complexity: O(log_5 n). Space complexity: O(1). """ zeros = 0 current = n while current // 5 > 0: current = current // 5 zeros += current return zeros def main(): # Ans: 0 n = 3 print Solution().trailingZeroes(n) # Ans: 6 n = 25 print Solution().trailingZeroes(n) if __name__ == '__main__': main()
<commit_before>"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int Time complexity: O(log_5 n). Space complexity: O(1). """ zeros = 0 temp = n while temp // 5 > 0: temp = temp // 5 zeros += temp return zeros def main(): # Ans: 0 n = 3 print Solution().trailingZeroes(n) # Ans: 1 n = 5 print Solution().trailingZeroes(n) if __name__ == '__main__': main() <commit_msg>Refactor codes and revise main<commit_after>"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int Time complexity: O(log_5 n). Space complexity: O(1). """ zeros = 0 current = n while current // 5 > 0: current = current // 5 zeros += current return zeros def main(): # Ans: 0 n = 3 print Solution().trailingZeroes(n) # Ans: 6 n = 25 print Solution().trailingZeroes(n) if __name__ == '__main__': main()
072774a36c82c3654cdabc6ebfd677b8603db49f
src/models/image.py
src/models/image.py
from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file)
import datetime from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain self.created = datetime.datetime.fromtimestamp(post.created).strftime("%y%m%d") if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.created, self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file)
Add a timestamp to the filename to allow for chronological ordering in the filesystem
Add a timestamp to the filename to allow for chronological ordering in the filesystem
Python
apache-2.0
CharlieCorner/pymage_downloader
from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file) Add a timestamp to the filename to allow for chronological ordering in the filesystem
import datetime from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain self.created = datetime.datetime.fromtimestamp(post.created).strftime("%y%m%d") if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.created, self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file)
<commit_before>from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file) <commit_msg>Add a timestamp to the filename to allow for chronological ordering in the filesystem<commit_after>
import datetime from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain self.created = datetime.datetime.fromtimestamp(post.created).strftime("%y%m%d") if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.created, self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file)
from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file) Add a timestamp to the filename to allow for chronological ordering in the filesystemimport datetime from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain self.created = datetime.datetime.fromtimestamp(post.created).strftime("%y%m%d") if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.created, self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file)
<commit_before>from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file) <commit_msg>Add a timestamp to the filename to allow for chronological ordering in the filesystem<commit_after>import datetime from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain self.created = datetime.datetime.fromtimestamp(post.created).strftime("%y%m%d") if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.created, self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file)
aaa0f03a91f3326dc893175510a4ad35649ec371
pltpreview/view.py
pltpreview/view.py
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. """ blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') plt.plot(*args, **kwargs) plt.show(blocking)
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. This command always creates a new figure. """ blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') plt.figure() plt.plot(*args, **kwargs) plt.show(blocking)
Create new figure in plot command
Create new figure in plot command
Python
mit
tfarago/pltpreview
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. """ blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') plt.plot(*args, **kwargs) plt.show(blocking) Create new figure in plot command
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. This command always creates a new figure. """ blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') plt.figure() plt.plot(*args, **kwargs) plt.show(blocking)
<commit_before>"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. """ blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') plt.plot(*args, **kwargs) plt.show(blocking) <commit_msg>Create new figure in plot command<commit_after>
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. This command always creates a new figure. """ blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') plt.figure() plt.plot(*args, **kwargs) plt.show(blocking)
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. """ blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') plt.plot(*args, **kwargs) plt.show(blocking) Create new figure in plot command"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. This command always creates a new figure. """ blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') plt.figure() plt.plot(*args, **kwargs) plt.show(blocking)
<commit_before>"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. """ blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') plt.plot(*args, **kwargs) plt.show(blocking) <commit_msg>Create new figure in plot command<commit_after>"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command always creates a new figure. Returns matplotlib's ``AxesImage``. """ plt.figure() mpl_image = plt.imshow(image, **kwargs) plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8)) plt.show(blocking) return mpl_image def plot(*args, **kwargs): """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*. *kwargs* are infected with *blocking* and if False or not specified, the call is nonblocking. This command always creates a new figure. """ blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking') plt.figure() plt.plot(*args, **kwargs) plt.show(blocking)
48087c2cc8cd9d0bb84014ea4b91fe2f68f958c4
gant/utils/docker_helper.py
gant/utils/docker_helper.py
# Helper functions for docker import docker import os DEFAULT_DOCKER_API_VERSION = '1.10' BASEIMAGETAG = "glusterbase:latest" GLUSTERIMAGENAME = "gluster:latest" BASEDIR=os.getcwd() class DockerHelper (docker.Client): """ Extended docker client with some helper functions """ def __init__ (self): super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION) def image_by_id (self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), None) def image_by_tag(self, tag): """ Return image with given tag """ if not tag: return None return next((image for image in self.images() if tag in image['RepoTags']), None) def image_exists (self, id = None, tag = None): """ Check if specified image exists """ exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag (tag): exists = True return exists
# Helper functions for docker import docker import os DEFAULT_DOCKER_API_VERSION = '1.10' BASEIMAGETAG = "glusterbase:latest" GLUSTERIMAGENAME = "gluster:latest" BASEDIR=os.getcwd() class DockerHelper (docker.Client): """ Extended docker client with some helper functions """ def __init__ (self): super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION) def image_by_id (self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), None) def image_by_tag(self, tag): """ Return image with given tag """ if not tag: return None return next((image for image in self.images() if tag in image['RepoTags']), None) def image_exists (self, id = None, tag = None): """ Check if specified image exists """ exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag (tag): exists = True return exists def container_ip (self, container): """ Returns the internal ip of the container if available """ info = self.inspect_container(container) if not info: return None netInfo = info['NetworkSettings'] if not netInfo: return None ip = netInfo['IPAddress'] if not ip: return None return ip
Add docker helper to get ip
Add docker helper to get ip
Python
bsd-2-clause
kshlm/gant
# Helper functions for docker import docker import os DEFAULT_DOCKER_API_VERSION = '1.10' BASEIMAGETAG = "glusterbase:latest" GLUSTERIMAGENAME = "gluster:latest" BASEDIR=os.getcwd() class DockerHelper (docker.Client): """ Extended docker client with some helper functions """ def __init__ (self): super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION) def image_by_id (self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), None) def image_by_tag(self, tag): """ Return image with given tag """ if not tag: return None return next((image for image in self.images() if tag in image['RepoTags']), None) def image_exists (self, id = None, tag = None): """ Check if specified image exists """ exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag (tag): exists = True return exists Add docker helper to get ip
# Helper functions for docker import docker import os DEFAULT_DOCKER_API_VERSION = '1.10' BASEIMAGETAG = "glusterbase:latest" GLUSTERIMAGENAME = "gluster:latest" BASEDIR=os.getcwd() class DockerHelper (docker.Client): """ Extended docker client with some helper functions """ def __init__ (self): super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION) def image_by_id (self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), None) def image_by_tag(self, tag): """ Return image with given tag """ if not tag: return None return next((image for image in self.images() if tag in image['RepoTags']), None) def image_exists (self, id = None, tag = None): """ Check if specified image exists """ exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag (tag): exists = True return exists def container_ip (self, container): """ Returns the internal ip of the container if available """ info = self.inspect_container(container) if not info: return None netInfo = info['NetworkSettings'] if not netInfo: return None ip = netInfo['IPAddress'] if not ip: return None return ip
<commit_before># Helper functions for docker import docker import os DEFAULT_DOCKER_API_VERSION = '1.10' BASEIMAGETAG = "glusterbase:latest" GLUSTERIMAGENAME = "gluster:latest" BASEDIR=os.getcwd() class DockerHelper (docker.Client): """ Extended docker client with some helper functions """ def __init__ (self): super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION) def image_by_id (self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), None) def image_by_tag(self, tag): """ Return image with given tag """ if not tag: return None return next((image for image in self.images() if tag in image['RepoTags']), None) def image_exists (self, id = None, tag = None): """ Check if specified image exists """ exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag (tag): exists = True return exists <commit_msg>Add docker helper to get ip<commit_after>
# Helper functions for docker import docker import os DEFAULT_DOCKER_API_VERSION = '1.10' BASEIMAGETAG = "glusterbase:latest" GLUSTERIMAGENAME = "gluster:latest" BASEDIR=os.getcwd() class DockerHelper (docker.Client): """ Extended docker client with some helper functions """ def __init__ (self): super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION) def image_by_id (self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), None) def image_by_tag(self, tag): """ Return image with given tag """ if not tag: return None return next((image for image in self.images() if tag in image['RepoTags']), None) def image_exists (self, id = None, tag = None): """ Check if specified image exists """ exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag (tag): exists = True return exists def container_ip (self, container): """ Returns the internal ip of the container if available """ info = self.inspect_container(container) if not info: return None netInfo = info['NetworkSettings'] if not netInfo: return None ip = netInfo['IPAddress'] if not ip: return None return ip
# Helper functions for docker import docker import os DEFAULT_DOCKER_API_VERSION = '1.10' BASEIMAGETAG = "glusterbase:latest" GLUSTERIMAGENAME = "gluster:latest" BASEDIR=os.getcwd() class DockerHelper (docker.Client): """ Extended docker client with some helper functions """ def __init__ (self): super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION) def image_by_id (self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), None) def image_by_tag(self, tag): """ Return image with given tag """ if not tag: return None return next((image for image in self.images() if tag in image['RepoTags']), None) def image_exists (self, id = None, tag = None): """ Check if specified image exists """ exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag (tag): exists = True return exists Add docker helper to get ip# Helper functions for docker import docker import os DEFAULT_DOCKER_API_VERSION = '1.10' BASEIMAGETAG = "glusterbase:latest" GLUSTERIMAGENAME = "gluster:latest" BASEDIR=os.getcwd() class DockerHelper (docker.Client): """ Extended docker client with some helper functions """ def __init__ (self): super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION) def image_by_id (self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), None) def image_by_tag(self, tag): """ Return image with given tag """ if not tag: return None return next((image for image in self.images() if tag in image['RepoTags']), None) def image_exists (self, id = None, tag = None): """ Check if specified image exists """ exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag (tag): exists = True return exists def container_ip (self, container): """ Returns the internal ip of the container if available """ info = self.inspect_container(container) if not info: return None netInfo = info['NetworkSettings'] if not netInfo: return None ip = netInfo['IPAddress'] if not ip: return None return ip
<commit_before># Helper functions for docker import docker import os DEFAULT_DOCKER_API_VERSION = '1.10' BASEIMAGETAG = "glusterbase:latest" GLUSTERIMAGENAME = "gluster:latest" BASEDIR=os.getcwd() class DockerHelper (docker.Client): """ Extended docker client with some helper functions """ def __init__ (self): super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION) def image_by_id (self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), None) def image_by_tag(self, tag): """ Return image with given tag """ if not tag: return None return next((image for image in self.images() if tag in image['RepoTags']), None) def image_exists (self, id = None, tag = None): """ Check if specified image exists """ exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag (tag): exists = True return exists <commit_msg>Add docker helper to get ip<commit_after># Helper functions for docker import docker import os DEFAULT_DOCKER_API_VERSION = '1.10' BASEIMAGETAG = "glusterbase:latest" GLUSTERIMAGENAME = "gluster:latest" BASEDIR=os.getcwd() class DockerHelper (docker.Client): """ Extended docker client with some helper functions """ def __init__ (self): super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION) def image_by_id (self, id): """ Return image with given Id """ if not id: return None return next((image for image in self.images() if image['Id'] == id), None) def image_by_tag(self, tag): """ Return image with given tag """ if not tag: return None return next((image for image in self.images() if tag in image['RepoTags']), None) def image_exists (self, id = None, tag = None): """ Check if specified image exists """ exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag (tag): exists = True return exists def container_ip (self, container): """ Returns the internal ip of the container if available """ info = self.inspect_container(container) if not info: return None netInfo = info['NetworkSettings'] if not netInfo: return None ip = netInfo['IPAddress'] if not ip: return None return ip
512ae6bd0ce42dc659f7cf4766fdc80587718909
go/apps/jsbox/definition.py
go/apps/jsbox/definition.py
import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): # TODO: make jsbox apps define these explicitly and # update the outbound resource to check and # complain if a jsbox app sends on an endpoint # it hasn't defined. app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints)
import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints)
Remove ancient TODO that was resolved a long time ago.
Remove ancient TODO that was resolved a long time ago.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): # TODO: make jsbox apps define these explicitly and # update the outbound resource to check and # complain if a jsbox app sends on an endpoint # it hasn't defined. app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints) Remove ancient TODO that was resolved a long time ago.
import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints)
<commit_before>import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): # TODO: make jsbox apps define these explicitly and # update the outbound resource to check and # complain if a jsbox app sends on an endpoint # it hasn't defined. app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints) <commit_msg>Remove ancient TODO that was resolved a long time ago.<commit_after>
import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints)
import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): # TODO: make jsbox apps define these explicitly and # update the outbound resource to check and # complain if a jsbox app sends on an endpoint # it hasn't defined. app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints) Remove ancient TODO that was resolved a long time ago.import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints)
<commit_before>import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): # TODO: make jsbox apps define these explicitly and # update the outbound resource to check and # complain if a jsbox app sends on an endpoint # it hasn't defined. app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints) <commit_msg>Remove ancient TODO that was resolved a long time ago.<commit_after>import json from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class ViewLogsAction(ConversationAction): action_name = 'view_logs' action_display_name = 'View Sandbox Logs' redirect_to = 'jsbox_logs' class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'jsbox' conversation_display_name = 'Javascript App' actions = (ViewLogsAction,) def configured_endpoints(self, config): app_config = config.get("jsbox_app_config", {}) raw_js_config = app_config.get("config", {}).get("value", {}) try: js_config = json.loads(raw_js_config) except Exception: return [] endpoints = set() # vumi-jssandbox-toolkit v2 endpoints try: endpoints.update(js_config["endpoints"].keys()) except Exception: pass # vumi-jssandbox-toolkit v1 endpoints try: pool, tag = js_config["sms_tag"] endpoints.add("%s:%s" % (pool, tag)) except Exception: pass return sorted(endpoints)
1a211c264de52fbd4719aaa130129f73388a5dd4
fore/hotswap.py
fore/hotswap.py
import os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.mod = mod self.gen = mod.generate(*args, **kwargs) self.loaded = self.current_modtime self.args = args self.kwargs = kwargs threading.Thread.__init__(self) self.daemon = True @property def current_modtime(self): return os.path.getmtime(self.mod.__file__.replace("pyc", "py")) def run(self): while True: if self.current_modtime != self.loaded: log.info("Hot-swapping module: %s", self.mod.__name__) # self.mod = reload(self.mod) self.loaded = self.current_modtime self.gen = self.mod.generate(*self.args, **self.kwargs) self.handle(self.gen.next()) def handle(self, elem): self.out(elem)
import os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.gen = mod.generate(*args, **kwargs) threading.Thread.__init__(self) self.daemon = True def run(self): while True: self.handle(self.gen.next()) def handle(self, elem): self.out(elem)
Remove all references to actually swapping
Hotswap: Remove all references to actually swapping
Python
artistic-2.0
Rosuav/appension,Rosuav/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension
import os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.mod = mod self.gen = mod.generate(*args, **kwargs) self.loaded = self.current_modtime self.args = args self.kwargs = kwargs threading.Thread.__init__(self) self.daemon = True @property def current_modtime(self): return os.path.getmtime(self.mod.__file__.replace("pyc", "py")) def run(self): while True: if self.current_modtime != self.loaded: log.info("Hot-swapping module: %s", self.mod.__name__) # self.mod = reload(self.mod) self.loaded = self.current_modtime self.gen = self.mod.generate(*self.args, **self.kwargs) self.handle(self.gen.next()) def handle(self, elem): self.out(elem) Hotswap: Remove all references to actually swapping
import os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.gen = mod.generate(*args, **kwargs) threading.Thread.__init__(self) self.daemon = True def run(self): while True: self.handle(self.gen.next()) def handle(self, elem): self.out(elem)
<commit_before>import os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.mod = mod self.gen = mod.generate(*args, **kwargs) self.loaded = self.current_modtime self.args = args self.kwargs = kwargs threading.Thread.__init__(self) self.daemon = True @property def current_modtime(self): return os.path.getmtime(self.mod.__file__.replace("pyc", "py")) def run(self): while True: if self.current_modtime != self.loaded: log.info("Hot-swapping module: %s", self.mod.__name__) # self.mod = reload(self.mod) self.loaded = self.current_modtime self.gen = self.mod.generate(*self.args, **self.kwargs) self.handle(self.gen.next()) def handle(self, elem): self.out(elem) <commit_msg>Hotswap: Remove all references to actually swapping<commit_after>
import os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.gen = mod.generate(*args, **kwargs) threading.Thread.__init__(self) self.daemon = True def run(self): while True: self.handle(self.gen.next()) def handle(self, elem): self.out(elem)
import os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.mod = mod self.gen = mod.generate(*args, **kwargs) self.loaded = self.current_modtime self.args = args self.kwargs = kwargs threading.Thread.__init__(self) self.daemon = True @property def current_modtime(self): return os.path.getmtime(self.mod.__file__.replace("pyc", "py")) def run(self): while True: if self.current_modtime != self.loaded: log.info("Hot-swapping module: %s", self.mod.__name__) # self.mod = reload(self.mod) self.loaded = self.current_modtime self.gen = self.mod.generate(*self.args, **self.kwargs) self.handle(self.gen.next()) def handle(self, elem): self.out(elem) Hotswap: Remove all references to actually swappingimport os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.gen = mod.generate(*args, **kwargs) threading.Thread.__init__(self) self.daemon = True def run(self): while True: self.handle(self.gen.next()) def handle(self, elem): self.out(elem)
<commit_before>import os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.mod = mod self.gen = mod.generate(*args, **kwargs) self.loaded = self.current_modtime self.args = args self.kwargs = kwargs threading.Thread.__init__(self) self.daemon = True @property def current_modtime(self): return os.path.getmtime(self.mod.__file__.replace("pyc", "py")) def run(self): while True: if self.current_modtime != self.loaded: log.info("Hot-swapping module: %s", self.mod.__name__) # self.mod = reload(self.mod) self.loaded = self.current_modtime self.gen = self.mod.generate(*self.args, **self.kwargs) self.handle(self.gen.next()) def handle(self, elem): self.out(elem) <commit_msg>Hotswap: Remove all references to actually swapping<commit_after>import os import logging import threading log = logging.getLogger(__name__) class Hotswap(threading.Thread): def __init__(self, out, mod, *args, **kwargs): self.out = out self.gen = mod.generate(*args, **kwargs) threading.Thread.__init__(self) self.daemon = True def run(self): while True: self.handle(self.gen.next()) def handle(self, elem): self.out(elem)
0d5072aea49ed5c34bc3c140a5019e59506135a4
menus/database_setup.py
menus/database_setup.py
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) description = Column(String(250)) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine)
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine)
Remove description from Restaurant class
bug: Remove description from Restaurant class
Python
mit
gsbullmer/restaurant-menu-directory,gsbullmer/restaurant-menu-directory
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) description = Column(String(250)) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine) bug: Remove description from Restaurant class
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine)
<commit_before>import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) description = Column(String(250)) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine) <commit_msg>bug: Remove description from Restaurant class<commit_after>
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine)
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) description = Column(String(250)) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine) bug: Remove description from Restaurant classimport sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine)
<commit_before>import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) description = Column(String(250)) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine) <commit_msg>bug: Remove description from Restaurant class<commit_after>import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80), nullable = False) id = Column(Integer, primary_key = True) @property def serialize(self): return { 'name': self.name, 'id': self.id, } class MenuItem(Base): __tablename__ = 'menu_item' name = Column(String(80), nullable = False) id = Column(Integer,primary_key = True) course = Column(String(250)) description = Column(String(250)) price = Column(String(8)) restaurant_id = Column(Integer, ForeignKey('restaurant.id')) restaurant = relationship(Restaurant) @property def serialize(self): return { 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, 'course': self.course, } engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.create_all(engine)
756a405bb4f84e819f0a10387355c48acb13a6bb
cogbot/cog_bot_state.py
cogbot/cog_bot_state.py
import json import logging log = logging.getLogger(__name__) # TODO persist state to file class CogBotState: def __init__(self, state_file: str): with open(state_file) as fp: try: raw_state = json.load(fp) except FileNotFoundError: log.warning(f'Bot state file not found: {state_file}') raw_state = {} # Optional self.command_prefix = raw_state.pop('command_prefix', '>') self.description = raw_state.pop('description', '') self.managers = raw_state.pop('managers', []) self.restart_delay = raw_state.pop('restart_delay', 10) self.hide_help = raw_state.pop('hide_help', False) self.extensions = raw_state.pop('extensions', []) self.extension_state = raw_state.pop('extension_state', {}) # Derived self.help_attrs = dict(name='_help', hidden=True) if self.hide_help else {} def get_extension_state(self, ext) -> dict: return self.extension_state.get(ext, {})
import json import logging log = logging.getLogger(__name__) # TODO persist state to file class CogBotState: def __init__(self, state_file: str): with open(state_file) as fp: try: raw_state = json.load(fp) except FileNotFoundError: log.warning(f'Bot state file not found: {state_file}') raw_state = {} # Optional self.command_prefix = raw_state.pop('command_prefix', '>') self.description = raw_state.pop('description', '') self.managers = raw_state.pop('managers', []) self.restart_delay = raw_state.pop('restart_delay', 10) self.hide_help = raw_state.pop('hide_help', False) self.extensions = raw_state.pop('extensions', []) self.extension_state = raw_state.pop('extension_state', {}) # Derived self.help_attrs = dict(name='_help', hidden=True) if self.hide_help else {} def get_extension_state(self, ext) -> dict: return self.extension_state.get(ext, {}).copy()
Return a copy of extension state
Return a copy of extension state
Python
mit
0-0-1/cogbot,Arcensoth/cogbot
import json import logging log = logging.getLogger(__name__) # TODO persist state to file class CogBotState: def __init__(self, state_file: str): with open(state_file) as fp: try: raw_state = json.load(fp) except FileNotFoundError: log.warning(f'Bot state file not found: {state_file}') raw_state = {} # Optional self.command_prefix = raw_state.pop('command_prefix', '>') self.description = raw_state.pop('description', '') self.managers = raw_state.pop('managers', []) self.restart_delay = raw_state.pop('restart_delay', 10) self.hide_help = raw_state.pop('hide_help', False) self.extensions = raw_state.pop('extensions', []) self.extension_state = raw_state.pop('extension_state', {}) # Derived self.help_attrs = dict(name='_help', hidden=True) if self.hide_help else {} def get_extension_state(self, ext) -> dict: return self.extension_state.get(ext, {}) Return a copy of extension state
import json import logging log = logging.getLogger(__name__) # TODO persist state to file class CogBotState: def __init__(self, state_file: str): with open(state_file) as fp: try: raw_state = json.load(fp) except FileNotFoundError: log.warning(f'Bot state file not found: {state_file}') raw_state = {} # Optional self.command_prefix = raw_state.pop('command_prefix', '>') self.description = raw_state.pop('description', '') self.managers = raw_state.pop('managers', []) self.restart_delay = raw_state.pop('restart_delay', 10) self.hide_help = raw_state.pop('hide_help', False) self.extensions = raw_state.pop('extensions', []) self.extension_state = raw_state.pop('extension_state', {}) # Derived self.help_attrs = dict(name='_help', hidden=True) if self.hide_help else {} def get_extension_state(self, ext) -> dict: return self.extension_state.get(ext, {}).copy()
<commit_before>import json import logging log = logging.getLogger(__name__) # TODO persist state to file class CogBotState: def __init__(self, state_file: str): with open(state_file) as fp: try: raw_state = json.load(fp) except FileNotFoundError: log.warning(f'Bot state file not found: {state_file}') raw_state = {} # Optional self.command_prefix = raw_state.pop('command_prefix', '>') self.description = raw_state.pop('description', '') self.managers = raw_state.pop('managers', []) self.restart_delay = raw_state.pop('restart_delay', 10) self.hide_help = raw_state.pop('hide_help', False) self.extensions = raw_state.pop('extensions', []) self.extension_state = raw_state.pop('extension_state', {}) # Derived self.help_attrs = dict(name='_help', hidden=True) if self.hide_help else {} def get_extension_state(self, ext) -> dict: return self.extension_state.get(ext, {}) <commit_msg>Return a copy of extension state<commit_after>
import json import logging log = logging.getLogger(__name__) # TODO persist state to file class CogBotState: def __init__(self, state_file: str): with open(state_file) as fp: try: raw_state = json.load(fp) except FileNotFoundError: log.warning(f'Bot state file not found: {state_file}') raw_state = {} # Optional self.command_prefix = raw_state.pop('command_prefix', '>') self.description = raw_state.pop('description', '') self.managers = raw_state.pop('managers', []) self.restart_delay = raw_state.pop('restart_delay', 10) self.hide_help = raw_state.pop('hide_help', False) self.extensions = raw_state.pop('extensions', []) self.extension_state = raw_state.pop('extension_state', {}) # Derived self.help_attrs = dict(name='_help', hidden=True) if self.hide_help else {} def get_extension_state(self, ext) -> dict: return self.extension_state.get(ext, {}).copy()
import json import logging log = logging.getLogger(__name__) # TODO persist state to file class CogBotState: def __init__(self, state_file: str): with open(state_file) as fp: try: raw_state = json.load(fp) except FileNotFoundError: log.warning(f'Bot state file not found: {state_file}') raw_state = {} # Optional self.command_prefix = raw_state.pop('command_prefix', '>') self.description = raw_state.pop('description', '') self.managers = raw_state.pop('managers', []) self.restart_delay = raw_state.pop('restart_delay', 10) self.hide_help = raw_state.pop('hide_help', False) self.extensions = raw_state.pop('extensions', []) self.extension_state = raw_state.pop('extension_state', {}) # Derived self.help_attrs = dict(name='_help', hidden=True) if self.hide_help else {} def get_extension_state(self, ext) -> dict: return self.extension_state.get(ext, {}) Return a copy of extension stateimport json import logging log = logging.getLogger(__name__) # TODO persist state to file class CogBotState: def __init__(self, state_file: str): with open(state_file) as fp: try: raw_state = json.load(fp) except FileNotFoundError: log.warning(f'Bot state file not found: {state_file}') raw_state = {} # Optional self.command_prefix = raw_state.pop('command_prefix', '>') self.description = raw_state.pop('description', '') self.managers = raw_state.pop('managers', []) self.restart_delay = raw_state.pop('restart_delay', 10) self.hide_help = raw_state.pop('hide_help', False) self.extensions = raw_state.pop('extensions', []) self.extension_state = raw_state.pop('extension_state', {}) # Derived self.help_attrs = dict(name='_help', hidden=True) if self.hide_help else {} def get_extension_state(self, ext) -> dict: return self.extension_state.get(ext, {}).copy()
<commit_before>import json import logging log = logging.getLogger(__name__) # TODO persist state to file class CogBotState: def __init__(self, state_file: str): with open(state_file) as fp: try: raw_state = json.load(fp) except FileNotFoundError: log.warning(f'Bot state file not found: {state_file}') raw_state = {} # Optional self.command_prefix = raw_state.pop('command_prefix', '>') self.description = raw_state.pop('description', '') self.managers = raw_state.pop('managers', []) self.restart_delay = raw_state.pop('restart_delay', 10) self.hide_help = raw_state.pop('hide_help', False) self.extensions = raw_state.pop('extensions', []) self.extension_state = raw_state.pop('extension_state', {}) # Derived self.help_attrs = dict(name='_help', hidden=True) if self.hide_help else {} def get_extension_state(self, ext) -> dict: return self.extension_state.get(ext, {}) <commit_msg>Return a copy of extension state<commit_after>import json import logging log = logging.getLogger(__name__) # TODO persist state to file class CogBotState: def __init__(self, state_file: str): with open(state_file) as fp: try: raw_state = json.load(fp) except FileNotFoundError: log.warning(f'Bot state file not found: {state_file}') raw_state = {} # Optional self.command_prefix = raw_state.pop('command_prefix', '>') self.description = raw_state.pop('description', '') self.managers = raw_state.pop('managers', []) self.restart_delay = raw_state.pop('restart_delay', 10) self.hide_help = raw_state.pop('hide_help', False) self.extensions = raw_state.pop('extensions', []) self.extension_state = raw_state.pop('extension_state', {}) # Derived self.help_attrs = dict(name='_help', hidden=True) if self.hide_help else {} def get_extension_state(self, ext) -> dict: return self.extension_state.get(ext, {}).copy()
d1b7753fd29cb5c1f68b5ee121a511e43c99b5de
pmix/ppp/odkcalculate.py
pmix/ppp/odkcalculate.py
class OdkCalculate: def __init__(self, row): self.row = row def to_html(self): return "" def to_text(self): return "" def __repr__(self): return '<OdkCalculate {}>'.format(self.row['name'])
class OdkCalculate: def __init__(self, row): self.row = row def to_html(self, *args, **kwargs): return "" def to_text(self, *args, **kwargs): return "" def __repr__(self): return '<OdkCalculate {}>'.format(self.row['name'])
Update signature of to_text and to_html
Update signature of to_text and to_html
Python
mit
jkpr/pmix
class OdkCalculate: def __init__(self, row): self.row = row def to_html(self): return "" def to_text(self): return "" def __repr__(self): return '<OdkCalculate {}>'.format(self.row['name']) Update signature of to_text and to_html
class OdkCalculate: def __init__(self, row): self.row = row def to_html(self, *args, **kwargs): return "" def to_text(self, *args, **kwargs): return "" def __repr__(self): return '<OdkCalculate {}>'.format(self.row['name'])
<commit_before>class OdkCalculate: def __init__(self, row): self.row = row def to_html(self): return "" def to_text(self): return "" def __repr__(self): return '<OdkCalculate {}>'.format(self.row['name']) <commit_msg>Update signature of to_text and to_html<commit_after>
class OdkCalculate: def __init__(self, row): self.row = row def to_html(self, *args, **kwargs): return "" def to_text(self, *args, **kwargs): return "" def __repr__(self): return '<OdkCalculate {}>'.format(self.row['name'])
class OdkCalculate: def __init__(self, row): self.row = row def to_html(self): return "" def to_text(self): return "" def __repr__(self): return '<OdkCalculate {}>'.format(self.row['name']) Update signature of to_text and to_htmlclass OdkCalculate: def __init__(self, row): self.row = row def to_html(self, *args, **kwargs): return "" def to_text(self, *args, **kwargs): return "" def __repr__(self): return '<OdkCalculate {}>'.format(self.row['name'])
<commit_before>class OdkCalculate: def __init__(self, row): self.row = row def to_html(self): return "" def to_text(self): return "" def __repr__(self): return '<OdkCalculate {}>'.format(self.row['name']) <commit_msg>Update signature of to_text and to_html<commit_after>class OdkCalculate: def __init__(self, row): self.row = row def to_html(self, *args, **kwargs): return "" def to_text(self, *args, **kwargs): return "" def __repr__(self): return '<OdkCalculate {}>'.format(self.row['name'])
d7e2f05d60aaba3d13337fd53add9fd50aafd6ee
tests/test_python_solutions.py
tests/test_python_solutions.py
import glob import json import os import time import pytest from helpers import solutions_dir # NOTE: If we make solution files a fixture instead of a normal attr/function, # then we can't use it in pytest's parametrize solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py")) @pytest.mark.python def test_solutions_exist(): assert solution_files # TODO ids. id function to turn file name into cleaner label @pytest.mark.python @pytest.mark.parametrize("solution_file", solution_files) def test_submit_file(solution_file, submit_solution): result = submit_solution(solution_file) assert result.get("success") is True, "Failed. Engine output:\n{:}".format( json.dumps(result, indent=4) )
import glob import json import os import time import pytest from helpers import solutions_dir # NOTE: If we make solution_files a fixture instead of a normal attr/function, # then we can't use it in pytest's parametrize solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py")) @pytest.mark.python def test_solutions_exist(): assert solution_files def id_func(param): problem_name, ext = os.path.splitext(os.path.basename(param)) return problem_name @pytest.mark.python @pytest.mark.parametrize("solution_file", solution_files, ids=id_func) def test_submit_file(solution_file, submit_solution): result = submit_solution(solution_file) assert result.get("success") is True, "Failed. Engine output:\n{:}".format( json.dumps(result, indent=4) )
Add ids to parametrized tests
Add ids to parametrized tests
Python
mit
project-lovelace/lovelace-engine,project-lovelace/lovelace-engine,project-lovelace/lovelace-engine
import glob import json import os import time import pytest from helpers import solutions_dir # NOTE: If we make solution files a fixture instead of a normal attr/function, # then we can't use it in pytest's parametrize solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py")) @pytest.mark.python def test_solutions_exist(): assert solution_files # TODO ids. id function to turn file name into cleaner label @pytest.mark.python @pytest.mark.parametrize("solution_file", solution_files) def test_submit_file(solution_file, submit_solution): result = submit_solution(solution_file) assert result.get("success") is True, "Failed. Engine output:\n{:}".format( json.dumps(result, indent=4) ) Add ids to parametrized tests
import glob import json import os import time import pytest from helpers import solutions_dir # NOTE: If we make solution_files a fixture instead of a normal attr/function, # then we can't use it in pytest's parametrize solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py")) @pytest.mark.python def test_solutions_exist(): assert solution_files def id_func(param): problem_name, ext = os.path.splitext(os.path.basename(param)) return problem_name @pytest.mark.python @pytest.mark.parametrize("solution_file", solution_files, ids=id_func) def test_submit_file(solution_file, submit_solution): result = submit_solution(solution_file) assert result.get("success") is True, "Failed. Engine output:\n{:}".format( json.dumps(result, indent=4) )
<commit_before>import glob import json import os import time import pytest from helpers import solutions_dir # NOTE: If we make solution files a fixture instead of a normal attr/function, # then we can't use it in pytest's parametrize solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py")) @pytest.mark.python def test_solutions_exist(): assert solution_files # TODO ids. id function to turn file name into cleaner label @pytest.mark.python @pytest.mark.parametrize("solution_file", solution_files) def test_submit_file(solution_file, submit_solution): result = submit_solution(solution_file) assert result.get("success") is True, "Failed. Engine output:\n{:}".format( json.dumps(result, indent=4) ) <commit_msg>Add ids to parametrized tests<commit_after>
import glob import json import os import time import pytest from helpers import solutions_dir # NOTE: If we make solution_files a fixture instead of a normal attr/function, # then we can't use it in pytest's parametrize solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py")) @pytest.mark.python def test_solutions_exist(): assert solution_files def id_func(param): problem_name, ext = os.path.splitext(os.path.basename(param)) return problem_name @pytest.mark.python @pytest.mark.parametrize("solution_file", solution_files, ids=id_func) def test_submit_file(solution_file, submit_solution): result = submit_solution(solution_file) assert result.get("success") is True, "Failed. Engine output:\n{:}".format( json.dumps(result, indent=4) )
import glob import json import os import time import pytest from helpers import solutions_dir # NOTE: If we make solution files a fixture instead of a normal attr/function, # then we can't use it in pytest's parametrize solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py")) @pytest.mark.python def test_solutions_exist(): assert solution_files # TODO ids. id function to turn file name into cleaner label @pytest.mark.python @pytest.mark.parametrize("solution_file", solution_files) def test_submit_file(solution_file, submit_solution): result = submit_solution(solution_file) assert result.get("success") is True, "Failed. Engine output:\n{:}".format( json.dumps(result, indent=4) ) Add ids to parametrized testsimport glob import json import os import time import pytest from helpers import solutions_dir # NOTE: If we make solution_files a fixture instead of a normal attr/function, # then we can't use it in pytest's parametrize solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py")) @pytest.mark.python def test_solutions_exist(): assert solution_files def id_func(param): problem_name, ext = os.path.splitext(os.path.basename(param)) return problem_name @pytest.mark.python @pytest.mark.parametrize("solution_file", solution_files, ids=id_func) def test_submit_file(solution_file, submit_solution): result = submit_solution(solution_file) assert result.get("success") is True, "Failed. Engine output:\n{:}".format( json.dumps(result, indent=4) )
<commit_before>import glob import json import os import time import pytest from helpers import solutions_dir # NOTE: If we make solution files a fixture instead of a normal attr/function, # then we can't use it in pytest's parametrize solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py")) @pytest.mark.python def test_solutions_exist(): assert solution_files # TODO ids. id function to turn file name into cleaner label @pytest.mark.python @pytest.mark.parametrize("solution_file", solution_files) def test_submit_file(solution_file, submit_solution): result = submit_solution(solution_file) assert result.get("success") is True, "Failed. Engine output:\n{:}".format( json.dumps(result, indent=4) ) <commit_msg>Add ids to parametrized tests<commit_after>import glob import json import os import time import pytest from helpers import solutions_dir # NOTE: If we make solution_files a fixture instead of a normal attr/function, # then we can't use it in pytest's parametrize solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py")) @pytest.mark.python def test_solutions_exist(): assert solution_files def id_func(param): problem_name, ext = os.path.splitext(os.path.basename(param)) return problem_name @pytest.mark.python @pytest.mark.parametrize("solution_file", solution_files, ids=id_func) def test_submit_file(solution_file, submit_solution): result = submit_solution(solution_file) assert result.get("success") is True, "Failed. Engine output:\n{:}".format( json.dumps(result, indent=4) )
d4e87e4e5401fa105b5ed974271e160f364a69f8
registration/__init__.py
registration/__init__.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
Add reminder to myself to to importlib fallback.
Add reminder to myself to to importlib fallback.
Python
bsd-3-clause
dinie/django-registration,Avenza/django-registration,FundedByMe/django-registration,dinie/django-registration,FundedByMe/django-registration
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class() Add reminder to myself to to importlib fallback.
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
<commit_before>from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class() <commit_msg>Add reminder to myself to to importlib fallback.<commit_after>
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class() Add reminder to myself to to importlib fallback.from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
<commit_before>from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class() <commit_msg>Add reminder to myself to to importlib fallback.<commit_after>from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
deee916f45ed569c232cef9bf80d5113e9cf5e8e
mahjong/meld.py
mahjong/meld.py
# -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]]
# -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles or [] self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]]
Initialize empty tiles array for Meld object
Initialize empty tiles array for Meld object
Python
mit
MahjongRepository/mahjong
# -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]] Initialize empty tiles array for Meld object
# -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles or [] self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]]
<commit_before># -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]] <commit_msg>Initialize empty tiles array for Meld object<commit_after>
# -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles or [] self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]]
# -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]] Initialize empty tiles array for Meld object# -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles or [] self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]]
<commit_before># -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]] <commit_msg>Initialize empty tiles array for Meld object<commit_after># -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles or [] self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]]
53b519c4912d7b3cc32f000eea73bc4d9693967e
tests/test_basic.py
tests/test_basic.py
import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long assert(iso.pvd.space_size == 24) assert(iso.pvd.log_block_size == 2048) assert(iso.pvd.path_tbl_size == 10)
import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage. outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) # Now open up the ISO with pyiso and check some things out. iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long. assert(iso.pvd.space_size == 24) # genisoimage always produces ISOs with 2048-byte sized logical blocks. assert(iso.pvd.log_block_size == 2048) # With no files, the path table should be exactly 10 bytes (just for the # root directory entry). assert(iso.pvd.path_tbl_size == 10) # The little endian version of the path table should start at extent 19. assert(iso.pvd.path_table_location_le == 19) # The big endian version of the path table should start at extent 21. assert(iso.pvd.path_table_location_be == 21)
Add in more unit tests.
Add in more unit tests. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@gmail.com>
Python
lgpl-2.1
clalancette/pycdlib,clalancette/pyiso
import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long assert(iso.pvd.space_size == 24) assert(iso.pvd.log_block_size == 2048) assert(iso.pvd.path_tbl_size == 10) Add in more unit tests. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@gmail.com>
import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage. outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) # Now open up the ISO with pyiso and check some things out. iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long. assert(iso.pvd.space_size == 24) # genisoimage always produces ISOs with 2048-byte sized logical blocks. assert(iso.pvd.log_block_size == 2048) # With no files, the path table should be exactly 10 bytes (just for the # root directory entry). assert(iso.pvd.path_tbl_size == 10) # The little endian version of the path table should start at extent 19. assert(iso.pvd.path_table_location_le == 19) # The big endian version of the path table should start at extent 21. assert(iso.pvd.path_table_location_be == 21)
<commit_before>import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long assert(iso.pvd.space_size == 24) assert(iso.pvd.log_block_size == 2048) assert(iso.pvd.path_tbl_size == 10) <commit_msg>Add in more unit tests. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@gmail.com><commit_after>
import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage. outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) # Now open up the ISO with pyiso and check some things out. iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long. assert(iso.pvd.space_size == 24) # genisoimage always produces ISOs with 2048-byte sized logical blocks. assert(iso.pvd.log_block_size == 2048) # With no files, the path table should be exactly 10 bytes (just for the # root directory entry). assert(iso.pvd.path_tbl_size == 10) # The little endian version of the path table should start at extent 19. assert(iso.pvd.path_table_location_le == 19) # The big endian version of the path table should start at extent 21. assert(iso.pvd.path_table_location_be == 21)
import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long assert(iso.pvd.space_size == 24) assert(iso.pvd.log_block_size == 2048) assert(iso.pvd.path_tbl_size == 10) Add in more unit tests. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@gmail.com>import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage. outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) # Now open up the ISO with pyiso and check some things out. iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long. assert(iso.pvd.space_size == 24) # genisoimage always produces ISOs with 2048-byte sized logical blocks. assert(iso.pvd.log_block_size == 2048) # With no files, the path table should be exactly 10 bytes (just for the # root directory entry). assert(iso.pvd.path_tbl_size == 10) # The little endian version of the path table should start at extent 19. assert(iso.pvd.path_table_location_le == 19) # The big endian version of the path table should start at extent 21. assert(iso.pvd.path_table_location_be == 21)
<commit_before>import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long assert(iso.pvd.space_size == 24) assert(iso.pvd.log_block_size == 2048) assert(iso.pvd.path_tbl_size == 10) <commit_msg>Add in more unit tests. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@gmail.com><commit_after>import pytest import subprocess import os import sys prefix = '.' for i in range(0,3): if os.path.exists(os.path.join(prefix, 'pyiso.py')): sys.path.insert(0, prefix) break else: prefix = '../' + prefix import pyiso def test_nofiles(tmpdir): # First set things up, and generate the ISO with genisoimage. outfile = tmpdir.join("no-file-test.iso") indir = tmpdir.mkdir("nofile") subprocess.call(["genisoimage", "-v", "-v", "-iso-level", "1", "-no-pad", "-o", str(outfile), str(indir)]) # Now open up the ISO with pyiso and check some things out. iso = pyiso.PyIso() iso.open(open(str(outfile), 'rb')) # With no files, the ISO should be exactly 24 extents long. assert(iso.pvd.space_size == 24) # genisoimage always produces ISOs with 2048-byte sized logical blocks. assert(iso.pvd.log_block_size == 2048) # With no files, the path table should be exactly 10 bytes (just for the # root directory entry). assert(iso.pvd.path_tbl_size == 10) # The little endian version of the path table should start at extent 19. assert(iso.pvd.path_table_location_le == 19) # The big endian version of the path table should start at extent 21. assert(iso.pvd.path_table_location_be == 21)
f71dd9055ba04d8aa0024d66d0782107a4b1ca08
lmod_proxy/tests/test_web.py
lmod_proxy/tests/test_web.py
# -*- coding: utf-8 -*- """ Test the root Web application """ import imp from lmod_proxy.tests.common import CommonTest class TestWeb(CommonTest): """Verify the root Web app. Currently it just redirects to edx_grades""" def setUp(self): """Setup commonly needed objects like the flask test client""" super(TestWeb, self).setUp() import lmod_proxy.web imp.reload(lmod_proxy.web) self.client = lmod_proxy.web.app.test_client() def test_redirect(self): """Do a get and verify we are redirected""" response = self.client.get('/', headers=self.get_basic_auth_headers()) self.assertEqual(302, response.status_code) self.assertEqual( 'http://localhost/edx_grades', response.headers['location'] ) def test_pages_protected(self): """Verify pages that should be protected actually are.""" for page in ['/edx_grades', '/']: response = self.client.get(page) self.assertEqual(401, response.status_code)
# -*- coding: utf-8 -*- """ Test the root Web application """ import imp import mock from passlib.apache import HtpasswdFile from lmod_proxy.tests.common import CommonTest class TestWeb(CommonTest): """Verify the root Web app. Currently it just redirects to edx_grades""" def setUp(self): """Setup commonly needed objects like the flask test client""" super(TestWeb, self).setUp() import lmod_proxy.web imp.reload(lmod_proxy.web) self.client = lmod_proxy.web.app.test_client() def test_redirect(self): """Do a get and verify we are redirected""" response = self.client.get('/', headers=self.get_basic_auth_headers()) self.assertEqual(302, response.status_code) self.assertEqual( 'http://localhost/edx_grades', response.headers['location'] ) def test_pages_protected(self): """Verify pages that should be protected actually are.""" for page in ['/edx_grades', '/']: response = self.client.get(page) self.assertEqual(401, response.status_code) @mock.patch.dict( 'os.environ', {'LMODP_HTPASSWD_PATH': '^^^/^^^'}, clear=True ) def test_htpasswd_file(self): """Verify we still create an app, even without an htpasswd file""" import lmod_proxy.config imp.reload(lmod_proxy.config) import lmod_proxy.web with mock.patch('lmod_proxy.web.log') as patch_log: local_app = lmod_proxy.web.app_factory() self.assertTrue(patch_log.critical.called) self.assertEqual( local_app.config['users'].users(), HtpasswdFile().users() )
Verify we handle null HTPasswd files
Verify we handle null HTPasswd files
Python
agpl-3.0
mitodl/lmod_proxy,mitodl/lmod_proxy,mitodl/lmod_proxy
# -*- coding: utf-8 -*- """ Test the root Web application """ import imp from lmod_proxy.tests.common import CommonTest class TestWeb(CommonTest): """Verify the root Web app. Currently it just redirects to edx_grades""" def setUp(self): """Setup commonly needed objects like the flask test client""" super(TestWeb, self).setUp() import lmod_proxy.web imp.reload(lmod_proxy.web) self.client = lmod_proxy.web.app.test_client() def test_redirect(self): """Do a get and verify we are redirected""" response = self.client.get('/', headers=self.get_basic_auth_headers()) self.assertEqual(302, response.status_code) self.assertEqual( 'http://localhost/edx_grades', response.headers['location'] ) def test_pages_protected(self): """Verify pages that should be protected actually are.""" for page in ['/edx_grades', '/']: response = self.client.get(page) self.assertEqual(401, response.status_code) Verify we handle null HTPasswd files
# -*- coding: utf-8 -*- """ Test the root Web application """ import imp import mock from passlib.apache import HtpasswdFile from lmod_proxy.tests.common import CommonTest class TestWeb(CommonTest): """Verify the root Web app. Currently it just redirects to edx_grades""" def setUp(self): """Setup commonly needed objects like the flask test client""" super(TestWeb, self).setUp() import lmod_proxy.web imp.reload(lmod_proxy.web) self.client = lmod_proxy.web.app.test_client() def test_redirect(self): """Do a get and verify we are redirected""" response = self.client.get('/', headers=self.get_basic_auth_headers()) self.assertEqual(302, response.status_code) self.assertEqual( 'http://localhost/edx_grades', response.headers['location'] ) def test_pages_protected(self): """Verify pages that should be protected actually are.""" for page in ['/edx_grades', '/']: response = self.client.get(page) self.assertEqual(401, response.status_code) @mock.patch.dict( 'os.environ', {'LMODP_HTPASSWD_PATH': '^^^/^^^'}, clear=True ) def test_htpasswd_file(self): """Verify we still create an app, even without an htpasswd file""" import lmod_proxy.config imp.reload(lmod_proxy.config) import lmod_proxy.web with mock.patch('lmod_proxy.web.log') as patch_log: local_app = lmod_proxy.web.app_factory() self.assertTrue(patch_log.critical.called) self.assertEqual( local_app.config['users'].users(), HtpasswdFile().users() )
<commit_before># -*- coding: utf-8 -*- """ Test the root Web application """ import imp from lmod_proxy.tests.common import CommonTest class TestWeb(CommonTest): """Verify the root Web app. Currently it just redirects to edx_grades""" def setUp(self): """Setup commonly needed objects like the flask test client""" super(TestWeb, self).setUp() import lmod_proxy.web imp.reload(lmod_proxy.web) self.client = lmod_proxy.web.app.test_client() def test_redirect(self): """Do a get and verify we are redirected""" response = self.client.get('/', headers=self.get_basic_auth_headers()) self.assertEqual(302, response.status_code) self.assertEqual( 'http://localhost/edx_grades', response.headers['location'] ) def test_pages_protected(self): """Verify pages that should be protected actually are.""" for page in ['/edx_grades', '/']: response = self.client.get(page) self.assertEqual(401, response.status_code) <commit_msg>Verify we handle null HTPasswd files<commit_after>
# -*- coding: utf-8 -*- """ Test the root Web application """ import imp import mock from passlib.apache import HtpasswdFile from lmod_proxy.tests.common import CommonTest class TestWeb(CommonTest): """Verify the root Web app. Currently it just redirects to edx_grades""" def setUp(self): """Setup commonly needed objects like the flask test client""" super(TestWeb, self).setUp() import lmod_proxy.web imp.reload(lmod_proxy.web) self.client = lmod_proxy.web.app.test_client() def test_redirect(self): """Do a get and verify we are redirected""" response = self.client.get('/', headers=self.get_basic_auth_headers()) self.assertEqual(302, response.status_code) self.assertEqual( 'http://localhost/edx_grades', response.headers['location'] ) def test_pages_protected(self): """Verify pages that should be protected actually are.""" for page in ['/edx_grades', '/']: response = self.client.get(page) self.assertEqual(401, response.status_code) @mock.patch.dict( 'os.environ', {'LMODP_HTPASSWD_PATH': '^^^/^^^'}, clear=True ) def test_htpasswd_file(self): """Verify we still create an app, even without an htpasswd file""" import lmod_proxy.config imp.reload(lmod_proxy.config) import lmod_proxy.web with mock.patch('lmod_proxy.web.log') as patch_log: local_app = lmod_proxy.web.app_factory() self.assertTrue(patch_log.critical.called) self.assertEqual( local_app.config['users'].users(), HtpasswdFile().users() )
# -*- coding: utf-8 -*- """ Test the root Web application """ import imp from lmod_proxy.tests.common import CommonTest class TestWeb(CommonTest): """Verify the root Web app. Currently it just redirects to edx_grades""" def setUp(self): """Setup commonly needed objects like the flask test client""" super(TestWeb, self).setUp() import lmod_proxy.web imp.reload(lmod_proxy.web) self.client = lmod_proxy.web.app.test_client() def test_redirect(self): """Do a get and verify we are redirected""" response = self.client.get('/', headers=self.get_basic_auth_headers()) self.assertEqual(302, response.status_code) self.assertEqual( 'http://localhost/edx_grades', response.headers['location'] ) def test_pages_protected(self): """Verify pages that should be protected actually are.""" for page in ['/edx_grades', '/']: response = self.client.get(page) self.assertEqual(401, response.status_code) Verify we handle null HTPasswd files# -*- coding: utf-8 -*- """ Test the root Web application """ import imp import mock from passlib.apache import HtpasswdFile from lmod_proxy.tests.common import CommonTest class TestWeb(CommonTest): """Verify the root Web app. Currently it just redirects to edx_grades""" def setUp(self): """Setup commonly needed objects like the flask test client""" super(TestWeb, self).setUp() import lmod_proxy.web imp.reload(lmod_proxy.web) self.client = lmod_proxy.web.app.test_client() def test_redirect(self): """Do a get and verify we are redirected""" response = self.client.get('/', headers=self.get_basic_auth_headers()) self.assertEqual(302, response.status_code) self.assertEqual( 'http://localhost/edx_grades', response.headers['location'] ) def test_pages_protected(self): """Verify pages that should be protected actually are.""" for page in ['/edx_grades', '/']: response = self.client.get(page) self.assertEqual(401, response.status_code) @mock.patch.dict( 'os.environ', {'LMODP_HTPASSWD_PATH': '^^^/^^^'}, clear=True ) def test_htpasswd_file(self): """Verify we still create an app, even without an htpasswd file""" import lmod_proxy.config imp.reload(lmod_proxy.config) import lmod_proxy.web with mock.patch('lmod_proxy.web.log') as patch_log: local_app = lmod_proxy.web.app_factory() self.assertTrue(patch_log.critical.called) self.assertEqual( local_app.config['users'].users(), HtpasswdFile().users() )
<commit_before># -*- coding: utf-8 -*- """ Test the root Web application """ import imp from lmod_proxy.tests.common import CommonTest class TestWeb(CommonTest): """Verify the root Web app. Currently it just redirects to edx_grades""" def setUp(self): """Setup commonly needed objects like the flask test client""" super(TestWeb, self).setUp() import lmod_proxy.web imp.reload(lmod_proxy.web) self.client = lmod_proxy.web.app.test_client() def test_redirect(self): """Do a get and verify we are redirected""" response = self.client.get('/', headers=self.get_basic_auth_headers()) self.assertEqual(302, response.status_code) self.assertEqual( 'http://localhost/edx_grades', response.headers['location'] ) def test_pages_protected(self): """Verify pages that should be protected actually are.""" for page in ['/edx_grades', '/']: response = self.client.get(page) self.assertEqual(401, response.status_code) <commit_msg>Verify we handle null HTPasswd files<commit_after># -*- coding: utf-8 -*- """ Test the root Web application """ import imp import mock from passlib.apache import HtpasswdFile from lmod_proxy.tests.common import CommonTest class TestWeb(CommonTest): """Verify the root Web app. Currently it just redirects to edx_grades""" def setUp(self): """Setup commonly needed objects like the flask test client""" super(TestWeb, self).setUp() import lmod_proxy.web imp.reload(lmod_proxy.web) self.client = lmod_proxy.web.app.test_client() def test_redirect(self): """Do a get and verify we are redirected""" response = self.client.get('/', headers=self.get_basic_auth_headers()) self.assertEqual(302, response.status_code) self.assertEqual( 'http://localhost/edx_grades', response.headers['location'] ) def test_pages_protected(self): """Verify pages that should be protected actually are.""" for page in ['/edx_grades', '/']: response = self.client.get(page) self.assertEqual(401, response.status_code) @mock.patch.dict( 'os.environ', {'LMODP_HTPASSWD_PATH': '^^^/^^^'}, clear=True ) def test_htpasswd_file(self): """Verify we still create an app, even without an htpasswd file""" import lmod_proxy.config imp.reload(lmod_proxy.config) import lmod_proxy.web with mock.patch('lmod_proxy.web.log') as patch_log: local_app = lmod_proxy.web.app_factory() self.assertTrue(patch_log.critical.called) self.assertEqual( local_app.config['users'].users(), HtpasswdFile().users() )
557e94f9407c0f2d3d6b8faba70209a3d13f3280
zou/event_stream.py
zou/event_stream.py
import os from flask import Flask from flask_sse import sse app = Flask(__name__) redis_host = os.environ.get("KV_HOST", "localhost") redis_port = os.environ.get("KV_PORT", "6379") redis_url = "redis://%s:%s/2" % (redis_host, redis_port) app.config["REDIS_URL"] = redis_url app.register_blueprint(sse, url_prefix='/events')
import os from flask import Flask from flask_sse import sse app = Flask(__name__) redis_host = os.environ.get("KV_HOST", "localhost") redis_port = os.environ.get("KV_PORT", "6379") redis_url = "redis://%s:%s/2" % (redis_host, redis_port) app.config["REDIS_URL"] = redis_url app.register_blueprint(sse, url_prefix='/events')
Use right env variable to build redis url
Use right env variable to build redis url It is for the events stream daemon.
Python
agpl-3.0
cgwire/zou
import os from flask import Flask from flask_sse import sse app = Flask(__name__) redis_host = os.environ.get("KV_HOST", "localhost") redis_port = os.environ.get("KV_PORT", "6379") redis_url = "redis://%s:%s/2" % (redis_host, redis_port) app.config["REDIS_URL"] = redis_url app.register_blueprint(sse, url_prefix='/events') Use right env variable to build redis url It is for the events stream daemon.
import os from flask import Flask from flask_sse import sse app = Flask(__name__) redis_host = os.environ.get("KV_HOST", "localhost") redis_port = os.environ.get("KV_PORT", "6379") redis_url = "redis://%s:%s/2" % (redis_host, redis_port) app.config["REDIS_URL"] = redis_url app.register_blueprint(sse, url_prefix='/events')
<commit_before>import os from flask import Flask from flask_sse import sse app = Flask(__name__) redis_host = os.environ.get("KV_HOST", "localhost") redis_port = os.environ.get("KV_PORT", "6379") redis_url = "redis://%s:%s/2" % (redis_host, redis_port) app.config["REDIS_URL"] = redis_url app.register_blueprint(sse, url_prefix='/events') <commit_msg>Use right env variable to build redis url It is for the events stream daemon.<commit_after>
import os from flask import Flask from flask_sse import sse app = Flask(__name__) redis_host = os.environ.get("KV_HOST", "localhost") redis_port = os.environ.get("KV_PORT", "6379") redis_url = "redis://%s:%s/2" % (redis_host, redis_port) app.config["REDIS_URL"] = redis_url app.register_blueprint(sse, url_prefix='/events')
import os from flask import Flask from flask_sse import sse app = Flask(__name__) redis_host = os.environ.get("KV_HOST", "localhost") redis_port = os.environ.get("KV_PORT", "6379") redis_url = "redis://%s:%s/2" % (redis_host, redis_port) app.config["REDIS_URL"] = redis_url app.register_blueprint(sse, url_prefix='/events') Use right env variable to build redis url It is for the events stream daemon.import os from flask import Flask from flask_sse import sse app = Flask(__name__) redis_host = os.environ.get("KV_HOST", "localhost") redis_port = os.environ.get("KV_PORT", "6379") redis_url = "redis://%s:%s/2" % (redis_host, redis_port) app.config["REDIS_URL"] = redis_url app.register_blueprint(sse, url_prefix='/events')
<commit_before>import os from flask import Flask from flask_sse import sse app = Flask(__name__) redis_host = os.environ.get("KV_HOST", "localhost") redis_port = os.environ.get("KV_PORT", "6379") redis_url = "redis://%s:%s/2" % (redis_host, redis_port) app.config["REDIS_URL"] = redis_url app.register_blueprint(sse, url_prefix='/events') <commit_msg>Use right env variable to build redis url It is for the events stream daemon.<commit_after>import os from flask import Flask from flask_sse import sse app = Flask(__name__) redis_host = os.environ.get("KV_HOST", "localhost") redis_port = os.environ.get("KV_PORT", "6379") redis_url = "redis://%s:%s/2" % (redis_host, redis_port) app.config["REDIS_URL"] = redis_url app.register_blueprint(sse, url_prefix='/events')
f44630714ce1c20c88919a1ce8d9e4ad49ec9fde
nodeconductor/cloud/perms.py
nodeconductor/cloud/perms.py
from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), )
from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), )
Fix permission path for customer role lookup
Fix permission path for customer role lookup
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), ) Fix permission path for customer role lookup
from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), )
<commit_before>from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), ) <commit_msg>Fix permission path for customer role lookup<commit_after>
from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), )
from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), ) Fix permission path for customer role lookupfrom __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), )
<commit_before>from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), ) <commit_msg>Fix permission path for customer role lookup<commit_after>from __future__ import unicode_literals from django.contrib.auth import get_user_model from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole User = get_user_model() PERMISSION_LOGICS = ( ('cloud.Cloud', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission_group__user', collaborators_filter={ 'customer__roles__role_type': CustomerRole.OWNER, }, any_permission=True, )), )
f743fec77e7090e3e0e7749ec8615fbf5523dbda
__/urls.py
__/urls.py
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^ajax/', include('ajax.urls', namespace='ajax')), url(r'^', include('pages.urls', namespace='pages')), )
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^ajax/', include('ajax.urls', namespace='ajax')), url(r'', include('pages.urls', namespace='pages')), )
Fix URL pattern in new versions of Django
Fix URL pattern in new versions of Django
Python
mit
djangogirlstaipei/djangogirlstaipei,djangogirlstaipei/djangogirlstaipei,djangogirlstaipei/djangogirlstaipei
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^ajax/', include('ajax.urls', namespace='ajax')), url(r'^', include('pages.urls', namespace='pages')), ) Fix URL pattern in new versions of Django
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^ajax/', include('ajax.urls', namespace='ajax')), url(r'', include('pages.urls', namespace='pages')), )
<commit_before>from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^ajax/', include('ajax.urls', namespace='ajax')), url(r'^', include('pages.urls', namespace='pages')), ) <commit_msg>Fix URL pattern in new versions of Django<commit_after>
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^ajax/', include('ajax.urls', namespace='ajax')), url(r'', include('pages.urls', namespace='pages')), )
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^ajax/', include('ajax.urls', namespace='ajax')), url(r'^', include('pages.urls', namespace='pages')), ) Fix URL pattern in new versions of Djangofrom django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^ajax/', include('ajax.urls', namespace='ajax')), url(r'', include('pages.urls', namespace='pages')), )
<commit_before>from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^ajax/', include('ajax.urls', namespace='ajax')), url(r'^', include('pages.urls', namespace='pages')), ) <commit_msg>Fix URL pattern in new versions of Django<commit_after>from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^ajax/', include('ajax.urls', namespace='ajax')), url(r'', include('pages.urls', namespace='pages')), )
c56e490d81e9ad35f1373adf333a452766f56729
storage/elasticsearch_storage.py
storage/elasticsearch_storage.py
from elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.keys()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False
from elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.values()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False
Fix bug in no sha use case
Fix bug in no sha use case
Python
mpl-2.0
awest1339/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,MITRECND/multiscanner,jmlong1027/multiscanner,MITRECND/multiscanner,mitre/multiscanner,awest1339/multiscanner,mitre/multiscanner
from elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.keys()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False Fix bug in no sha use case
from elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.values()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False
<commit_before>from elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.keys()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False <commit_msg>Fix bug in no sha use case<commit_after>
from elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.values()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False
from elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.keys()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False Fix bug in no sha use casefrom elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.values()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False
<commit_before>from elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.keys()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False <commit_msg>Fix bug in no sha use case<commit_after>from elasticsearch import Elasticsearch from storage import Storage class ElasticSearchStorage(Storage): def __init__(self, config_dict): self.db = config_dict['database'] self.host = config_dict['host'] self.port = config_dict['port'] self.username = config_dict['username'] self.password = config_dict['password'] self.index = config_dict['index'] self.doc_type = config_dict['doc_type'] self.es = Elasticsearch( host=self.host, port=self.port ) def store(self, report): try: report_id = report.values()[0]['SHA256'] report.values()[0]['filename'] = report.keys()[0] clean_report = report.values()[0] except: report_id = '' clean_report = report.values()[0] result = self.es.index( index=self.index, doc_type=self.doc_type, id=report_id, body=clean_report ) return result['_id'] def get_report(self, report_id): try: result = self.es.get( index=self.index, doc_type=self.doc_type, id=report_id ) return result['_source'] except: return None def delete(self, report_id): try: self.es.delete( index=self.index, doc_type=self.doc_type, id=report_id ) return True except: return False
aaa8743c8610eb4b5ae7d08167715f3c1181d4d5
app/sessions.py
app/sessions.py
from functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) # testing: automatically make an admin user if not User.query.first(): u = User('admin', 'password') db.session.add(u) db.session.commit() @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index'))
from functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index'))
Remove development auto admin user creation
Remove development auto admin user creation
Python
mit
tjgavlick/whiskey-blog,tjgavlick/whiskey-blog,tjgavlick/whiskey-blog,tjgavlick/whiskey-blog
from functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) # testing: automatically make an admin user if not User.query.first(): u = User('admin', 'password') db.session.add(u) db.session.commit() @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index')) Remove development auto admin user creation
from functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index'))
<commit_before>from functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) # testing: automatically make an admin user if not User.query.first(): u = User('admin', 'password') db.session.add(u) db.session.commit() @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index')) <commit_msg>Remove development auto admin user creation<commit_after>
from functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index'))
from functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) # testing: automatically make an admin user if not User.query.first(): u = User('admin', 'password') db.session.add(u) db.session.commit() @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index')) Remove development auto admin user creationfrom functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index'))
<commit_before>from functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) # testing: automatically make an admin user if not User.query.first(): u = User('admin', 'password') db.session.add(u) db.session.commit() @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index')) <commit_msg>Remove development auto admin user creation<commit_after>from functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index'))
28b067ab7fc7385ac5462eb6c9f9371cef9eb496
ritter/dataprocessors/annotators.py
ritter/dataprocessors/annotators.py
import re class ArtifactAnnotator: def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': item['text'] = strings[i] i = i + 1
import re class ArtifactAnnotator: excluded_types = set(['heading', 'code']) def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types: strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types item['text'] = strings[i] i = i + 1
Improve annotating of code segements
feat: Improve annotating of code segements
Python
mit
ErikGartner/ghostdoc-ritter
import re class ArtifactAnnotator: def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': item['text'] = strings[i] i = i + 1 feat: Improve annotating of code segements
import re class ArtifactAnnotator: excluded_types = set(['heading', 'code']) def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types: strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types item['text'] = strings[i] i = i + 1
<commit_before>import re class ArtifactAnnotator: def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': item['text'] = strings[i] i = i + 1 <commit_msg>feat: Improve annotating of code segements<commit_after>
import re class ArtifactAnnotator: excluded_types = set(['heading', 'code']) def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types: strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types item['text'] = strings[i] i = i + 1
import re class ArtifactAnnotator: def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': item['text'] = strings[i] i = i + 1 feat: Improve annotating of code segementsimport re class ArtifactAnnotator: excluded_types = set(['heading', 'code']) def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types: strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types item['text'] = strings[i] i = i + 1
<commit_before>import re class ArtifactAnnotator: def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': item['text'] = strings[i] i = i + 1 <commit_msg>feat: Improve annotating of code segements<commit_after>import re class ArtifactAnnotator: excluded_types = set(['heading', 'code']) def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types: strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types item['text'] = strings[i] i = i + 1
8806f70fc5d38d5aa8a49fbe096deb778df3c247
schemas.py
schemas.py
from models import Reservation from setup import ma from marshmallow import fields class ReservationSchema(ma.ModelSchema): user = fields.Method('get_user') def get_user(self, reservation): user = self.context if user.admin or reservation.user == user: return reservation.user.id else: return None class Meta: model = Reservation reservation_schema = ReservationSchema() reservations_schema = ReservationSchema(many=True)
from models import Reservation from setup import ma from marshmallow import fields class ReservationSchema(ma.ModelSchema): user = fields.Method('get_user') def get_user(self, reservation, **kwargs): user = self.context['user'] if user.admin or reservation.user == user: return reservation.user.id else: return None class Meta: model = Reservation reservation_schema = ReservationSchema() reservations_schema = ReservationSchema(many=True)
Fix user in reservations responses
Fix user in reservations responses
Python
agpl-3.0
CMU-Senate/tcc-room-reservation,CMU-Senate/tcc-room-reservation,CMU-Senate/tcc-room-reservation
from models import Reservation from setup import ma from marshmallow import fields class ReservationSchema(ma.ModelSchema): user = fields.Method('get_user') def get_user(self, reservation): user = self.context if user.admin or reservation.user == user: return reservation.user.id else: return None class Meta: model = Reservation reservation_schema = ReservationSchema() reservations_schema = ReservationSchema(many=True) Fix user in reservations responses
from models import Reservation from setup import ma from marshmallow import fields class ReservationSchema(ma.ModelSchema): user = fields.Method('get_user') def get_user(self, reservation, **kwargs): user = self.context['user'] if user.admin or reservation.user == user: return reservation.user.id else: return None class Meta: model = Reservation reservation_schema = ReservationSchema() reservations_schema = ReservationSchema(many=True)
<commit_before>from models import Reservation from setup import ma from marshmallow import fields class ReservationSchema(ma.ModelSchema): user = fields.Method('get_user') def get_user(self, reservation): user = self.context if user.admin or reservation.user == user: return reservation.user.id else: return None class Meta: model = Reservation reservation_schema = ReservationSchema() reservations_schema = ReservationSchema(many=True) <commit_msg>Fix user in reservations responses<commit_after>
from models import Reservation from setup import ma from marshmallow import fields class ReservationSchema(ma.ModelSchema): user = fields.Method('get_user') def get_user(self, reservation, **kwargs): user = self.context['user'] if user.admin or reservation.user == user: return reservation.user.id else: return None class Meta: model = Reservation reservation_schema = ReservationSchema() reservations_schema = ReservationSchema(many=True)
from models import Reservation from setup import ma from marshmallow import fields class ReservationSchema(ma.ModelSchema): user = fields.Method('get_user') def get_user(self, reservation): user = self.context if user.admin or reservation.user == user: return reservation.user.id else: return None class Meta: model = Reservation reservation_schema = ReservationSchema() reservations_schema = ReservationSchema(many=True) Fix user in reservations responsesfrom models import Reservation from setup import ma from marshmallow import fields class ReservationSchema(ma.ModelSchema): user = fields.Method('get_user') def get_user(self, reservation, **kwargs): user = self.context['user'] if user.admin or reservation.user == user: return reservation.user.id else: return None class Meta: model = Reservation reservation_schema = ReservationSchema() reservations_schema = ReservationSchema(many=True)
<commit_before>from models import Reservation from setup import ma from marshmallow import fields class ReservationSchema(ma.ModelSchema): user = fields.Method('get_user') def get_user(self, reservation): user = self.context if user.admin or reservation.user == user: return reservation.user.id else: return None class Meta: model = Reservation reservation_schema = ReservationSchema() reservations_schema = ReservationSchema(many=True) <commit_msg>Fix user in reservations responses<commit_after>from models import Reservation from setup import ma from marshmallow import fields class ReservationSchema(ma.ModelSchema): user = fields.Method('get_user') def get_user(self, reservation, **kwargs): user = self.context['user'] if user.admin or reservation.user == user: return reservation.user.id else: return None class Meta: model = Reservation reservation_schema = ReservationSchema() reservations_schema = ReservationSchema(many=True)