commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
7fc58c651ea4d2d9db8b37a9f9768cecc834b225
primestg/__init__.py
primestg/__init__.py
try: __version__ = __import__('pkg_resources') \ .get_distribution(__name__).version except Exception, e: __version__ = 'unknown'
import os try: __version__ = __import__('pkg_resources') \ .get_distribution(__name__).version except Exception, e: __version__ = 'unknown' _ROOT = os.path.abspath(os.path.dirname(__file__)) def get_data(path): filename = isinstance(path, (list, tuple)) and path[0] or path return os.path.join(_ROOT, 'data', filename)
Add function to get relative path in repository
Add function to get relative path in repository
Python
agpl-3.0
gisce/primestg
--- +++ @@ -1,5 +1,14 @@ +import os + try: __version__ = __import__('pkg_resources') \ .get_distribution(__name__).version except Exception, e: __version__ = 'unknown' + +_ROOT = os.path.abspath(os.path.dirname(__file__)) + + +def get_data(path): + filename = isinstance(path, (list, tuple)) and path[0] or path + return os.path.join(_ROOT, 'data', filename)
2d0ad125a63592fc64c52432fc8e697c681f465c
webapp/element43/apps/auth/urls.py
webapp/element43/apps/auth/urls.py
from django.conf.urls import patterns, url urlpatterns = patterns('apps.auth.views', # # Authentication and Registration URLs # # Registration url(r'^register/activate/(?P<key>[a-zA-Z0-9]+)/$', 'activate', name='activate_account'), url(r'^register/$', 'register', name='registration'), # Password reset url(r'^register/reset_password/$', 'reset_password', name='reset_password'), # Login url(r'^login/$', 'login', name='login'), # Logout url(r'^logout/$', 'logout', name='logout'), )
from django.conf.urls import patterns, url urlpatterns = patterns('apps.auth.views', # # Authentication and Registration URLs # # Registration url(r'^register/activate/(?P<key>[a-zA-Z0-9-]+)/$', 'activate', name='activate_account'), url(r'^register/$', 'register', name='registration'), # Password reset url(r'^register/reset_password/$', 'reset_password', name='reset_password'), # Login url(r'^login/$', 'login', name='login'), # Logout url(r'^logout/$', 'logout', name='logout'), )
Allow a hypen in activation URL
Allow a hypen in activation URL Make activation work with my login (ei-grad).
Python
bsd-3-clause
EVE-Tools/element43,EVE-Tools/element43
--- +++ @@ -6,7 +6,7 @@ # # Registration - url(r'^register/activate/(?P<key>[a-zA-Z0-9]+)/$', 'activate', name='activate_account'), + url(r'^register/activate/(?P<key>[a-zA-Z0-9-]+)/$', 'activate', name='activate_account'), url(r'^register/$', 'register', name='registration'), # Password reset
57170909979d89c6887fde80510855c2ea4770e9
django_prometheus/__init__.py
django_prometheus/__init__.py
"""Django-Prometheus https://github.com/korfuri/django-prometheus """ # Import all files that define metrics. This has the effect that # `import django_prometheus` will always instanciate all metric # objects right away. import django_prometheus.middleware import django_prometheus.models # Import pip_prometheus to export the pip metrics automatically. import pip_prometheus default_app_config = 'django_prometheus.apps.DjangoPrometheusConfig'
"""Django-Prometheus https://github.com/korfuri/django-prometheus """ # Import all files that define metrics. This has the effect that # `import django_prometheus` will always instanciate all metric # objects right away. import django_prometheus.middleware import django_prometheus.models # Import pip_prometheus to export the pip metrics automatically. try: import pip_prometheus except ImportError: # If people don't have pip, don't export anything. pass default_app_config = 'django_prometheus.apps.DjangoPrometheusConfig'
Make the use of pip-prometheus optional.
Make the use of pip-prometheus optional.
Python
apache-2.0
obytes/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus,korfuri/django-prometheus
--- +++ @@ -10,6 +10,10 @@ import django_prometheus.models # Import pip_prometheus to export the pip metrics automatically. -import pip_prometheus +try: + import pip_prometheus +except ImportError: + # If people don't have pip, don't export anything. + pass default_app_config = 'django_prometheus.apps.DjangoPrometheusConfig'
343fadde748aa66d17d21d79cb481c9c09782466
search/signals.py
search/signals.py
from django.dispatch import Signal, receiver from django.core.mail import EmailMultiAlternatives from search.models import Person import logging from django.conf import settings unknown_tag_signal = Signal(providing_args=['author', 'title', 'tags']) logger = logging.getLogger('search') @receiver(unknown_tag_signal) def unknown_tag_callback(sender, **kwargs): author = Person.objects.get(pk=kwargs['author']) title = kwargs['title'] unknown_tags = kwargs['tags'] message = "Dear moderator,\n\n" + \ "{person} created an item '{title}' ".format(person=author.name, title=title) + \ "and tried to add the following nonexisting tags:\n\n" + \ "Tokens: " + ','.join(unknown_tags['token']) + "\n" + \ "Persons: " + ','.join(unknown_tags['person']) + "\n" + \ "Literals: " + ','.join(unknown_tags['literal']) + "\n\n" + \ "It is up to you to determine whether these tags should " + \ "exist and add them to both the system and this item." + \ "\n\nThis message was generated automatically." logger.debug(message) subject = '[Starfish] User {person} uses unknown tags'.format(person=author.name) from_email = "notifications@%s" % (settings.HOSTNAME,) msg = EmailMultiAlternatives(subject, message, from_email, to=settings.ADMIN_NOTIFICATION_EMAIL) msg.send(fail_silently=True)
from django.dispatch import Signal, receiver from django.core.mail import EmailMultiAlternatives from search.models import Person import logging from django.conf import settings unknown_tag_signal = Signal(providing_args=['author', 'title', 'tags']) logger = logging.getLogger('search') @receiver(unknown_tag_signal) def unknown_tag_callback(sender, **kwargs): author = Person.objects.get(pk=kwargs['author']) title = kwargs['title'] unknown_tags = kwargs['tags'] message = "Dear moderator,\n\n" + \ u"{person} created an item '{title}' ".format(person=author.name, title=title) + \ "and tried to add the following nonexisting tags:\n\n" + \ "Tokens: " + ','.join(unknown_tags['token']) + "\n" + \ "Persons: " + ','.join(unknown_tags['person']) + "\n" + \ "Literals: " + ','.join(unknown_tags['literal']) + "\n\n" + \ "It is up to you to determine whether these tags should " + \ "exist and add them to both the system and this item." + \ "\n\nThis message was generated automatically." logger.debug(message) subject = u'[Starfish] User {person} uses unknown tags'.format( person=author.name) from_email = "notifications@%s" % (settings.HOSTNAME,) msg = EmailMultiAlternatives(subject, message, from_email, to=settings.ADMIN_NOTIFICATION_EMAIL) msg.send(fail_silently=True)
Fix unicode issues with new tag
Fix unicode issues with new tag
Python
agpl-3.0
ictofnwi/steep,ictofnwi/steep,ictofnwi/steep,ictofnwi/steep
--- +++ @@ -14,7 +14,7 @@ title = kwargs['title'] unknown_tags = kwargs['tags'] message = "Dear moderator,\n\n" + \ - "{person} created an item '{title}' ".format(person=author.name, + u"{person} created an item '{title}' ".format(person=author.name, title=title) + \ "and tried to add the following nonexisting tags:\n\n" + \ "Tokens: " + ','.join(unknown_tags['token']) + "\n" + \ @@ -24,7 +24,8 @@ "exist and add them to both the system and this item." + \ "\n\nThis message was generated automatically." logger.debug(message) - subject = '[Starfish] User {person} uses unknown tags'.format(person=author.name) + subject = u'[Starfish] User {person} uses unknown tags'.format( + person=author.name) from_email = "notifications@%s" % (settings.HOSTNAME,) msg = EmailMultiAlternatives(subject, message, from_email, to=settings.ADMIN_NOTIFICATION_EMAIL)
9abce17371ac1b2a0e29a90b39ce8560f05bf47e
pastas/version.py
pastas/version.py
# This is the only location where the version will be written and changed. # Based on https://packaging.python.org/single_source_version/ __version__ = '0.12.0b'
# This is the only location where the version will be written and changed. # Based on https://packaging.python.org/single_source_version/ __version__ = '0.12.0'
Prepare update Master to 0.12.0
Prepare update Master to 0.12.0
Python
mit
gwtsa/gwtsa,pastas/pastas,pastas/pasta
--- +++ @@ -1,3 +1,3 @@ # This is the only location where the version will be written and changed. # Based on https://packaging.python.org/single_source_version/ -__version__ = '0.12.0b' +__version__ = '0.12.0'
55d372b4887bc9461d9e5ea958a5703ed19bdcae
frontend/checkFrontend.py
frontend/checkFrontend.py
#!/bin/env python # # Description: # Check if a glideinFrontend is running # # Arguments: # $1 = config file # # Author: # Igor Sfiligoi Jul 17th 2008 # import sys,os.path sys.path.append(os.path.join(sys.path[0],"../lib")) import glideinFrontendPidLib config_dict={} try: execfile(sys.argv[1],config_dict) log_dir=config_dict['log_dir'] frontend_pid=glideinFrontendPidLib.get_frontend_pid(log_dir) except: print "Not running" sys.exit(1) print "Running" sys.exit(0)
#!/bin/env python # # Description: # Check if a glideinFrontend is running # # Arguments: # $1 = work_dir # # Author: # Igor Sfiligoi # import sys,os.path sys.path.append(os.path.join(sys.path[0],"../lib")) import glideinFrontendPidLib try: work_dir=sys.argv[1] frontend_pid=glideinFrontendPidLib.get_frontend_pid(work_dir) except: print "Not running" sys.exit(1) print "Running" sys.exit(0)
Rewrite based on factory one
Rewrite based on factory one
Python
bsd-3-clause
holzman/glideinwms-old,bbockelm/glideinWMS,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS
--- +++ @@ -4,21 +4,19 @@ # Check if a glideinFrontend is running # # Arguments: -# $1 = config file +# $1 = work_dir # # Author: -# Igor Sfiligoi Jul 17th 2008 +# Igor Sfiligoi # import sys,os.path sys.path.append(os.path.join(sys.path[0],"../lib")) import glideinFrontendPidLib -config_dict={} try: - execfile(sys.argv[1],config_dict) - log_dir=config_dict['log_dir'] - frontend_pid=glideinFrontendPidLib.get_frontend_pid(log_dir) + work_dir=sys.argv[1] + frontend_pid=glideinFrontendPidLib.get_frontend_pid(work_dir) except: print "Not running" sys.exit(1)
9a23ef917dbd22ad30237ca51ed4d5d43b1bfa4d
python/mia_server.py
python/mia_server.py
#!/usr/bin/env python HOST = '' PORT = 4080 def mia_server_start(): pass if __name__ == "__main__": mia_server_start()
#!/usr/bin/env python HOST = '' PORT = 4080 DEBUG = True def handle_packet(sock, addr, data): if data.startswith("REGISTER;"): response = register_player(data, addr) elif data.startswith("REGISTER_SPECTATOR"): response = register_spectator(data, addr) if response: if DEBUG: print "Replying '",response,"'" sock.sendto(response, addr) else: if DEBUG: print "No response" def mia_server_start(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((HOST, PORT)) while 1: try: data, addr = sock.recvfrom(1024) if DEBUG: print "Received", data.strip(), "from", addr handle_packet(sock, addr, data.strip()) except KeyboardInterrupt: print "Shutting down server" break except: pass s.close() if __name__ == "__main__": mia_server_start()
Add python mia server UDP loop
Add python mia server UDP loop
Python
mit
SteffenBauer/mia_elixir,SteffenBauer/mia_elixir
--- +++ @@ -3,8 +3,33 @@ HOST = '' PORT = 4080 +DEBUG = True + +def handle_packet(sock, addr, data): + if data.startswith("REGISTER;"): + response = register_player(data, addr) + elif data.startswith("REGISTER_SPECTATOR"): + response = register_spectator(data, addr) + + if response: + if DEBUG: print "Replying '",response,"'" + sock.sendto(response, addr) + else: + if DEBUG: print "No response" + def mia_server_start(): - pass + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.bind((HOST, PORT)) + while 1: + try: + data, addr = sock.recvfrom(1024) + if DEBUG: print "Received", data.strip(), "from", addr + handle_packet(sock, addr, data.strip()) + except KeyboardInterrupt: + print "Shutting down server" + break + except: pass + s.close() if __name__ == "__main__": mia_server_start()
ef8452020c95b08fa8aed9840a7e0cb94eaec514
__openerp__.py
__openerp__.py
# -*- coding: utf-8 -*- { 'name': 'Document Attachment', 'version': '1.2', 'author': 'XCG Consulting', 'category': 'Dependency', 'description': """Enchancements to the ir.attachment module to manage kinds of attachments that can be linked with OpenERP objects. The implenter has to: - Pass 'res_model' and 'res_id' in the context. - Define menus and actions should it want to allow changing document types. Document attachments are displayed in a many2many field; it can optionally be changed to work like a one2many field by using the "domain="[('res_id', '=', id)]" attribute. """, 'website': 'http://www.openerp-experts.com', 'depends': [ 'base', 'document', ], 'data': [ 'security/ir.model.access.csv', 'document_attachment.xml', ], 'test': [ ], 'installable': True, }
# -*- coding: utf-8 -*- { 'name': 'Document Attachment', 'version': '1.2', 'author': 'XCG Consulting', 'category': 'Dependency', 'description': """Enchancements to the ir.attachment module to manage kinds of attachments that can be linked with OpenERP objects. The implenter has to: - Pass 'res_model' and 'res_id' in the context. - Define menus and actions should it want to allow changing document types. Document attachments are displayed in a many2many field; it can optionally be changed to work like a one2many field by using the "domain="[('res_id', '=', id)]" attribute. """, 'website': 'www.odoo.consulting/', 'depends': [ 'base', 'document', ], 'data': [ 'security/ir.model.access.csv', 'document_attachment.xml', ], 'test': [ ], 'installable': True, }
Change url of the website
Change url of the website
Python
agpl-3.0
xcgd/document_attachment
--- +++ @@ -15,7 +15,7 @@ changed to work like a one2many field by using the "domain="[('res_id', '=', id)]" attribute. """, - 'website': 'http://www.openerp-experts.com', + 'website': 'www.odoo.consulting/', 'depends': [ 'base', 'document',
fae501041857f1e4eea2b5157feb94a3f3c84f18
pinax/__init__.py
pinax/__init__.py
VERSION = (0, 9, 0, "a", 1) # following PEP 386 def get_version(): version = "%s.%s" % (VERSION[0], VERSION[1]) if VERSION[2]: version = "%s.%s" % (version, VERSION[2]) if VERSION[3] != "f": version = "%s%s%s" % (version, VERSION[3], VERSION[4]) return version __version__ = get_version()
import os VERSION = (0, 9, 0, "a", 1) # following PEP 386 def get_version(): version = "%s.%s" % (VERSION[0], VERSION[1]) if VERSION[2]: version = "%s.%s" % (version, VERSION[2]) if VERSION[3] != "f": version = "%s%s%s" % (version, VERSION[3], VERSION[4]) dev = os.environ.get("PINAX_DEV_N") if dev: version = "%s.dev%s" % (version, dev) return version __version__ = get_version()
Support development versions using an environment variable
Support development versions using an environment variable
Python
mit
amarandon/pinax,amarandon/pinax,amarandon/pinax,amarandon/pinax
--- +++ @@ -1,3 +1,6 @@ +import os + + VERSION = (0, 9, 0, "a", 1) # following PEP 386 @@ -7,6 +10,9 @@ version = "%s.%s" % (version, VERSION[2]) if VERSION[3] != "f": version = "%s%s%s" % (version, VERSION[3], VERSION[4]) + dev = os.environ.get("PINAX_DEV_N") + if dev: + version = "%s.dev%s" % (version, dev) return version
ab3b2e9a681740159897ef8592c4f891df791119
publisher_test_project/manage.py
publisher_test_project/manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python3 import os import sys print("sys.real_prefix:", getattr(sys, "real_prefix", "-")) print("sys.prefix:", sys.prefix) if __name__ == "__main__": if "VIRTUAL_ENV" not in os.environ: raise RuntimeError(" *** ERROR: Virtual env not activated! *** ") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Raise error if virtualenv not activated
Raise error if virtualenv not activated
Python
bsd-3-clause
wearehoods/django-model-publisher-ai,wearehoods/django-model-publisher-ai,wearehoods/django-model-publisher-ai
--- +++ @@ -1,8 +1,15 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 + import os import sys +print("sys.real_prefix:", getattr(sys, "real_prefix", "-")) +print("sys.prefix:", sys.prefix) + if __name__ == "__main__": + if "VIRTUAL_ENV" not in os.environ: + raise RuntimeError(" *** ERROR: Virtual env not activated! *** ") + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.management import execute_from_command_line
daeda47aa33abad38f8f93ef9dde261809171c9b
podcasts/models.py
podcasts/models.py
from django.db import models class Podcast(models.Model): title = models.CharField(max_length=100, blank=True) link = models.URLField(blank=True) feed = models.URLField() description = models.CharField(max_length=200, blank=True) def __str__(self): return self.title def title_or_unnamed(self): return self.title if self.title else 'unnamed' class Episode(models.Model): title = models.CharField(max_length=200) link = models.URLField() description = models.TextField(blank=True) podcast = models.ForeignKey(Podcast)
from django.db import models class Podcast(models.Model): title = models.CharField(max_length=100, blank=True) link = models.URLField(blank=True) feed = models.URLField() description = models.CharField(max_length=200, blank=True) def __str__(self): return self.title def title_or_unnamed(self): return self.title if self.title else 'unnamed' class Episode(models.Model): title = models.CharField(max_length=200) link = models.URLField(blank=True) description = models.TextField(blank=True) podcast = models.ForeignKey(Podcast)
Make so an episode link isn't mandatory
Make so an episode link isn't mandatory
Python
mit
matachi/sputnik,matachi/sputnik,matachi/sputnik,matachi/sputnik
--- +++ @@ -16,6 +16,6 @@ class Episode(models.Model): title = models.CharField(max_length=200) - link = models.URLField() + link = models.URLField(blank=True) description = models.TextField(blank=True) podcast = models.ForeignKey(Podcast)
e49cd7aeaf81ed12490d82b8a65ca93088ec916e
spacy/__init__.py
spacy/__init__.py
# coding: utf8 from __future__ import unicode_literals from .cli.info import info as cli_info from .glossary import explain from .deprecated import resolve_load_name from .about import __version__ from . import util def load(name, **overrides): name = resolve_load_name(name, **overrides) return util.load_model(name, **overrides) def blank(name, **kwargs): LangClass = util.get_lang_class(name) return LangClass(**kwargs) def info(model=None, markdown=False): return cli_info(None, model, markdown)
# coding: utf8 from __future__ import unicode_literals from .cli.info import info as cli_info from .glossary import explain from .about import __version__ from . import util def load(name, **overrides): from .deprecated import resolve_load_name name = resolve_load_name(name, **overrides) return util.load_model(name, **overrides) def blank(name, **kwargs): LangClass = util.get_lang_class(name) return LangClass(**kwargs) def info(model=None, markdown=False): return cli_info(None, model, markdown)
Move import into load to avoid circular imports
Move import into load to avoid circular imports
Python
mit
aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,recognai/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,honnibal/spaCy,honnibal/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy
--- +++ @@ -3,12 +3,12 @@ from .cli.info import info as cli_info from .glossary import explain -from .deprecated import resolve_load_name from .about import __version__ from . import util def load(name, **overrides): + from .deprecated import resolve_load_name name = resolve_load_name(name, **overrides) return util.load_model(name, **overrides)
5b1eee618e57cd3cd84df4b819ef69876db55ddf
clock.py
clock.py
from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() job_defaults = { 'coalesce': False, 'max_instances': 2 } scheduler = BlockingScheduler(job_defaults=job_defaults) @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier (interval=1)") subprocess.check_call( "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685", shell=True) @scheduler.scheduled_job('interval', minutes=10) def timed_job_min10(): print("Run notifier (interval=10)") subprocess.check_call( "notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685", shell=True) @scheduler.scheduled_job('interval', days=7) def timed_job_days7(): print("Run teacher_error_resetter") subprocess.check_call( "teacher_error_resetter -concurrency=5", shell=True) scheduler.start()
from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() job_defaults = { 'coalesce': False, 'max_instances': 2 } scheduler = BlockingScheduler(job_defaults=job_defaults) @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier (interval=1)") subprocess.check_call( "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685", shell=True) @scheduler.scheduled_job('interval', minutes=20) def timed_job_min10(): print("Run notifier (interval=10)") subprocess.check_call( "notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685", shell=True) @scheduler.scheduled_job('interval', days=7) def timed_job_days7(): print("Run teacher_error_resetter") subprocess.check_call( "teacher_error_resetter -concurrency=5", shell=True) scheduler.start()
Change interval: 10 -> 20
Change interval: 10 -> 20
Python
mit
oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije
--- +++ @@ -19,7 +19,7 @@ shell=True) -@scheduler.scheduled_job('interval', minutes=10) +@scheduler.scheduled_job('interval', minutes=20) def timed_job_min10(): print("Run notifier (interval=10)") subprocess.check_call(
c54240e6d9f6393370fe94f2cd05476680cf17f2
pygtfs/__init__.py
pygtfs/__init__.py
from .loader import append_feed, delete_feed, overwrite_feed, list_feeds from .schedule import Schedule from ._version import version as __version__
import warnings from .loader import append_feed, delete_feed, overwrite_feed, list_feeds from .schedule import Schedule try: from ._version import version as __version__ except ImportError: warnings.warn("pygtfs should be installed for the version to work") __version__ = "0"
Allow usage directly from the code (fix the _version import)
Allow usage directly from the code (fix the _version import)
Python
mit
jarondl/pygtfs
--- +++ @@ -1,3 +1,10 @@ +import warnings + from .loader import append_feed, delete_feed, overwrite_feed, list_feeds from .schedule import Schedule -from ._version import version as __version__ + +try: + from ._version import version as __version__ +except ImportError: + warnings.warn("pygtfs should be installed for the version to work") + __version__ = "0"
215746e2fd7e5f78b6dae031aae6a935ab164dd1
pyjokes/pyjokes.py
pyjokes/pyjokes.py
from __future__ import absolute_import import random import importlib def get_joke(category='neutral', language='en'): """ Parameters ---------- category: str Choices: 'neutral', 'explicit', 'chuck', 'all' lang: str Choices: 'en', 'de', 'es' Returns ------- joke: str """ if language == 'en': from .jokes_en import jokes elif language == 'de': from .jokes_de import jokes elif language == 'es': from .jokes_es import jokes try: jokes = jokes[category] except: return 'Could not get the joke. Choose another category.' else: return random.choice(jokes)
from __future__ import absolute_import import random from .jokes_en import jokes as jokes_en from .jokes_de import jokes as jokes_de from .jokes_es import jokes as jokes_es all_jokes = { 'en': jokes_en, 'de': jokes_de, 'es': jokes_es, } class LanguageNotFoundError(Exception): pass class CategoryNotFoundError(Exception): pass def get_joke(category='neutral', language='en'): """ Parameters ---------- category: str Choices: 'neutral', 'explicit', 'chuck', 'all' lang: str Choices: 'en', 'de', 'es' Returns ------- joke: str """ if language in all_jokes: jokes = all_jokes[language] else: raise LanguageNotFoundError('No such language %s' % language) if category in jokes: jokes = jokes[category] return random.choice(jokes) else: raise CategoryNotFound('No such category %s' % category)
Use dict not if/else, add exceptions
Use dict not if/else, add exceptions
Python
bsd-3-clause
borjaayerdi/pyjokes,birdsarah/pyjokes,pyjokes/pyjokes,bennuttall/pyjokes,trojjer/pyjokes,gmarkall/pyjokes,martinohanlon/pyjokes,ElectronicsGeek/pyjokes
--- +++ @@ -1,6 +1,25 @@ from __future__ import absolute_import import random -import importlib + +from .jokes_en import jokes as jokes_en +from .jokes_de import jokes as jokes_de +from .jokes_es import jokes as jokes_es + + +all_jokes = { + 'en': jokes_en, + 'de': jokes_de, + 'es': jokes_es, +} + + +class LanguageNotFoundError(Exception): + pass + + +class CategoryNotFoundError(Exception): + pass + def get_joke(category='neutral', language='en'): """ @@ -16,16 +35,13 @@ joke: str """ - if language == 'en': - from .jokes_en import jokes - elif language == 'de': - from .jokes_de import jokes - elif language == 'es': - from .jokes_es import jokes + if language in all_jokes: + jokes = all_jokes[language] + else: + raise LanguageNotFoundError('No such language %s' % language) - try: + if category in jokes: jokes = jokes[category] - except: - return 'Could not get the joke. Choose another category.' + return random.choice(jokes) else: - return random.choice(jokes) + raise CategoryNotFound('No such category %s' % category)
52a2b6c8ac87678202634806d9a7f570eab5b8bb
mysite/urls.py
mysite/urls.py
from django.conf.urls.defaults import * import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^search/$', 'mysite.search.views.fetch_bugs'), (r'^admin/(.*)', admin.site.root), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT}), )
from django.conf.urls.defaults import * import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^search/$', 'mysite.search.views.fetch_bugs'), (r'^admin/(.*)', admin.site.root), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT}), (r'^$', 'mysite.search.views.fetch_bugs'), )
Make front page be == /search/
Make front page be == /search/
Python
agpl-3.0
willingc/oh-mainline,mzdaniel/oh-mainline,onceuponatimeforever/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,sudheesh001/oh-mainline,moijes12/oh-mainline,heeraj123/oh-mainline,heeraj123/oh-mainline,campbe13/openhatch,waseem18/oh-mainline,campbe13/openhatch,openhatch/oh-mainline,ojengwa/oh-mainline,vipul-sharma20/oh-mainline,campbe13/openhatch,onceuponatimeforever/oh-mainline,eeshangarg/oh-mainline,mzdaniel/oh-mainline,willingc/oh-mainline,waseem18/oh-mainline,waseem18/oh-mainline,jledbetter/openhatch,willingc/oh-mainline,openhatch/oh-mainline,jledbetter/openhatch,Changaco/oh-mainline,openhatch/oh-mainline,SnappleCap/oh-mainline,heeraj123/oh-mainline,ehashman/oh-mainline,sudheesh001/oh-mainline,nirmeshk/oh-mainline,Changaco/oh-mainline,nirmeshk/oh-mainline,vipul-sharma20/oh-mainline,moijes12/oh-mainline,mzdaniel/oh-mainline,eeshangarg/oh-mainline,ojengwa/oh-mainline,heeraj123/oh-mainline,campbe13/openhatch,mzdaniel/oh-mainline,Changaco/oh-mainline,eeshangarg/oh-mainline,sudheesh001/oh-mainline,ehashman/oh-mainline,ehashman/oh-mainline,SnappleCap/oh-mainline,sudheesh001/oh-mainline,moijes12/oh-mainline,ojengwa/oh-mainline,ojengwa/oh-mainline,ehashman/oh-mainline,nirmeshk/oh-mainline,willingc/oh-mainline,heeraj123/oh-mainline,campbe13/openhatch,eeshangarg/oh-mainline,ehashman/oh-mainline,jledbetter/openhatch,Changaco/oh-mainline,SnappleCap/oh-mainline,vipul-sharma20/oh-mainline,vipul-sharma20/oh-mainline,mzdaniel/oh-mainline,openhatch/oh-mainline,mzdaniel/oh-mainline,SnappleCap/oh-mainline,ojengwa/oh-mainline,waseem18/oh-mainline,nirmeshk/oh-mainline,moijes12/oh-mainline,willingc/oh-mainline,nirmeshk/oh-mainline,moijes12/oh-mainline,jledbetter/openhatch,onceuponatimeforever/oh-mainline,eeshangarg/oh-mainline,jledbetter/openhatch,SnappleCap/oh-mainline,waseem18/oh-mainline,vipul-sharma20/oh-mainline,openhatch/oh-mainline,onceuponatimeforever/oh-mainline,sudheesh001/oh-mainline,onceuponatimeforever/oh-mainline
--- +++ @@ -10,4 +10,7 @@ (r'^admin/(.*)', admin.site.root), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT}), + (r'^$', 'mysite.search.views.fetch_bugs'), ) + +
b4fbb4784b61001cc29c311e3b50c3fad3c60ef0
nipap/setup.py
nipap/setup.py
#!/usr/bin/env python from distutils.core import setup import nipap long_desc = open('README.rst').read() short_desc = long_desc.split('\n')[0].split(' - ')[1].strip() setup( name = 'nipap', version = nipap.__version__, description = short_desc, long_description = long_desc, author = nipap.__author__, author_email = nipap.__author_email__, license = nipap.__license__, url = nipap.__url__, packages = ['nipap'], keywords = ['nipap'], requires = ['twisted', 'ldap', 'sqlite3', 'IPy', 'psycopg2'], data_files = [ ('/etc/nipap/', ['local_auth.db', 'nipap.conf']), ('/usr/bin/', ['nipap-passwd']), ('/usr/sbin/', ['nipapd']), ('/usr/share/nipap/sql/', [ 'sql/functions.plsql', 'sql/ip_net.plsql' ]) ], classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Telecommunications Industry', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.6', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware' ] )
#!/usr/bin/env python from distutils.core import setup import nipap long_desc = open('README.rst').read() short_desc = long_desc.split('\n')[0].split(' - ')[1].strip() setup( name = 'nipap', version = nipap.__version__, description = short_desc, long_description = long_desc, author = nipap.__author__, author_email = nipap.__author_email__, license = nipap.__license__, url = nipap.__url__, packages = ['nipap'], keywords = ['nipap'], requires = ['twisted', 'ldap', 'sqlite3', 'IPy', 'psycopg2'], data_files = [ ('/etc/nipap/', ['local_auth.db', 'nipap.conf']), ('/usr/sbin/', ['nipapd', 'nipap-passwd']), ('/usr/share/nipap/sql/', [ 'sql/functions.plsql', 'sql/ip_net.plsql' ]) ], classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Telecommunications Industry', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.6', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware' ] )
Change installation path for nipap-passwd
Change installation path for nipap-passwd This really is a "admin tool" and so we put it in /usr/sbin instead! Fixes #196
Python
mit
SpriteLink/NIPAP,garberg/NIPAP,SoundGoof/NIPAP,SpriteLink/NIPAP,fredsod/NIPAP,fredsod/NIPAP,bbaja42/NIPAP,garberg/NIPAP,SpriteLink/NIPAP,ettrig/NIPAP,SoundGoof/NIPAP,SpriteLink/NIPAP,ettrig/NIPAP,garberg/NIPAP,SpriteLink/NIPAP,garberg/NIPAP,plajjan/NIPAP,plajjan/NIPAP,SoundGoof/NIPAP,plajjan/NIPAP,bbaja42/NIPAP,bbaja42/NIPAP,SoundGoof/NIPAP,bbaja42/NIPAP,bbaja42/NIPAP,SoundGoof/NIPAP,plajjan/NIPAP,ettrig/NIPAP,ettrig/NIPAP,SoundGoof/NIPAP,fredsod/NIPAP,bbaja42/NIPAP,ettrig/NIPAP,garberg/NIPAP,fredsod/NIPAP,plajjan/NIPAP,ettrig/NIPAP,SpriteLink/NIPAP,plajjan/NIPAP,fredsod/NIPAP,garberg/NIPAP,fredsod/NIPAP
--- +++ @@ -21,8 +21,7 @@ requires = ['twisted', 'ldap', 'sqlite3', 'IPy', 'psycopg2'], data_files = [ ('/etc/nipap/', ['local_auth.db', 'nipap.conf']), - ('/usr/bin/', ['nipap-passwd']), - ('/usr/sbin/', ['nipapd']), + ('/usr/sbin/', ['nipapd', 'nipap-passwd']), ('/usr/share/nipap/sql/', [ 'sql/functions.plsql', 'sql/ip_net.plsql'
2e941cf1f6208b9ac2f6039681c24502b324ab5f
planner/models.py
planner/models.py
import datetime from django.conf import settings from django.db import models from django.utils.encoding import python_2_unicode_compatible class Milestone(models.Model): date = models.DateTimeField() @python_2_unicode_compatible class School(models.Model): name = models.TextField() slug = models.SlugField(max_length=256, unique=True) url = models.URLField(unique=True) milestones_url = models.URLField() def __str__(self): return self.name class Semester(models.Model): active = models.BooleanField(default=True) date = models.DateField() # XXX: This is locked in for the default value of the initial migration. # I'm not sure what needs to be done to let me safely delete this and # have migrations continue to work. def current_year(): today = datetime.date.today() return today.year @python_2_unicode_compatible class Student(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students') first_name = models.TextField() last_name = models.TextField() # XXX: Remove null constraint after migration. matriculation_semester = models.ForeignKey( Semester, null=True, on_delete=models.PROTECT) def __str__(self): return '{} {}'.format(self.first_name, self.last_name)
import datetime from django.conf import settings from django.db import models from django.utils.encoding import python_2_unicode_compatible class Milestone(models.Model): date = models.DateTimeField() @python_2_unicode_compatible class School(models.Model): name = models.TextField() slug = models.SlugField(max_length=256, unique=True) url = models.URLField(unique=True) milestones_url = models.URLField() def __str__(self): return self.name @python_2_unicode_compatible class Semester(models.Model): active = models.BooleanField(default=True) date = models.DateField() def __str__(self): return str(self.date) # XXX: This is locked in for the default value of the initial migration. # I'm not sure what needs to be done to let me safely delete this and # have migrations continue to work. def current_year(): today = datetime.date.today() return today.year @python_2_unicode_compatible class Student(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students') first_name = models.TextField() last_name = models.TextField() # XXX: Remove null constraint after migration. matriculation_semester = models.ForeignKey( Semester, null=True, on_delete=models.PROTECT) def __str__(self): return '{} {}'.format(self.first_name, self.last_name)
Add Semester str method for admin interface.
Add Semester str method for admin interface. Fixes #149
Python
bsd-2-clause
mblayman/lcp,mblayman/lcp,mblayman/lcp
--- +++ @@ -20,9 +20,13 @@ return self.name +@python_2_unicode_compatible class Semester(models.Model): active = models.BooleanField(default=True) date = models.DateField() + + def __str__(self): + return str(self.date) # XXX: This is locked in for the default value of the initial migration.
fd5810c86f5998c2e2a7b96f09e82b40fbe2cc11
string/first-str-substr-occr.py
string/first-str-substr-occr.py
# Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1 def find_substring(string, substr): string_len = len(string) substr_len = len(substr) i = 0 if substr_len >= 1: i = 0 while i < string_len: if string[i] == substr[j]: if j == substr_len: return i - substr_len j += 1 else: j = 0 i += 1
# Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1 def find_substring(string, substr): string_len = len(string) substr_len = len(substr) i = 0 if substr_len >= 1: i = 0 while i < string_len: if string[i] == substr[j]: if j == substr_len: return i - substr_len j += 1 else: j = 0 i += 1 return -1
Return -1 if no substring is found
Return -1 if no substring is found
Python
mit
derekmpham/interview-prep,derekmpham/interview-prep
--- +++ @@ -15,3 +15,5 @@ else: j = 0 i += 1 + + return -1
0994fb6a8c924e907151764f9c1eaa19f2c3aea7
salt/returners/syslog_return.py
salt/returners/syslog_return.py
# -*- coding: utf-8 -*- ''' Return data to the host operating system's syslog facility Required python modules: syslog, json The syslog returner simply reuses the operating system's syslog facility to log return data To use the syslog returner, append '--return syslog' to the salt command. .. code-block:: bash salt '*' test.ping --return syslog ''' from __future__ import absolute_import # Import python libs import json try: import syslog HAS_SYSLOG = True except ImportError: HAS_SYSLOG = False # Import Salt libs import salt.utils.jid # Define the module's virtual name __virtualname__ = 'syslog' def __virtual__(): if not HAS_SYSLOG: return False return __virtualname__ def returner(ret): ''' Return data to the local syslog ''' syslog.syslog(syslog.LOG_INFO, 'salt-minion: {0}'.format(json.dumps(ret))) def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid()
# -*- coding: utf-8 -*- ''' Return data to the host operating system's syslog facility Required python modules: syslog, json The syslog returner simply reuses the operating system's syslog facility to log return data To use the syslog returner, append '--return syslog' to the salt command. .. code-block:: bash salt '*' test.ping --return syslog ''' from __future__ import absolute_import # Import python libs import json try: import syslog HAS_SYSLOG = True except ImportError: HAS_SYSLOG = False # Import Salt libs import salt.utils.jid # Define the module's virtual name __virtualname__ = 'syslog' def __virtual__(): if not HAS_SYSLOG: return False return __virtualname__ def returner(ret): ''' Return data to the local syslog ''' syslog.syslog(syslog.LOG_INFO, '{0}'.format(json.dumps(ret))) def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument ''' Do any work necessary to prepare a JID, including sending a custom id ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid()
Remove redundant text from syslog returner
Remove redundant text from syslog returner The implicit call to syslog.openlog will already add salt-minion (technically `sys.argv[0]`) to the syslog.syslog call. It's redundant (and not technically correct) to have salt-minion here. Can also be applied to 2015.8 and develop without issue. Fixes #27756
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -41,7 +41,7 @@ ''' Return data to the local syslog ''' - syslog.syslog(syslog.LOG_INFO, 'salt-minion: {0}'.format(json.dumps(ret))) + syslog.syslog(syslog.LOG_INFO, '{0}'.format(json.dumps(ret))) def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
c9880fa56a6667d79bfc28fe4091f1cdbf3b2210
teknologr/registration/views.py
teknologr/registration/views.py
from django.shortcuts import render, redirect from django.conf import settings from django.views import View from members.programmes import DEGREE_PROGRAMME_CHOICES from registration.forms import RegistrationForm from registration.mailutils import mailApplicantSubmission class BaseView(View): context = {'DEBUG': settings.DEBUG} class HomeView(BaseView): template = 'registration.html' def get(self, request): self.context['programmes'] = DEGREE_PROGRAMME_CHOICES self.context['form'] = RegistrationForm() return render(request, self.template, self.context) class SubmitView(BaseView): template = 'submit.html' def get(self, request, **kwargs): previous_context = request.session.pop('context', None) if not previous_context: return redirect('registration.views.home') return render(request, self.template, previous_context) def post(self, request): form = RegistrationForm(request.POST) if form.is_valid(): registration = form.instance self.context['name'] = registration.preferred_name or registration.given_names.split(' ')[0] self.context['email'] = registration.email # FIXME: handle situation where email is not sent (e.g. admin log tool) mailApplicantSubmission(self.context) registration.save() else: self.context['form'] = form return render(request, HomeView.template, self.context, status=400) request.session['context'] = self.context return redirect('registration.views.submit')
from django.shortcuts import render, redirect from django.conf import settings from django.views import View from members.programmes import DEGREE_PROGRAMME_CHOICES from registration.forms import RegistrationForm from registration.mailutils import mailApplicantSubmission class BaseView(View): context = {'DEBUG': settings.DEBUG} class HomeView(BaseView): template = 'registration.html' def get(self, request): self.context['programmes'] = DEGREE_PROGRAMME_CHOICES self.context['form'] = RegistrationForm() return render(request, self.template, self.context) class SubmitView(BaseView): template = 'submit.html' def get(self, request, **kwargs): previous_context = request.session.pop('context', None) if not previous_context: return redirect('registration.views.home') return render(request, self.template, previous_context) def post(self, request): form = RegistrationForm(request.POST) if form.is_valid(): registration = form.instance next_context = { 'name': registration.preferred_name or registration.given_names.split(' ')[0], 'email': registration.email, } # FIXME: handle situation where email is not sent (e.g. admin log tool) mailApplicantSubmission(self.context) registration.save() request.session['context'] = next_context return redirect('registration.views.submit') else: self.context['form'] = form return render(request, HomeView.template, self.context, status=400)
Fix serialization issue with form submission
Fix serialization issue with form submission
Python
mit
Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io
--- +++ @@ -34,16 +34,18 @@ if form.is_valid(): registration = form.instance - self.context['name'] = registration.preferred_name or registration.given_names.split(' ')[0] - self.context['email'] = registration.email + next_context = { + 'name': registration.preferred_name or registration.given_names.split(' ')[0], + 'email': registration.email, + } # FIXME: handle situation where email is not sent (e.g. admin log tool) mailApplicantSubmission(self.context) registration.save() + + request.session['context'] = next_context + return redirect('registration.views.submit') else: self.context['form'] = form return render(request, HomeView.template, self.context, status=400) - - request.session['context'] = self.context - return redirect('registration.views.submit')
2fc13f58d8deba0f34c1e33ed78884630e8a7804
pages/tests.py
pages/tests.py
from django.test import TestCase from pages.models import * from django.test.client import Client class PagesTestCase(TestCase): fixtures = ['tests.json'] def test_01_add_page(self): """ Test that the add admin page could be displayed correctly """ c = Client() c.login(username= 'batiste', password='b') response = c.get('/admin/pages/page/add/') assert(response.status_code == 200)
from django.test import TestCase from pages.models import * from django.test.client import Client class PagesTestCase(TestCase): fixtures = ['tests.json'] def test_01_add_page(self): """ Test that the add admin page could be displayed via the admin """ c = Client() c.login(username= 'batiste', password='b') response = c.get('/admin/pages/page/add/') assert(response.status_code == 200) def test_02_create_page(self): """ Test that a page can be created via the admin """ c = Client() c.login(username= 'batiste', password='b') page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1} response = c.post('/admin/pages/page/add/', page_data) self.assertRedirects(response, '/admin/pages/page/')
Add a create page test
Add a create page test git-svn-id: 54fea250f97f2a4e12c6f7a610b8f07cb4c107b4@300 439a9e5f-3f3e-0410-bc46-71226ad0111b
Python
bsd-3-clause
akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,remik/django-page-cms,batiste/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms
--- +++ @@ -1,4 +1,5 @@ from django.test import TestCase + from pages.models import * from django.test.client import Client @@ -7,10 +8,20 @@ def test_01_add_page(self): """ - Test that the add admin page could be displayed correctly + Test that the add admin page could be displayed via the admin """ c = Client() c.login(username= 'batiste', password='b') response = c.get('/admin/pages/page/add/') assert(response.status_code == 200) - + + + def test_02_create_page(self): + """ + Test that a page can be created via the admin + """ + c = Client() + c.login(username= 'batiste', password='b') + page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1} + response = c.post('/admin/pages/page/add/', page_data) + self.assertRedirects(response, '/admin/pages/page/')
ed71dc1e9163c5a7a7b0f623ea75393286804138
dbsettings/utils.py
dbsettings/utils.py
def set_defaults(app, *defaults): "Installs a set of default values during syncdb processing" from django.core.exceptions import ImproperlyConfigured from django.db.models import signals from dbsettings.loading import get_setting_storage, set_setting_value if not defaults: raise ImproperlyConfigured("No defaults were supplied to set_defaults.") app_label = app.__name__.split('.')[-2] def install_settings(app, created_models, verbosity=2, **kwargs): printed = False for class_name, attribute_name, value in defaults: if not get_setting_storage(app.__name__, class_name, attribute_name): if verbosity >= 2 and not printed: # Print this message only once, and only if applicable print "Installing default settings for %s" % app_label printed = True try: set_setting_value(app.__name__, class_name, attribute_name, value) except: raise ImproperlyConfigured("%s requires dbsettings." % app_label) signals.post_syncdb.connect(install_settings, sender=app)
def set_defaults(app, *defaults): "Installs a set of default values during syncdb processing" from django.core.exceptions import ImproperlyConfigured from django.db.models import signals from dbsettings.loading import get_setting_storage, set_setting_value if not defaults: raise ImproperlyConfigured("No defaults were supplied to set_defaults.") app_label = app.__name__.split('.')[-2] def install_settings(app, created_models, verbosity=2, **kwargs): printed = False for class_name, attribute_name, value in defaults: if not get_setting_storage(app.__name__, class_name, attribute_name): if verbosity >= 2 and not printed: # Print this message only once, and only if applicable print "Installing default settings for %s" % app_label printed = True try: set_setting_value(app.__name__, class_name, attribute_name, value) except: raise ImproperlyConfigured("%s requires dbsettings." % app_label) signals.post_syncdb.connect(install_settings, sender=app, weak=False)
Fix bug with registering local methods that got garbage collected due to django's weakref handling in signals.
Fix bug with registering local methods that got garbage collected due to django's weakref handling in signals.
Python
bsd-3-clause
johnpaulett/django-dbsettings,nwaxiomatic/django-dbsettings,MiriamSexton/django-dbsettings,DjangoAdminHackers/django-dbsettings,zlorf/django-dbsettings,nwaxiomatic/django-dbsettings,sciyoshi/django-dbsettings,helber/django-dbsettings,DjangoAdminHackers/django-dbsettings,helber/django-dbsettings,zlorf/django-dbsettings,winfieldco/django-dbsettings,sciyoshi/django-dbsettings,johnpaulett/django-dbsettings,winfieldco/django-dbsettings
--- +++ @@ -22,4 +22,4 @@ except: raise ImproperlyConfigured("%s requires dbsettings." % app_label) - signals.post_syncdb.connect(install_settings, sender=app) + signals.post_syncdb.connect(install_settings, sender=app, weak=False)
2bf5809b651bc85e922c853d2dab27d35fee85b8
test/bibliopixel/threads/sub_test.py
test/bibliopixel/threads/sub_test.py
import functools, time, unittest from bibliopixel.util.threads import sub WAIT_FOR_SUB = 0.1 def pause(delay=0.01): time.sleep(delay) def run(input, output, *arg, **kwds): pause() output.put('first') if arg != (1, 2, 3): raise ValueError('1 2 3') if kwds != dict(a=1): raise ValueError('a=1') pause() output.put('second') class SubTest(unittest.TestCase): def do_test(self, use_subprocess): s, input, output = sub.run( run, 1, 2, 3, a=1, use_subprocess=use_subprocess) self.assertTrue(s.is_alive()) self.assertEqual(output.get(), 'first') self.assertTrue(s.is_alive()) self.assertEqual(output.get(), 'second') pause(WAIT_FOR_SUB) self.assertFalse(s.is_alive()) def test_subprocess(self): self.do_test(True) def test_threading(self): self.do_test(False)
import functools, time, unittest from bibliopixel.util.threads import sub from .. import mark_tests WAIT_FOR_SUB = 0.1 def pause(delay=0.01): time.sleep(delay) def run(input, output, *arg, **kwds): pause() output.put('first') if arg != (1, 2, 3): raise ValueError('1 2 3') if kwds != dict(a=1): raise ValueError('a=1') pause() output.put('second') class SubTest(unittest.TestCase): def do_test(self, use_subprocess): s, input, output = sub.run( run, 1, 2, 3, a=1, use_subprocess=use_subprocess) self.assertTrue(s.is_alive()) self.assertEqual(output.get(), 'first') self.assertTrue(s.is_alive()) self.assertEqual(output.get(), 'second') pause(WAIT_FOR_SUB) self.assertFalse(s.is_alive()) @mark_tests.fails_on_windows def test_subprocess(self): self.do_test(True) def test_threading(self): self.do_test(False)
Disable one test in windows-only
Disable one test in windows-only
Python
mit
ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel
--- +++ @@ -1,5 +1,6 @@ import functools, time, unittest from bibliopixel.util.threads import sub +from .. import mark_tests WAIT_FOR_SUB = 0.1 @@ -34,6 +35,7 @@ pause(WAIT_FOR_SUB) self.assertFalse(s.is_alive()) + @mark_tests.fails_on_windows def test_subprocess(self): self.do_test(True)
77136f1c7dc6159a040c17cf5143bea14e9462b3
housing/listings/forms.py
housing/listings/forms.py
from django import forms from .models import Listing, HousingUser class ListingForm(forms.ModelForm): furnished_details = forms.CharField(widget=forms.Textarea(attrs={ "placeholder": "Example: bed and desk only"})) additional_lease_terms = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'form-control', "placeholder": "Example: Owner pays for trash, sewer, and water. Owner " "shovel snow, lawn, garden, driveway maintenance."})) lease_duration_custom = forms.CharField(max_length=128, required=False, widget=forms.TextInput(attrs={"placeholder": "Example: 6/9 - 8/9/2016"})) date_available = forms.DateField(widget=forms.TextInput(attrs={"type": "date"})) class Meta: model = Listing exclude = ("listing_owner", "is_active", "datetime_modified", "datetime_created") class HousingUserCreationForm(forms.ModelForm): class Meta: model = HousingUser fields = ("username", "password")
from django import forms from .models import Listing, HousingUser class ListingForm(forms.ModelForm): furnished_details = forms.CharField(required=False, widget=forms.Textarea(attrs={ "placeholder": "Example: bed and desk only"})) additional_lease_terms = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'form-control', "placeholder": "Example: Owner pays for trash, sewer, and water. Owner " "shovel snow, lawn, garden, driveway maintenance."})) lease_duration_custom = forms.CharField(max_length=128, required=False, widget=forms.TextInput(attrs={"placeholder": "Example: 6/9 - 8/9/2016"})) date_available = forms.DateField(widget=forms.TextInput(attrs={"type": "date"})) class Meta: model = Listing exclude = ("listing_owner", "is_active", "datetime_modified", "datetime_created") class HousingUserCreationForm(forms.ModelForm): class Meta: model = HousingUser fields = ("username", "password")
Update newListing no longer require furnishing detail
Update newListing no longer require furnishing detail
Python
mit
xyb994/housing,xyb994/housing,xyb994/housing,xyb994/housing
--- +++ @@ -2,7 +2,7 @@ from .models import Listing, HousingUser class ListingForm(forms.ModelForm): - furnished_details = forms.CharField(widget=forms.Textarea(attrs={ + furnished_details = forms.CharField(required=False, widget=forms.Textarea(attrs={ "placeholder": "Example: bed and desk only"})) additional_lease_terms = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'form-control',
a1bfb35bb5865cc45aded58b7cffab6da7cc0baf
pykeg/settings.py
pykeg/settings.py
# Pykeg main settings file. # Note: YOU SHOULD NOT NEED TO EDIT THIS FILE. Instead, see the instructions in # common_settings.py.example. INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.humanize', 'django.contrib.markup', 'pykeg.core', ) AUTH_PROFILE_MODULE = "core.UserProfile" try: import common_settings from common_settings import * except ImportError: print 'Error: Could not find common_settings.py' print 'Most likely, this means kegbot has not been configured properly.' print 'Consult setup documentation. Exiting...' import sys sys.exit(1)
# Pykeg main settings file. # Note: YOU SHOULD NOT NEED TO EDIT THIS FILE. Instead, see the instructions in # common_settings.py.example. INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.humanize', 'django.contrib.markup', 'pykeg.core', 'pykeg.contrib.twitter', ) AUTH_PROFILE_MODULE = "core.UserProfile" try: import common_settings from common_settings import * except ImportError: print 'Error: Could not find common_settings.py' print 'Most likely, this means kegbot has not been configured properly.' print 'Consult setup documentation. Exiting...' import sys sys.exit(1)
Add twitter to default apps.
Add twitter to default apps.
Python
mit
Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server
--- +++ @@ -11,6 +11,7 @@ 'django.contrib.humanize', 'django.contrib.markup', 'pykeg.core', + 'pykeg.contrib.twitter', ) AUTH_PROFILE_MODULE = "core.UserProfile"
509ca9c2cad65b47e1a2a16a0c169434620b8c74
mla_game/apps/transcript/management/commands/scrape_archive.py
mla_game/apps/transcript/management/commands/scrape_archive.py
import logging from django.core.management.base import BaseCommand from django.conf import settings from popuparchive.client import Client from ...models import Transcript from ...tasks import process_transcript logger = logging.getLogger('pua_scraper') class Command(BaseCommand): help = 'scrapes the popup archive poll for information' def handle(self, *args, **options): client = Client( settings.PUA_KEY, settings.PUA_SECRET, ) for collection in client.get_collections(): logger.info('collection id: ' + str(collection['id'])) for item_id in collection['item_ids']: logger.info('item id: ' + str(item_id)) item = client.get_item(collection['id'], item_id) process_transcript(item)
import logging from django.core.management.base import BaseCommand from django.conf import settings from popuparchive.client import Client from ...models import Transcript from ...tasks import process_transcript logger = logging.getLogger('pua_scraper') class Command(BaseCommand): help = 'scrapes the popup archive poll for information' def handle(self, *args, **options): client = Client( settings.PUA_KEY, settings.PUA_SECRET, ) for collection in client.get_collections(): logger.info('processing collection id: ' + str(collection['id'])) for item_id in collection['item_ids']: logger.info('processing item id: ' + str(item_id)) try: Transcript.objects.get(id_number=item_id) except Transcript.DoesNotExist: item = client.get_item(collection['id'], item_id) process_transcript(item)
Test for transcript before scraping from PUA
Test for transcript before scraping from PUA
Python
mit
WGBH/FixIt,WGBH/FixIt,WGBH/FixIt
--- +++ @@ -19,8 +19,11 @@ settings.PUA_SECRET, ) for collection in client.get_collections(): - logger.info('collection id: ' + str(collection['id'])) + logger.info('processing collection id: ' + str(collection['id'])) for item_id in collection['item_ids']: - logger.info('item id: ' + str(item_id)) - item = client.get_item(collection['id'], item_id) - process_transcript(item) + logger.info('processing item id: ' + str(item_id)) + try: + Transcript.objects.get(id_number=item_id) + except Transcript.DoesNotExist: + item = client.get_item(collection['id'], item_id) + process_transcript(item)
eeaa4251234cfbbefc8f24e7cba22d330d98eefc
cloudbaseinit/shell.py
cloudbaseinit/shell.py
# Copyright 2012 Cloudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import sys import pythoncom sys.coinit_flags = pythoncom.COINIT_MULTITHREADED pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) from oslo_config import cfg from oslo_log import log as oslo_logging from cloudbaseinit import init from cloudbaseinit.utils import log as logging CONF = cfg.CONF LOG = oslo_logging.getLogger(__name__) def main(): CONF(sys.argv[1:]) logging.setup('cloudbaseinit') try: init.InitManager().configure_host() except Exception as exc: LOG.exception(exc) raise if __name__ == "__main__": main()
# Copyright 2012 Cloudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import struct import sys if struct.calcsize("P") == 8 and sys.platform == 'win32': # This is needed by Nano Server. # Set COINIT_MULTITHREADED only on x64 interpreters due to issues on x86. import pythoncom sys.coinit_flags = pythoncom.COINIT_MULTITHREADED pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) from oslo_config import cfg from oslo_log import log as oslo_logging from cloudbaseinit import init from cloudbaseinit.utils import log as logging CONF = cfg.CONF LOG = oslo_logging.getLogger(__name__) def main(): CONF(sys.argv[1:]) logging.setup('cloudbaseinit') try: init.InitManager().configure_host() except Exception as exc: LOG.exception(exc) raise if __name__ == "__main__": main()
Make the multithreaded coinitialize only on 64bit
Make the multithreaded coinitialize only on 64bit Change-Id: I5d44efb634051f00cd3ca54b99ce0dea806543be
Python
apache-2.0
alexpilotti/cloudbase-init,ader1990/cloudbase-init,stefan-caraiman/cloudbase-init,cmin764/cloudbase-init,openstack/cloudbase-init,stackforge/cloudbase-init
--- +++ @@ -12,11 +12,15 @@ # License for the specific language governing permissions and limitations # under the License. +import struct import sys -import pythoncom -sys.coinit_flags = pythoncom.COINIT_MULTITHREADED -pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) +if struct.calcsize("P") == 8 and sys.platform == 'win32': + # This is needed by Nano Server. + # Set COINIT_MULTITHREADED only on x64 interpreters due to issues on x86. + import pythoncom + sys.coinit_flags = pythoncom.COINIT_MULTITHREADED + pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) from oslo_config import cfg from oslo_log import log as oslo_logging
56a76b9dc0745d22d9b1eac54348d6109dc3c0e1
src/funding/urls.py
src/funding/urls.py
# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.urls import path, include from . import views urlpatterns = [ path('', views.CurrentView.as_view(), name='funding_current'), path('teraz/', views.CurrentView.as_view()), path('teraz/<slug:slug>/', views.CurrentView.as_view(), name='funding_current'), path('lektura/', views.OfferListView.as_view(), name='funding'), path('lektura/<slug:slug>/', views.OfferDetailView.as_view(), name='funding_offer'), path('pozostale/', views.WLFundView.as_view(), name='funding_wlfund'), path('dziekujemy/', views.ThanksView.as_view(), name='funding_thanks'), path('niepowodzenie/', views.NoThanksView.as_view(), name='funding_nothanks'), path('wylacz_email/', views.DisableNotifications.as_view(), name='funding_disable_notifications'), path('getpaid/', include('getpaid.urls')), ]
# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.urls import path, include from annoy.utils import banner_exempt from . import views urlpatterns = [ path('', banner_exempt(views.CurrentView.as_view()), name='funding_current'), path('teraz/', banner_exempt(views.CurrentView.as_view())), path('teraz/<slug:slug>/', banner_exempt(views.CurrentView.as_view()), name='funding_current'), path('lektura/', banner_exempt(views.OfferListView.as_view()), name='funding'), path('lektura/<slug:slug>/', banner_exempt(views.OfferDetailView.as_view()), name='funding_offer'), path('pozostale/', banner_exempt(views.WLFundView.as_view()), name='funding_wlfund'), path('dziekujemy/', banner_exempt(views.ThanksView.as_view()), name='funding_thanks'), path('niepowodzenie/', banner_exempt(views.NoThanksView.as_view()), name='funding_nothanks'), path('wylacz_email/', banner_exempt(views.DisableNotifications.as_view()), name='funding_disable_notifications'), path('getpaid/', include('getpaid.urls')), ]
Disable banners on funding pages.
Disable banners on funding pages.
Python
agpl-3.0
fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury
--- +++ @@ -2,21 +2,22 @@ # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.urls import path, include +from annoy.utils import banner_exempt from . import views urlpatterns = [ - path('', views.CurrentView.as_view(), name='funding_current'), - path('teraz/', views.CurrentView.as_view()), - path('teraz/<slug:slug>/', views.CurrentView.as_view(), name='funding_current'), - path('lektura/', views.OfferListView.as_view(), name='funding'), - path('lektura/<slug:slug>/', views.OfferDetailView.as_view(), name='funding_offer'), - path('pozostale/', views.WLFundView.as_view(), name='funding_wlfund'), + path('', banner_exempt(views.CurrentView.as_view()), name='funding_current'), + path('teraz/', banner_exempt(views.CurrentView.as_view())), + path('teraz/<slug:slug>/', banner_exempt(views.CurrentView.as_view()), name='funding_current'), + path('lektura/', banner_exempt(views.OfferListView.as_view()), name='funding'), + path('lektura/<slug:slug>/', banner_exempt(views.OfferDetailView.as_view()), name='funding_offer'), + path('pozostale/', banner_exempt(views.WLFundView.as_view()), name='funding_wlfund'), - path('dziekujemy/', views.ThanksView.as_view(), name='funding_thanks'), - path('niepowodzenie/', views.NoThanksView.as_view(), name='funding_nothanks'), + path('dziekujemy/', banner_exempt(views.ThanksView.as_view()), name='funding_thanks'), + path('niepowodzenie/', banner_exempt(views.NoThanksView.as_view()), name='funding_nothanks'), - path('wylacz_email/', views.DisableNotifications.as_view(), name='funding_disable_notifications'), + path('wylacz_email/', banner_exempt(views.DisableNotifications.as_view()), name='funding_disable_notifications'), path('getpaid/', include('getpaid.urls')), ]
4927a1c29d258b1ab7c70ffecff6904b808480eb
bokeh/validation/warnings.py
bokeh/validation/warnings.py
''' Define standard warning codes and messages for Bokeh validation checks. 1000 : *MISSING_RENDERERS* A |Plot| object has no renderers configured (will result in a blank plot). 1001 : *NO_GLYPH_RENDERERS* A |Plot| object has no glyph renderers (will result in an empty plot frame). 1002 : *EMPTY_LAYOUT* A layout model has no children (will result in a blank layout). 9999 : *EXT* Indicates that a custom warning check has failed. ''' codes = { 1000: ("MISSING_RENDERERS", "Plot has no renderers"), 1001: ("NO_GLYPH_RENDERERS", "Plot has no glyph renderers"), 1002: ("EMPTY_LAYOUT", "Layout has no children"), 1003: ("COLON_IN_CATEGORY_LABEL", "Category label contains colons"), 9999: ("EXT", "Custom extension reports warning"), } for code in codes: exec("%s = %d" % (codes[code][0], code))
''' Define standard warning codes and messages for Bokeh validation checks. 1000 : *MISSING_RENDERERS* A |Plot| object has no renderers configured (will result in a blank plot). 1001 : *NO_GLYPH_RENDERERS* A |Plot| object has no glyph renderers (will result in an empty plot frame). 1002 : *EMPTY_LAYOUT* A layout model has no children (will result in a blank layout). 1003 : *COLON_IN_CATEGORY_LABEL* Category label contains colons (will result in a blank layout). 9999 : *EXT* Indicates that a custom warning check has failed. ''' codes = { 1000: ("MISSING_RENDERERS", "Plot has no renderers"), 1001: ("NO_GLYPH_RENDERERS", "Plot has no glyph renderers"), 1002: ("EMPTY_LAYOUT", "Layout has no children"), 1003: ("COLON_IN_CATEGORY_LABEL", "Category label contains colons"), 9999: ("EXT", "Custom extension reports warning"), } for code in codes: exec("%s = %d" % (codes[code][0], code))
Add module level documentation for colon warning
Add module level documentation for colon warning
Python
bsd-3-clause
ericmjl/bokeh,timsnyder/bokeh,draperjames/bokeh,philippjfr/bokeh,mindriot101/bokeh,aavanian/bokeh,aavanian/bokeh,phobson/bokeh,daodaoliang/bokeh,KasperPRasmussen/bokeh,rothnic/bokeh,dennisobrien/bokeh,phobson/bokeh,DuCorey/bokeh,timsnyder/bokeh,jplourenco/bokeh,ericdill/bokeh,srinathv/bokeh,bokeh/bokeh,srinathv/bokeh,justacec/bokeh,clairetang6/bokeh,DuCorey/bokeh,ChinaQuants/bokeh,paultcochrane/bokeh,deeplook/bokeh,mindriot101/bokeh,ericdill/bokeh,philippjfr/bokeh,dennisobrien/bokeh,KasperPRasmussen/bokeh,ericmjl/bokeh,htygithub/bokeh,khkaminska/bokeh,ptitjano/bokeh,saifrahmed/bokeh,ericmjl/bokeh,matbra/bokeh,schoolie/bokeh,justacec/bokeh,jakirkham/bokeh,saifrahmed/bokeh,rothnic/bokeh,aavanian/bokeh,aiguofer/bokeh,draperjames/bokeh,rs2/bokeh,clairetang6/bokeh,Karel-van-de-Plassche/bokeh,percyfal/bokeh,schoolie/bokeh,rothnic/bokeh,ericdill/bokeh,jakirkham/bokeh,azjps/bokeh,gpfreitas/bokeh,khkaminska/bokeh,srinathv/bokeh,evidation-health/bokeh,aavanian/bokeh,bokeh/bokeh,jakirkham/bokeh,jplourenco/bokeh,daodaoliang/bokeh,stonebig/bokeh,mindriot101/bokeh,deeplook/bokeh,tacaswell/bokeh,Karel-van-de-Plassche/bokeh,schoolie/bokeh,aiguofer/bokeh,timsnyder/bokeh,ChinaQuants/bokeh,ptitjano/bokeh,Karel-van-de-Plassche/bokeh,schoolie/bokeh,evidation-health/bokeh,percyfal/bokeh,khkaminska/bokeh,stonebig/bokeh,matbra/bokeh,quasiben/bokeh,muku42/bokeh,xguse/bokeh,percyfal/bokeh,phobson/bokeh,muku42/bokeh,mindriot101/bokeh,timsnyder/bokeh,quasiben/bokeh,ptitjano/bokeh,philippjfr/bokeh,DuCorey/bokeh,rs2/bokeh,ptitjano/bokeh,paultcochrane/bokeh,philippjfr/bokeh,schoolie/bokeh,azjps/bokeh,KasperPRasmussen/bokeh,ChinaQuants/bokeh,maxalbert/bokeh,xguse/bokeh,Karel-van-de-Plassche/bokeh,muku42/bokeh,dennisobrien/bokeh,muku42/bokeh,tacaswell/bokeh,matbra/bokeh,gpfreitas/bokeh,paultcochrane/bokeh,Karel-van-de-Plassche/bokeh,bokeh/bokeh,ericmjl/bokeh,jakirkham/bokeh,rs2/bokeh,timsnyder/bokeh,msarahan/bokeh,azjps/bokeh,evidation-health/bokeh,htygithub/bokeh,ChinaQuants/bokeh,htygithub/bokeh,ericdill/bokeh,draperjames/bokeh,maxalbert/bokeh,percyfal/bokeh,rs2/bokeh,phobson/bokeh,bokeh/bokeh,phobson/bokeh,xguse/bokeh,gpfreitas/bokeh,maxalbert/bokeh,daodaoliang/bokeh,quasiben/bokeh,evidation-health/bokeh,deeplook/bokeh,khkaminska/bokeh,jplourenco/bokeh,percyfal/bokeh,msarahan/bokeh,stonebig/bokeh,paultcochrane/bokeh,htygithub/bokeh,maxalbert/bokeh,matbra/bokeh,msarahan/bokeh,srinathv/bokeh,DuCorey/bokeh,saifrahmed/bokeh,ptitjano/bokeh,dennisobrien/bokeh,jplourenco/bokeh,daodaoliang/bokeh,DuCorey/bokeh,dennisobrien/bokeh,gpfreitas/bokeh,stonebig/bokeh,philippjfr/bokeh,tacaswell/bokeh,justacec/bokeh,jakirkham/bokeh,draperjames/bokeh,KasperPRasmussen/bokeh,msarahan/bokeh,justacec/bokeh,clairetang6/bokeh,tacaswell/bokeh,xguse/bokeh,azjps/bokeh,draperjames/bokeh,rs2/bokeh,KasperPRasmussen/bokeh,bokeh/bokeh,clairetang6/bokeh,aiguofer/bokeh,aiguofer/bokeh,azjps/bokeh,ericmjl/bokeh,deeplook/bokeh,aiguofer/bokeh,rothnic/bokeh,aavanian/bokeh,saifrahmed/bokeh
--- +++ @@ -9,17 +9,20 @@ 1002 : *EMPTY_LAYOUT* A layout model has no children (will result in a blank layout). +1003 : *COLON_IN_CATEGORY_LABEL* + Category label contains colons (will result in a blank layout). + 9999 : *EXT* Indicates that a custom warning check has failed. ''' codes = { - 1000: ("MISSING_RENDERERS", "Plot has no renderers"), - 1001: ("NO_GLYPH_RENDERERS", "Plot has no glyph renderers"), - 1002: ("EMPTY_LAYOUT", "Layout has no children"), - 1003: ("COLON_IN_CATEGORY_LABEL", "Category label contains colons"), - 9999: ("EXT", "Custom extension reports warning"), + 1000: ("MISSING_RENDERERS", "Plot has no renderers"), + 1001: ("NO_GLYPH_RENDERERS", "Plot has no glyph renderers"), + 1002: ("EMPTY_LAYOUT", "Layout has no children"), + 1003: ("COLON_IN_CATEGORY_LABEL", "Category label contains colons"), + 9999: ("EXT", "Custom extension reports warning"), } for code in codes:
d8a46686f12de76381bf9c2cfde0e9482acc2259
Toolkit/PlayPen/rooster.py
Toolkit/PlayPen/rooster.py
import os import sys import math def main(): # do while len(spot.xds) > 100 (say) # index, no unit cell / symmetry set # copy out indexed spots, orientation matrix # done # compare list of orientation matrices - how are they related? # graphical representation?
import os import sys import math import shutil def split_spot_file(j): '''Split the spot file into those which have been indexed (goes to SPOT.j) and those which have not, which gets returned to SPOT.XDS. Returns number of unindexed reflections.''' spot_j = open('SPOT.%d' % j, 'w') spot_0 = open('SPOT.0', 'w') spot = open('SPOT.XDS', 'r') n_j = 0 n_0 = 0 for record in spot: if ' 0 0 0' in record: spot_0.write(record) n_0 += 1 else: spot_j.write(record) n_j += 1 spot_j.close() spot_0.close() spot.close() shutil.move('SPOT.0', 'SPOT.XDS') return n_0, n_j def prepare_xds_inp(): xds_inp = open('XDS.0', 'w') for record in open('XDS.INP'): if 'SPACE_GROUP_NUMBER' in record: continue if 'UNIT_CELL_CONSTANTS' in record: continue xds_inp.write(record) xds_inp.close() shutil.move('XDS.0', 'XDS.INP') return def run_xds(j): os.system('xds_par > /dev/null') shutil.copyfile('IDXREF.LP', 'IDXREF.%d' % j) shutil.copyfile('XPARM.XDS', 'XPARM.%d' % j) n_unindexed, n_indexed = split_spot_file(j) return n_unindexed, n_indexed def get_unit_cell(): unit_cell = map(float, open('XPARM.XDS', 'r').read().split()[27:33]) return tuple(unit_cell) def num_spots(): j = 0 for record in open('SPOT.XDS', 'r'): if record.strip(): j += 1 return j def main(): prepare_xds_inp() n_unindexed = num_spots() j = 0 while n_unindexed > 100: j += 1 n_unindexed, n_indexed = run_xds(j) if n_indexed == 0: break unit_cell = get_unit_cell() print '%5d %5d' % (n_indexed, n_unindexed), \ '%6.2f %6.2f %6.2f %6.2f %6.2f %6.2f' % unit_cell if __name__ == '__main__': main()
Make a start on the recursive reindexing
Make a start on the recursive reindexing
Python
bsd-3-clause
xia2/xia2,xia2/xia2
--- +++ @@ -1,13 +1,95 @@ import os import sys import math +import shutil + +def split_spot_file(j): + '''Split the spot file into those which have been indexed (goes to SPOT.j) + and those which have not, which gets returned to SPOT.XDS. Returns number + of unindexed reflections.''' + + spot_j = open('SPOT.%d' % j, 'w') + spot_0 = open('SPOT.0', 'w') + spot = open('SPOT.XDS', 'r') + + n_j = 0 + n_0 = 0 + + for record in spot: + if ' 0 0 0' in record: + spot_0.write(record) + n_0 += 1 + else: + spot_j.write(record) + n_j += 1 + + spot_j.close() + spot_0.close() + spot.close() + + shutil.move('SPOT.0', 'SPOT.XDS') + + return n_0, n_j + +def prepare_xds_inp(): + + xds_inp = open('XDS.0', 'w') + + for record in open('XDS.INP'): + if 'SPACE_GROUP_NUMBER' in record: + continue + if 'UNIT_CELL_CONSTANTS' in record: + continue + xds_inp.write(record) + + xds_inp.close() + + shutil.move('XDS.0', 'XDS.INP') + + return + +def run_xds(j): + + os.system('xds_par > /dev/null') + + shutil.copyfile('IDXREF.LP', 'IDXREF.%d' % j) + shutil.copyfile('XPARM.XDS', 'XPARM.%d' % j) + + n_unindexed, n_indexed = split_spot_file(j) + + return n_unindexed, n_indexed + +def get_unit_cell(): + unit_cell = map(float, open('XPARM.XDS', 'r').read().split()[27:33]) + return tuple(unit_cell) + +def num_spots(): + j = 0 + + for record in open('SPOT.XDS', 'r'): + if record.strip(): + j += 1 + + return j def main(): - # do while len(spot.xds) > 100 (say) - # index, no unit cell / symmetry set - # copy out indexed spots, orientation matrix - # done + prepare_xds_inp() - # compare list of orientation matrices - how are they related? - # graphical representation? + n_unindexed = num_spots() + + j = 0 + + while n_unindexed > 100: + j += 1 + n_unindexed, n_indexed = run_xds(j) + if n_indexed == 0: + break + unit_cell = get_unit_cell() + print '%5d %5d' % (n_indexed, n_unindexed), \ + '%6.2f %6.2f %6.2f %6.2f %6.2f %6.2f' % unit_cell + + + +if __name__ == '__main__': + main()
2e1d1e5914d853a4da55dd0c8ea534df396697a0
coop_cms/forms/__init__.py
coop_cms/forms/__init__.py
# -*- coding: utf-8 -*- # This can be imported directly from coop_cms.forms from coop_cms.forms.articles import ArticleForm, ArticleSettingsForm, NewArticleForm from coop_cms.forms.newsletters import NewsletterForm, NewsletterSettingsForm __all__ = ['ArticleForm', 'ArticleSettingsForm', 'NewArticleForm', 'NewsletterForm', 'NewsletterSettingsForm']
# -*- coding: utf-8 -*- # This can be imported directly from coop_cms.forms from coop_cms.forms.articles import ( ArticleForm, ArticleAdminForm, ArticleSettingsForm, NewArticleForm, BaseArticleAdminForm ) from coop_cms.forms.newsletters import NewsletterForm, NewsletterSettingsForm __all__ = [ 'ArticleForm', 'ArticleAdminForm', 'ArticleSettingsForm', 'BaseArticleAdminForm', 'NewArticleForm', 'NewsletterForm', 'NewsletterSettingsForm' ]
Add more forms to the publics
Add more forms to the publics
Python
bsd-3-clause
ljean/coop_cms,ljean/coop_cms,ljean/coop_cms
--- +++ @@ -1,7 +1,12 @@ # -*- coding: utf-8 -*- # This can be imported directly from coop_cms.forms -from coop_cms.forms.articles import ArticleForm, ArticleSettingsForm, NewArticleForm +from coop_cms.forms.articles import ( + ArticleForm, ArticleAdminForm, ArticleSettingsForm, NewArticleForm, BaseArticleAdminForm +) from coop_cms.forms.newsletters import NewsletterForm, NewsletterSettingsForm -__all__ = ['ArticleForm', 'ArticleSettingsForm', 'NewArticleForm', 'NewsletterForm', 'NewsletterSettingsForm'] +__all__ = [ + 'ArticleForm', 'ArticleAdminForm', 'ArticleSettingsForm', 'BaseArticleAdminForm', 'NewArticleForm', + 'NewsletterForm', 'NewsletterSettingsForm' +]
e3ae701be163ccff7e2f64721752b0374dffdfc1
rosie/chamber_of_deputies/tests/test_dataset.py
rosie/chamber_of_deputies/tests/test_dataset.py
import os.path from tempfile import mkdtemp from unittest import TestCase from unittest.mock import patch from shutil import copy2 from rosie.chamber_of_deputies import settings from rosie.chamber_of_deputies.adapter import Adapter class TestDataset(TestCase): def setUp(self): temp_path = mkdtemp() copy2('rosie/chamber_of_deputies/tests/fixtures/companies.xz', os.path.join(temp_path, settings.COMPANIES_DATASET)) copy2('rosie/chamber_of_deputies/tests/fixtures/reimbursements.xz', temp_path) self.subject = Adapter(temp_path) @patch('rosie.chamber_of_deputies.adapter.CEAPDataset') @patch('rosie.chamber_of_deputies.adapter.fetch') def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, _ceap_dataset, _fetch): dataset = self.subject.dataset() self.assertEqual(5, len(dataset)) self.assertEqual(1, dataset['legal_entity'].isnull().sum())
import shutil import os from tempfile import mkdtemp from unittest import TestCase from unittest.mock import patch from shutil import copy2 from rosie.chamber_of_deputies.adapter import Adapter class TestDataset(TestCase): def setUp(self): self.temp_path = mkdtemp() fixtures = os.path.join('rosie', 'chamber_of_deputies', 'tests', 'fixtures') copies = ( ('companies.xz', Adapter.COMPANIES_DATASET), ('reimbursements.xz', 'reimbursements.xz') ) for source, target in copies: copy2(os.path.join(fixtures, source), os.path.join(self.temp_path, target)) self.subject = Adapter(self.temp_path) def tearDown(self): shutil.rmtree(self.temp_path) @patch('rosie.chamber_of_deputies.adapter.CEAPDataset') @patch('rosie.chamber_of_deputies.adapter.fetch') def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, fetch, ceap): self.assertEqual(5, len(self.subject.dataset)) self.assertEqual(1, self.subject.dataset['legal_entity'].isnull().sum())
Fix companies path in Chamber of Deputies dataset test
Fix companies path in Chamber of Deputies dataset test
Python
mit
marcusrehm/serenata-de-amor,datasciencebr/rosie,marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor,datasciencebr/serenata-de-amor,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor
--- +++ @@ -1,25 +1,31 @@ -import os.path +import shutil +import os from tempfile import mkdtemp from unittest import TestCase from unittest.mock import patch from shutil import copy2 -from rosie.chamber_of_deputies import settings from rosie.chamber_of_deputies.adapter import Adapter class TestDataset(TestCase): def setUp(self): - temp_path = mkdtemp() - copy2('rosie/chamber_of_deputies/tests/fixtures/companies.xz', - os.path.join(temp_path, settings.COMPANIES_DATASET)) - copy2('rosie/chamber_of_deputies/tests/fixtures/reimbursements.xz', temp_path) - self.subject = Adapter(temp_path) + self.temp_path = mkdtemp() + fixtures = os.path.join('rosie', 'chamber_of_deputies', 'tests', 'fixtures') + copies = ( + ('companies.xz', Adapter.COMPANIES_DATASET), + ('reimbursements.xz', 'reimbursements.xz') + ) + for source, target in copies: + copy2(os.path.join(fixtures, source), os.path.join(self.temp_path, target)) + self.subject = Adapter(self.temp_path) + + def tearDown(self): + shutil.rmtree(self.temp_path) @patch('rosie.chamber_of_deputies.adapter.CEAPDataset') @patch('rosie.chamber_of_deputies.adapter.fetch') - def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, _ceap_dataset, _fetch): - dataset = self.subject.dataset() - self.assertEqual(5, len(dataset)) - self.assertEqual(1, dataset['legal_entity'].isnull().sum()) + def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, fetch, ceap): + self.assertEqual(5, len(self.subject.dataset)) + self.assertEqual(1, self.subject.dataset['legal_entity'].isnull().sum())
cf60277951c7c4a23fe8672f5c21ed2ee8a7a0ee
birdseye/ipython.py
birdseye/ipython.py
import inspect import socket import sys from io import BytesIO from threading import currentThread, Thread from IPython.core.display import HTML, display from werkzeug.local import LocalProxy from werkzeug.serving import ThreadingMixIn from birdseye import server, eye thread_proxies = {} def stream_proxy(original): def p(): frame = inspect.currentframe() while frame: if frame.f_code == ThreadingMixIn.process_request_thread.__code__: return BytesIO() frame = frame.f_back return thread_proxies.get(currentThread().ident, original) return LocalProxy(p) sys.stderr = stream_proxy(sys.stderr) sys.stdout = stream_proxy(sys.stdout) def run_server(): thread_proxies[currentThread().ident] = BytesIO() try: server.main([]) except socket.error: pass def cell_magic(_line, cell): Thread(target=run_server).start() call_id = eye.exec_ipython_cell(cell) html = HTML('<iframe ' ' src="http://localhost:7777/ipython_call/%s"' % call_id + ' style="width: 100%"' ' height="500"' '/>') # noinspection PyTypeChecker display(html)
import inspect import socket import sys from io import BytesIO, StringIO from threading import currentThread, Thread from IPython.core.display import HTML, display from werkzeug.local import LocalProxy from werkzeug.serving import ThreadingMixIn from birdseye import eye, PY2 from birdseye.server import app fake_stream = BytesIO if PY2 else StringIO thread_proxies = {} def stream_proxy(original): def p(): frame = inspect.currentframe() while frame: if frame.f_code == ThreadingMixIn.process_request_thread.__code__: return fake_stream() frame = frame.f_back return thread_proxies.get(currentThread().ident, original) return LocalProxy(p) sys.stderr = stream_proxy(sys.stderr) sys.stdout = stream_proxy(sys.stdout) def run_server(): thread_proxies[currentThread().ident] = fake_stream() try: app.run( debug=True, port=7777, host='127.0.0.1', use_reloader=False, ) except socket.error: pass def cell_magic(_line, cell): Thread(target=run_server).start() call_id = eye.exec_ipython_cell(cell) html = HTML('<iframe ' ' src="http://localhost:7777/ipython_call/%s"' % call_id + ' style="width: 100%"' ' height="500"' '/>') # noinspection PyTypeChecker display(html)
Make stream redirection py3 compatible. Ensure flask reloader is off inside notebook
Make stream redirection py3 compatible. Ensure flask reloader is off inside notebook
Python
mit
alexmojaki/birdseye,alexmojaki/birdseye,alexmojaki/birdseye,alexmojaki/birdseye
--- +++ @@ -1,14 +1,17 @@ import inspect import socket import sys -from io import BytesIO +from io import BytesIO, StringIO from threading import currentThread, Thread from IPython.core.display import HTML, display from werkzeug.local import LocalProxy from werkzeug.serving import ThreadingMixIn -from birdseye import server, eye +from birdseye import eye, PY2 +from birdseye.server import app + +fake_stream = BytesIO if PY2 else StringIO thread_proxies = {} @@ -18,7 +21,7 @@ frame = inspect.currentframe() while frame: if frame.f_code == ThreadingMixIn.process_request_thread.__code__: - return BytesIO() + return fake_stream() frame = frame.f_back return thread_proxies.get(currentThread().ident, original) @@ -31,9 +34,14 @@ def run_server(): - thread_proxies[currentThread().ident] = BytesIO() + thread_proxies[currentThread().ident] = fake_stream() try: - server.main([]) + app.run( + debug=True, + port=7777, + host='127.0.0.1', + use_reloader=False, + ) except socket.error: pass
8aeee881bb32935718e767114256179f9c9bf216
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_drf_views.py
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_drf_views.py
import pytest from django.test import RequestFactory from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet from {{ cookiecutter.project_slug }}.users.models import User pytestmark = pytest.mark.django_db class TestUserViewSet: def test_get_queryset(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request assert user in view.get_queryset() def test_me(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request response = view.me(request) assert response.data == { "username": user.username, "email": user.email, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", }
import pytest from django.test import RequestFactory from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet from {{ cookiecutter.project_slug }}.users.models import User pytestmark = pytest.mark.django_db class TestUserViewSet: def test_get_queryset(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request assert user in view.get_queryset() def test_me(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request response = view.me(request) assert response.data == { "username": user.username, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", }
Remove email from User API Test
Remove email from User API Test
Python
bsd-3-clause
ryankanno/cookiecutter-django,ryankanno/cookiecutter-django,pydanny/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,pydanny/cookiecutter-django,pydanny/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,trungdong/cookiecutter-django
--- +++ @@ -28,7 +28,6 @@ assert response.data == { "username": user.username, - "email": user.email, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", }
8f3fb41b8001c3f2dffc6086e89e782a9a46f79a
draftjs_exporter/constants.py
draftjs_exporter/constants.py
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, tuple_list): self.tuple_list = tuple_list def __getattr__(self, name): return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum(('LINK', 'IMAGE', 'TOKEN')) INLINE_STYLES = Enum(('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE'))
from __future__ import absolute_import, unicode_literals # http://stackoverflow.com/a/22723724/1798491 class Enum(object): def __init__(self, tuple_list): self.tuple_list = tuple_list def __getattr__(self, name): if name not in self.tuple_list: raise AttributeError("'Enum' has no attribute '{}'".format(name)) return name # https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js class BLOCK_TYPES: UNSTYLED = 'unstyled' HEADER_ONE = 'header-one' HEADER_TWO = 'header-two' HEADER_THREE = 'header-three' HEADER_FOUR = 'header-four' HEADER_FIVE = 'header-five' HEADER_SIX = 'header-six' UNORDERED_LIST_ITEM = 'unordered-list-item' ORDERED_LIST_ITEM = 'ordered-list-item' BLOCKQUOTE = 'blockquote' PULLQUOTE = 'pullquote' CODE = 'code-block' ATOMIC = 'atomic' HORIZONTAL_RULE = 'horizontal-rule' ENTITY_TYPES = Enum(('LINK', 'IMAGE', 'TOKEN')) INLINE_STYLES = Enum(('BOLD', 'CODE', 'ITALIC', 'STRIKETHROUGH', 'UNDERLINE'))
Fix Enum returning invalid elements
Fix Enum returning invalid elements
Python
mit
springload/draftjs_exporter,springload/draftjs_exporter,springload/draftjs_exporter
--- +++ @@ -7,6 +7,9 @@ self.tuple_list = tuple_list def __getattr__(self, name): + if name not in self.tuple_list: + raise AttributeError("'Enum' has no attribute '{}'".format(name)) + return name
3350ace16ec8148b861985d59a399470655b4421
cube_viewer/glue_viewer.py
cube_viewer/glue_viewer.py
import numpy as np from glue.qt.widgets.data_viewer import DataViewer from .options_widget import IsosurfaceOptionsWidget from .vtk_widget import QtVTKWidget class GlueVTKViewer(DataViewer): LABEL = "VTK Isosurfaces" def __init__(self, session, parent=None): super(GlueVTKViewer, self).__init__(session, parent=parent) self._vtk_widget = QtVTKWidget() self.setCentralWidget(self._vtk_widget) self._options_widget = IsosurfaceOptionsWidget(vtk_widget=self._vtk_widget) def add_data(self, data): self._vtk_widget.set_data(data['PRIMARY']) initial_level = "{0:.3g}".format(np.percentile(data['PRIMARY'], 99)) self._options_widget.levels = initial_level self._options_widget.update_viewer() return True def options_widget(self): return self._options_widget
import numpy as np from glue.qt.widgets.data_viewer import DataViewer from .options_widget import IsosurfaceOptionsWidget from .vtk_widget import QtVTKWidget class GlueVTKViewer(DataViewer): LABEL = "VTK Isosurfaces" def __init__(self, session, parent=None): super(GlueVTKViewer, self).__init__(session, parent=parent) self._vtk_widget = QtVTKWidget() self.setCentralWidget(self._vtk_widget) self._options_widget = IsosurfaceOptionsWidget(vtk_widget=self._vtk_widget) def add_data(self, data): self._vtk_widget.set_data(data['PRIMARY']) initial_level = "{0:.3g}".format(np.nanpercentile(data['PRIMARY'], 99)) self._options_widget.levels = initial_level self._options_widget.update_viewer() return True def options_widget(self): return self._options_widget
Use nanpercentile instead of percentile
Use nanpercentile instead of percentile
Python
bsd-2-clause
astrofrog/cube-viewer
--- +++ @@ -17,7 +17,7 @@ def add_data(self, data): self._vtk_widget.set_data(data['PRIMARY']) - initial_level = "{0:.3g}".format(np.percentile(data['PRIMARY'], 99)) + initial_level = "{0:.3g}".format(np.nanpercentile(data['PRIMARY'], 99)) self._options_widget.levels = initial_level self._options_widget.update_viewer() return True
d0a16cb7d0b4a3a04a0461df455697fd65302c9b
accelerator/migrations/0110_remove_bucket_list_program_role_20220707_1001.py
accelerator/migrations/0110_remove_bucket_list_program_role_20220707_1001.py
from django.db import migrations def remove_bucket_list_program_roles(apps, schema_editor): BucketState = apps.get_model('accelerator', 'BucketState') ProgramRole = apps.get_model('accelerator', 'ProgramRole') ProgramRoleGrant = apps.get_model('accelerator', 'ProgramRoleGrant') NodePublishedFor = apps.get_model('accelerator', 'NodePublishedFor') program_role_ids = BucketState.objects.values_list('program_role_id', flat=True) NodePublishedFor.objects.filter( published_for_id__in=program_role_ids).delete() ProgramRoleGrant.objects.filter( program_role_id__in=program_role_ids).delete() BucketState.objects.all().delete() ProgramRole.objects.filter(pk__in=program_role_ids).delete() class Migration(migrations.Migration): dependencies = [ ('accelerator', '0109_remove_interest_fields_20220705_0425'), ] operations = [ migrations.RunPython(remove_bucket_list_program_roles, migrations.RunPython.noop) ]
from django.db import migrations def remove_bucket_list_program_roles(apps, schema_editor): BucketState = apps.get_model('accelerator', 'BucketState') ProgramRole = apps.get_model('accelerator', 'ProgramRole') ProgramRoleGrant = apps.get_model('accelerator', 'ProgramRoleGrant') NodePublishedFor = apps.get_model('accelerator', 'NodePublishedFor') program_role_ids = BucketState.objects.values_list('program_role_id', flat=True) NodePublishedFor.objects.filter( published_for_id__in=program_role_ids).delete() ProgramRoleGrant.objects.filter( program_role_id__in=program_role_ids).delete() BucketState.objects.all().delete() ProgramRole.objects.filter(pk__in=program_role_ids).delete() class Migration(migrations.Migration): dependencies = [ ('accelerator', '0109_remove_interest_fields_20220705_0425'), ] operations = [ migrations.RunPython(remove_bucket_list_program_roles, migrations.RunPython.noop) ]
Remove program role from bucket list
[AC-9556]: Remove program role from bucket list
Python
mit
masschallenge/django-accelerator,masschallenge/django-accelerator
--- +++ @@ -8,7 +8,7 @@ NodePublishedFor = apps.get_model('accelerator', 'NodePublishedFor') program_role_ids = BucketState.objects.values_list('program_role_id', - flat=True) + flat=True) NodePublishedFor.objects.filter( published_for_id__in=program_role_ids).delete() ProgramRoleGrant.objects.filter(
87079b55d17edc4cc8bbcb2a7af80adf5799608e
swingtime/urls.py
swingtime/urls.py
from django.conf.urls import patterns, url from swingtime import views urlpatterns = patterns('', url( r'^(?:calendar/)?$', views.today_view, name='swingtime-today' ), url( r'^calendar/(?P<year>\d{4})/$', views.year_view, name='swingtime-yearly-view' ), url( r'^calendar/(\d{4})/(0?[1-9]|1[012])/$', views.month_view, name='swingtime-monthly-view' ), url( r'^calendar/(\d{4})/(0?[1-9]|1[012])/([0-3]?\d)/$', views.day_view, name='swingtime-daily-view' ), url( r'^events/$', views.event_listing, name='swingtime-events' ), url( r'^events/add/$', views.add_event, name='swingtime-add-event' ), url( r'^events/(\d+)/$', views.event_view, name='swingtime-event' ), url( r'^events/(\d+)/(\d+)/$', views.occurrence_view, name='swingtime-occurrence' ), )
from django.conf.urls import patterns, url from swingtime import views urlpatterns = patterns('', url( r'^(?:calendar/)?$', views.today_view, name='swingtime-today' ), url( r'^calendar/json/$', views.CalendarJSONView.as_view(), name='swingtime-calendar-json' ), url( r'^calendar/(?P<year>\d{4})/$', views.year_view, name='swingtime-yearly-view' ), url( r'^calendar/(\d{4})/(0?[1-9]|1[012])/$', views.month_view, name='swingtime-monthly-view' ), url( r'^calendar/(\d{4})/(0?[1-9]|1[012])/([0-3]?\d)/$', views.day_view, name='swingtime-daily-view' ), url( r'^events/$', views.event_listing, name='swingtime-events' ), url( r'^events/add/$', views.add_event, name='swingtime-add-event' ), url( r'^events/(\d+)/$', views.event_view, name='swingtime-event' ), url( r'^events/(\d+)/(\d+)/$', views.occurrence_view, name='swingtime-occurrence' ), )
Remove whitespace, and also add JSON url
Remove whitespace, and also add JSON url
Python
mit
jonge-democraten/mezzanine-fullcalendar
--- +++ @@ -3,26 +3,32 @@ urlpatterns = patterns('', url( - r'^(?:calendar/)?$', - views.today_view, + r'^(?:calendar/)?$', + views.today_view, name='swingtime-today' ), url( - r'^calendar/(?P<year>\d{4})/$', - views.year_view, + r'^calendar/json/$', + views.CalendarJSONView.as_view(), + name='swingtime-calendar-json' + ), + + url( + r'^calendar/(?P<year>\d{4})/$', + views.year_view, name='swingtime-yearly-view' ), url( - r'^calendar/(\d{4})/(0?[1-9]|1[012])/$', - views.month_view, + r'^calendar/(\d{4})/(0?[1-9]|1[012])/$', + views.month_view, name='swingtime-monthly-view' ), url( - r'^calendar/(\d{4})/(0?[1-9]|1[012])/([0-3]?\d)/$', - views.day_view, + r'^calendar/(\d{4})/(0?[1-9]|1[012])/([0-3]?\d)/$', + views.day_view, name='swingtime-daily-view' ), @@ -31,22 +37,22 @@ views.event_listing, name='swingtime-events' ), - + url( - r'^events/add/$', - views.add_event, + r'^events/add/$', + views.add_event, name='swingtime-add-event' ), - + url( - r'^events/(\d+)/$', - views.event_view, + r'^events/(\d+)/$', + views.event_view, name='swingtime-event' ), - + url( - r'^events/(\d+)/(\d+)/$', - views.occurrence_view, + r'^events/(\d+)/(\d+)/$', + views.occurrence_view, name='swingtime-occurrence' ), )
e264d00fa37dd1b326f1296badd74fa4ab599a45
project/runner.py
project/runner.py
from subprocess import Popen, PIPE from django.test.runner import DiscoverRunner class CustomTestRunner(DiscoverRunner): """ Same as the default Django test runner, except it also runs our node server as a subprocess so we can render React components. """ def setup_test_environment(self, **kwargs): # Start the node server self.node_server = Popen(['node', 'react-server.js'], stdout=PIPE) # Wait until the server is ready before proceeding _ = self.node_server.stdout.readline() super(CustomTestRunner, self).setup_test_environment(**kwargs) def teardown_test_environment(self, **kwargs): # Kill the node server self.node_server.terminate() super(CustomTestRunner, self).teardown_test_environment(**kwargs)
from subprocess import Popen, PIPE from django.test.runner import DiscoverRunner from django.conf import settings from react.render_server import render_server TEST_REACT_SERVER_HOST = getattr(settings, 'TEST_REACT_SERVER_HOST', '127.0.0.1') TEST_REACT_SERVER_PORT = getattr(settings, 'TEST_REACT_SERVER_PORT', 9008) class CustomTestRunner(DiscoverRunner): """ Same as the default Django test runner, except it also runs our node server as a subprocess so we can render React components. """ def setup_test_environment(self, **kwargs): # Start the test node server self.node_server = Popen( [ 'node', 'react-server.js', '--host=%s' % TEST_REACT_SERVER_HOST, '--port=%s' % TEST_REACT_SERVER_PORT ], stdout=PIPE ) # Wait until the server is ready before proceeding self.node_server.stdout.readline() # Point the renderer to our new test server render_server.url = 'http://%s:%s' % ( TEST_REACT_SERVER_HOST, TEST_REACT_SERVER_PORT) super(CustomTestRunner, self).setup_test_environment(**kwargs) def teardown_test_environment(self, **kwargs): # Kill the node server self.node_server.terminate() super(CustomTestRunner, self).teardown_test_environment(**kwargs)
Use separate node server when running the tests
Use separate node server when running the tests
Python
mit
jphalip/django-react-djangocon2015,jphalip/django-react-djangocon2015,jphalip/django-react-djangocon2015
--- +++ @@ -1,5 +1,11 @@ from subprocess import Popen, PIPE from django.test.runner import DiscoverRunner +from django.conf import settings +from react.render_server import render_server + + +TEST_REACT_SERVER_HOST = getattr(settings, 'TEST_REACT_SERVER_HOST', '127.0.0.1') +TEST_REACT_SERVER_PORT = getattr(settings, 'TEST_REACT_SERVER_PORT', 9008) class CustomTestRunner(DiscoverRunner): @@ -9,10 +15,21 @@ """ def setup_test_environment(self, **kwargs): - # Start the node server - self.node_server = Popen(['node', 'react-server.js'], stdout=PIPE) + # Start the test node server + self.node_server = Popen( + [ + 'node', + 'react-server.js', + '--host=%s' % TEST_REACT_SERVER_HOST, + '--port=%s' % TEST_REACT_SERVER_PORT + ], + stdout=PIPE + ) # Wait until the server is ready before proceeding - _ = self.node_server.stdout.readline() + self.node_server.stdout.readline() + # Point the renderer to our new test server + render_server.url = 'http://%s:%s' % ( + TEST_REACT_SERVER_HOST, TEST_REACT_SERVER_PORT) super(CustomTestRunner, self).setup_test_environment(**kwargs) def teardown_test_environment(self, **kwargs):
bd49d3ab611a8715436987cf549097ed9cbc2a5d
dsub/_dsub_version.py
dsub/_dsub_version.py
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.3.5'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.3.6.dev0'
Update dsub version to 0.3.6.dev0
Update dsub version to 0.3.6.dev0 PiperOrigin-RevId: 276310514
Python
apache-2.0
DataBiosphere/dsub,DataBiosphere/dsub
--- +++ @@ -26,4 +26,4 @@ 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ -DSUB_VERSION = '0.3.5' +DSUB_VERSION = '0.3.6.dev0'
84fa71e639bc1b6fda246ddfd321f0f777b86216
tasks/__init__.py
tasks/__init__.py
from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ "tasks.message_tasks" ]) selftest_task_queue.conf.update(**queue_conf)
from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftest_task_queue', backend='rpc', broker=create_mq_url(options.mq_hostname, options.mq_port, username=options.mq_username, password=options.mq_password), include=[ "tasks.message_tasks", "tasks.notifiers", ]) selftest_task_queue.conf.update(**queue_conf)
Add notifiers to task list
Add notifiers to task list
Python
apache-2.0
BishopFox/SpoofcheckSelfTest,BishopFox/SpoofcheckSelfTest,BishopFox/SpoofcheckSelfTest
--- +++ @@ -17,6 +17,7 @@ username=options.mq_username, password=options.mq_password), include=[ - "tasks.message_tasks" + "tasks.message_tasks", + "tasks.notifiers", ]) selftest_task_queue.conf.update(**queue_conf)
6c3d18e8f2a242f9de79679c4cccafbca5066bb6
runners/serializers.py
runners/serializers.py
from rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'url') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions')
from rest_framework import serializers from .models import Runner, RunnerVersion class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion fields = ('version', 'architecture', 'url') class RunnerSerializer(serializers.ModelSerializer): versions = RunnerVersionSerializer(many=True) class Meta(object): model = Runner fields = ('name', 'slug', 'icon', 'website', 'versions')
Add architecture to runner version serializer
Add architecture to runner version serializer
Python
agpl-3.0
lutris/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website
--- +++ @@ -5,7 +5,7 @@ class RunnerVersionSerializer(serializers.ModelSerializer): class Meta(object): model = RunnerVersion - fields = ('version', 'url') + fields = ('version', 'architecture', 'url') class RunnerSerializer(serializers.ModelSerializer):
2f635e890414f777fbe3ddde1aea74ab13558313
llvmlite/tests/test_dylib.py
llvmlite/tests/test_dylib.py
import unittest from . import TestCase from llvmlite import binding as llvm from llvmlite.binding import dylib import platform class TestDylib(TestCase): def setUp(self): llvm.initialize() llvm.initialize_native_target() llvm.initialize_native_asmprinter() def test_bad_library(self): with self.assertRaises(Exception) as context: dylib.load_library_permanently("zzzasdkf;jasd;l") system = platform.system() if system == "Linux": self.assertTrue('zzzasdkf;jasd;l: cannot open shared object file: No such file or directory' in str(context.exception)) elif system == "Darwin": self.assertTrue('dlopen(zzzasdkf;jasd;l, 9): image not found' in str(context.exception))
from . import TestCase from llvmlite import binding as llvm from llvmlite.binding import dylib import platform from ctypes.util import find_library import unittest @unittest.skipUnless(platform.system() in {"Linux", "Darwin"}, "Unsupport test for current OS") class TestDylib(TestCase): def setUp(self): llvm.initialize() llvm.initialize_native_target() llvm.initialize_native_asmprinter() self.system = platform.system() def test_bad_library(self): with self.assertRaises(Exception) as context: dylib.load_library_permanently("zzzasdkf;jasd;l") if self.system == "Linux": self.assertTrue('zzzasdkf;jasd;l: cannot open shared object file: No such file or directory' in str(context.exception)) elif self.system == "Darwin": self.assertTrue('dlopen(zzzasdkf;jasd;l, 9): image not found' in str(context.exception)) def test_libm(self): try: if self.system == "Linux": libm = find_library("m") elif self.system == "Darwin": libm = find_library("libm") dylib.load_library_permanently(libm) except Exception: self.fail("Valid call to link library should not fail.")
Add tests to check loading library.
Add tests to check loading library.
Python
bsd-2-clause
m-labs/llvmlite,pitrou/llvmlite,ssarangi/llvmlite,m-labs/llvmlite,markdewing/llvmlite,pitrou/llvmlite,numba/llvmlite,markdewing/llvmlite,sklam/llvmlite,sklam/llvmlite,pitrou/llvmlite,numba/llvmlite,ssarangi/llvmlite,markdewing/llvmlite,squisher/llvmlite,ssarangi/llvmlite,m-labs/llvmlite,numba/llvmlite,numba/llvmlite,squisher/llvmlite,squisher/llvmlite,sklam/llvmlite,ssarangi/llvmlite,sklam/llvmlite,squisher/llvmlite,markdewing/llvmlite,m-labs/llvmlite,pitrou/llvmlite
--- +++ @@ -1,25 +1,35 @@ -import unittest from . import TestCase from llvmlite import binding as llvm from llvmlite.binding import dylib import platform +from ctypes.util import find_library +import unittest - +@unittest.skipUnless(platform.system() in {"Linux", "Darwin"}, "Unsupport test for current OS") class TestDylib(TestCase): - def setUp(self): llvm.initialize() llvm.initialize_native_target() llvm.initialize_native_asmprinter() + self.system = platform.system() def test_bad_library(self): with self.assertRaises(Exception) as context: dylib.load_library_permanently("zzzasdkf;jasd;l") - system = platform.system() - if system == "Linux": + if self.system == "Linux": self.assertTrue('zzzasdkf;jasd;l: cannot open shared object file: No such file or directory' in str(context.exception)) - elif system == "Darwin": + elif self.system == "Darwin": self.assertTrue('dlopen(zzzasdkf;jasd;l, 9): image not found' in str(context.exception)) + + def test_libm(self): + try: + if self.system == "Linux": + libm = find_library("m") + elif self.system == "Darwin": + libm = find_library("libm") + dylib.load_library_permanently(libm) + except Exception: + self.fail("Valid call to link library should not fail.")
95b4cdae136ea918279a4c8968f756dc15a629ed
buzzmobile/setup.py
buzzmobile/setup.py
#!/usr/bin/env python #for downloading the packages needed for this project. from setuptools import setup, find_packages setup( name='buzzmobile', version='0.3', url='https://github.com/gtagency/buzzmobile', author='gtagency', license='MIT', keywords='car cars self-driving lidar gps ros', install_requires=[ 'catkin_pkg==0.2.10', 'googlemaps==2.4.4', 'matplotlib==1.5.3', 'numpy==1.11.2', 'polyline==1.3.1', 'pylint', 'pytest==3.0.3', 'pyyaml==3.12', 'rospkg==1.0.41', 'ds4drv', # requires apt-get install python-dev 'empy==3.3.2', # required to make catkin_make work ], )
#!/usr/bin/env python #for downloading the packages needed for this project. from setuptools import setup, find_packages setup( name='buzzmobile', version='0.3', url='https://github.com/gtagency/buzzmobile', author='gtagency', license='MIT', keywords='car cars self-driving lidar gps ros', install_requires=[ 'catkin_pkg==0.2.10', 'googlemaps==2.4.4', 'matplotlib==1.5.3', 'numpy==1.11.2', 'polyline==1.3.1', 'pylint', 'pytest==3.0.3', 'pyyaml==3.12', 'rospkg==1.0.41', 'ds4drv', # requires apt-get install python-dev 'empy==3.3.2', # required to make catkin_make work 'netifaces==0.10.5', ], )
Add required dependency for roslaunch
Add required dependency for roslaunch
Python
mit
gtagency/buzzmobile,gtagency/buzzmobile,jgkamat/buzzmobile,jgkamat/buzzmobile,jgkamat/buzzmobile,gtagency/buzzmobile
--- +++ @@ -22,5 +22,6 @@ 'rospkg==1.0.41', 'ds4drv', # requires apt-get install python-dev 'empy==3.3.2', # required to make catkin_make work + 'netifaces==0.10.5', ], )
77f975b9f19fad319708f19c4602ab4fd7ad8260
scripts/ben10_build.py
scripts/ben10_build.py
from __future__ import unicode_literals from aasimar.shared_commands import BuildCommand from ben10.foundation.decorators import Override #=================================================================================================== # Ben10BuildCommand #=================================================================================================== class Ben10BuildCommand(BuildCommand): PLATFORMS = ['win32', 'win64', 'redhat64', 'centos64'] @Override(BuildCommand.EvBuild) def EvBuild(self, args): self.Clean() self.Install() self.IsClean() self.RunTests( jobs=self.shared_script['hudson_test_jobs'], use_cache=not self.opts.no_cache, xml=True, verbose=4 ) @Override(BuildCommand.EvPublish) def EvPublish(self, args): self.CiPublish(installer=False, all_platforms='win32,win64,redhat64', force=True)
from __future__ import unicode_literals from aasimar.shared_commands import BuildCommand from ben10.foundation.decorators import Override #=================================================================================================== # Ben10BuildCommand #=================================================================================================== class Ben10BuildCommand(BuildCommand): PLATFORMS = ['win32', 'win64', 'redhat64', 'centos64'] @Override(BuildCommand.EvBuild) def EvBuild(self, args): self.Clean() self.Install(no_spawn=True) self.IsClean() self.RunTests( jobs=self.shared_script['hudson_test_jobs'], use_cache=not self.opts.no_cache, xml=True, verbose=4 ) @Override(BuildCommand.EvPublish) def EvPublish(self, args): self.CiPublish(installer=False, all_platforms='win32,win64,redhat64', force=True)
Fix build issues when sharedscripts10 is not available.
Fix build issues when sharedscripts10 is not available. By calling project.install with --no-spawn, we can avoid an error that happened during build: [ben10] Resource not found "sharedscripts10".
Python
lgpl-2.1
Kaniabi/ben10,ESSS/ben10,Kaniabi/ben10,ESSS/ben10
--- +++ @@ -14,7 +14,7 @@ @Override(BuildCommand.EvBuild) def EvBuild(self, args): self.Clean() - self.Install() + self.Install(no_spawn=True) self.IsClean() self.RunTests( jobs=self.shared_script['hudson_test_jobs'],
f5922951bcabac81c41fd52e2ed5cd9b67c9a920
src/gramcore/features/tests/test_descriptors.py
src/gramcore/features/tests/test_descriptors.py
"""Tests for module gramcore.features.descriptors""" import numpy from nose.tools import assert_equal from gramcore.features import descriptors def test_hog_size(): """Create a fixture and check hog result size There are already enough tests in skimage for this, just adding so to document how many values are returned and why. Creates a square array and inputs it to hog. For simplicity the blocks and the cells are square. The calculated orientations are set to 9. Based on these the result should include a number of values equal to:: block_possitions^2 * cells_per_block^2 * orientations """ pixels_per_cell = 9 cells_per_block = 8 orientations = 9 # double the size so to generate some blocks and initialize the array arr_dim = 2 * pixels_per_cell * cells_per_block arr = numpy.zeros((arr_dim, arr_dim)) parameters = {'data': [arr], 'orientations': orientations, 'pixels_per_cell': [pixels_per_cell, pixels_per_cell], 'cells_per_block': [cells_per_block, cells_per_block]} results = descriptors.hog(parameters) # calculate how many blocks fit in the array, basically how many # sliding window positions are there block_positions = (arr_dim / pixels_per_cell) - cells_per_block + 1 assert_equal(results.shape[0], block_positions**2 *\ cells_per_block**2 *\ orientations)
"""Tests for module gramcore.features.descriptors""" import numpy from nose.tools import assert_equal from gramcore.features import descriptors def test_hog_size(): """Create a fixture and check hog result size There are already enough tests in skimage for this, just adding so to document how many values are returned and why. Creates a square array and inputs it to hog. For simplicity the blocks and the cells are square. The calculated orientations are set to 9. Based on these the result should include a number of values equal to:: block_possitions^2 * cells_per_block^2 * orientations HOG calculations take place in row major order. """ pixels_per_cell = 9 cells_per_block = 8 orientations = 9 # double the size so to generate some blocks and initialize the array arr_dim = 2 * pixels_per_cell * cells_per_block arr = numpy.zeros((arr_dim, arr_dim)) parameters = {'data': [arr], 'orientations': orientations, 'pixels_per_cell': [pixels_per_cell, pixels_per_cell], 'cells_per_block': [cells_per_block, cells_per_block]} results = descriptors.hog(parameters) # calculate how many blocks fit in the array, basically how many # sliding window positions are there block_positions = (arr_dim / pixels_per_cell) - cells_per_block + 1 assert_equal(results.shape[0], block_positions**2 *\ cells_per_block**2 *\ orientations)
Add comment on HOG calculations
Add comment on HOG calculations
Python
mit
cpsaltis/pythogram-core
--- +++ @@ -17,6 +17,8 @@ Based on these the result should include a number of values equal to:: block_possitions^2 * cells_per_block^2 * orientations + + HOG calculations take place in row major order. """ pixels_per_cell = 9
8aca599083f69fbc4427f608554d4035c7d2dccf
social/apps/pyramid_app/views.py
social/apps/pyramid_app/views.py
from pyramid.view import view_config from social.utils import module_member from social.actions import do_auth, do_complete, do_disconnect from social.apps.pyramid_app.utils import psa, login_required @view_config(route_name='social.auth', request_method='GET') @psa('social.complete') def auth(request): return do_auth(request.backend, redirect_name='next') @view_config(route_name='social.complete', request_method=('GET', 'POST')) @psa('social.complete') def complete(request, *args, **kwargs): do_login = module_member(request.backend.setting('LOGIN_FUNCTION')) return do_complete(request.backend, do_login, request.user, redirect_name='next', *args, **kwargs) @view_config(route_name='social.disconnect', request_method=('POST',)) @view_config(route_name='social.disconnect_association', request_method=('POST',)) @psa() @login_required def disconnect(request): return do_disconnect(request.backend, request.user, request.matchdict.get('association_id'), redirect_name='next')
from pyramid.view import view_config from social.utils import module_member from social.actions import do_auth, do_complete, do_disconnect from social.apps.pyramid_app.utils import psa, login_required @view_config(route_name='social.auth', request_method=('GET', 'POST')) @psa('social.complete') def auth(request): return do_auth(request.backend, redirect_name='next') @view_config(route_name='social.complete', request_method=('GET', 'POST')) @psa('social.complete') def complete(request, *args, **kwargs): do_login = module_member(request.backend.setting('LOGIN_FUNCTION')) return do_complete(request.backend, do_login, request.user, redirect_name='next', *args, **kwargs) @view_config(route_name='social.disconnect', request_method=('POST',)) @view_config(route_name='social.disconnect_association', request_method=('POST',)) @psa() @login_required def disconnect(request): return do_disconnect(request.backend, request.user, request.matchdict.get('association_id'), redirect_name='next')
Allow POST requests for auth method so OpenID forms could use it that way.
Allow POST requests for auth method so OpenID forms could use it that way.
Python
bsd-3-clause
fearlessspider/python-social-auth,cjltsod/python-social-auth,python-social-auth/social-app-django,tobias47n9e/social-core,python-social-auth/social-core,python-social-auth/social-app-django,python-social-auth/social-storage-sqlalchemy,fearlessspider/python-social-auth,python-social-auth/social-app-cherrypy,cjltsod/python-social-auth,python-social-auth/social-app-django,rsalmaso/python-social-auth,python-social-auth/social-docs,fearlessspider/python-social-auth,python-social-auth/social-core,rsalmaso/python-social-auth
--- +++ @@ -5,7 +5,7 @@ from social.apps.pyramid_app.utils import psa, login_required -@view_config(route_name='social.auth', request_method='GET') +@view_config(route_name='social.auth', request_method=('GET', 'POST')) @psa('social.complete') def auth(request): return do_auth(request.backend, redirect_name='next')
cbdc24aeef9ffbd8e7400ab43112409509b3337d
reviewday/util.py
reviewday/util.py
import os import shutil import html_helper from Cheetah.Template import Template def prep_out_dir(out_dir='out_report'): src_dir = os.path.dirname(__file__) report_files_dir = os.path.join(src_dir, 'report_files') if os.path.exists(out_dir): print 'WARNING: output directory "%s" already exists' % out_dir else: shutil.copytree(report_files_dir, out_dir) def create_report(name_space={}): filename = os.path.join(os.path.dirname(__file__), 'report.html') report_text = open(filename).read() name_space['helper'] = html_helper t = Template(report_text, searchList=[name_space]) out_dir = 'out_report' prep_out_dir(out_dir) out_file = open(os.path.join(out_dir, 'index.html'), "w") out_file.write(str(t)) out_file.close()
import os import html_helper from Cheetah.Template import Template from distutils.dir_util import copy_tree def prep_out_dir(out_dir='out_report'): src_dir = os.path.dirname(__file__) report_files_dir = os.path.join(src_dir, 'report_files') copy_tree(report_files_dir, out_dir) def create_report(name_space={}): filename = os.path.join(os.path.dirname(__file__), 'report.html') report_text = open(filename).read() name_space['helper'] = html_helper t = Template(report_text, searchList=[name_space]) out_dir = 'out_report' prep_out_dir(out_dir) out_file = open(os.path.join(out_dir, 'index.html'), "w") out_file.write(str(t)) out_file.close()
Remove warning for existing output directory.
Remove warning for existing output directory. In our configuration puppet will manage the output directory, so it is expected behavior for it to exist, removing warning. Also switching to distutils.dir_util copy_tree since that allows for copying of required supporting files into an existing output directory. Change-Id: I38b2c6ec47fd61814554a4b5007a83553b05aeb2 Reviewed-on: https://review.openstack.org/20647 Approved: Dan Prince <62cccc0004df0a8e3c343b26b69e434f6aa9711c@redhat.com> Reviewed-by: Dan Prince <62cccc0004df0a8e3c343b26b69e434f6aa9711c@redhat.com> Tested-by: Jenkins
Python
mit
openstack-infra/reviewday,openstack-infra/reviewday,dprince/reviewday
--- +++ @@ -1,16 +1,13 @@ import os -import shutil import html_helper from Cheetah.Template import Template +from distutils.dir_util import copy_tree def prep_out_dir(out_dir='out_report'): src_dir = os.path.dirname(__file__) report_files_dir = os.path.join(src_dir, 'report_files') - if os.path.exists(out_dir): - print 'WARNING: output directory "%s" already exists' % out_dir - else: - shutil.copytree(report_files_dir, out_dir) + copy_tree(report_files_dir, out_dir) def create_report(name_space={}):
4ed64168541993e2ea85e7ea47139550d1daa206
backdrop/write/config/development_environment_sample.py
backdrop/write/config/development_environment_sample.py
# Copy this file to development_environment.py # and replace OAuth credentials your dev credentials TOKENS = { '_foo_bucket': '_foo_bucket-bearer-token', 'bucket': 'bucket-bearer-token', 'foo': 'foo-bearer-token', 'foo_bucket': 'foo_bucket-bearer-token', 'licensing': 'licensing-bearer-token', 'licensing_journey': 'licensing_journey-bearer-token' } PERMISSIONS = {} OAUTH_CLIENT_ID = \ "1759c91cdc926eebe5d5c9fce53a58170ad17ba30a22b4b451c377a339a98844" OAUTH_CLIENT_SECRET = \ "8f205218c0a378e33dccae5a557b4cac766f343a7dbfcb50de2286f03db4273a" OAUTH_BASE_URL = "http://signon.dev.gov.uk"
# Copy this file to development_environment.py # and replace OAuth credentials your dev credentials TOKENS = { '_foo_bucket': '_foo_bucket-bearer-token', 'bucket': 'bucket-bearer-token', 'foo': 'foo-bearer-token', 'foo_bucket': 'foo_bucket-bearer-token', 'licensing': 'licensing-bearer-token', 'licensing_journey': 'licensing_journey-bearer-token', 'licensing_live_data': 'licensing_live_data_bearer_token', 'licence_finder_live_data': 'licence_finder_live_data_bearer_token' } PERMISSIONS = {} OAUTH_CLIENT_ID = \ "1759c91cdc926eebe5d5c9fce53a58170ad17ba30a22b4b451c377a339a98844" OAUTH_CLIENT_SECRET = \ "8f205218c0a378e33dccae5a557b4cac766f343a7dbfcb50de2286f03db4273a" OAUTH_BASE_URL = "http://signon.dev.gov.uk"
Add buckets for collecting pingdom data
Add buckets for collecting pingdom data
Python
mit
alphagov/backdrop,alphagov/backdrop,alphagov/backdrop
--- +++ @@ -6,7 +6,9 @@ 'foo': 'foo-bearer-token', 'foo_bucket': 'foo_bucket-bearer-token', 'licensing': 'licensing-bearer-token', - 'licensing_journey': 'licensing_journey-bearer-token' + 'licensing_journey': 'licensing_journey-bearer-token', + 'licensing_live_data': 'licensing_live_data_bearer_token', + 'licence_finder_live_data': 'licence_finder_live_data_bearer_token' } PERMISSIONS = {} OAUTH_CLIENT_ID = \
653ae451e204905b8295e424ca86c20d60ee686c
settings/__init__.py
settings/__init__.py
import yaml import utils with open('settings.yml') as settings_file: YML = yaml.safe_load(settings_file) IMAGE = utils.Settings(YML['image']) SNAP = utils.Settings(YML['snap']) DROPBOX_TOKEN_FILE = "./dropbox.txt" WORKING_DIRECTORY = "/home/pi/time-lapse" IMAGES_DIRECTORY = WORKING_DIRECTORY + "/images" JOBS_DIRECTORY = WORKING_DIRECTORY + "/jobs"
import glob import yaml import utils with open('settings.yml') as settings_file: YML = yaml.safe_load(settings_file) IMAGE = utils.Settings(YML['image']) SNAP = utils.Settings(YML['snap']) DROPBOX_TOKEN_FILE = "./dropbox.txt" WORKING_DIRECTORY = "/home/pi/time-lapse" IMAGES_DIRECTORY = WORKING_DIRECTORY + "/images" JOBS_DIRECTORY = WORKING_DIRECTORY + "/jobs" class Setting(object): def __init__(self, settings_dict): self.__dict__.update(settings_dict) class Job(object): def __init__(self): self.image = None self.snap = None self.__load_job_data() def __parse_data_from_file(self, job_file): with open('settings.yml') as file_data: parsed_yaml = yaml.safe_load(file_data) return parsed_yaml def __load_job_data(self): job_files = glob.glob(JOBS_DIRECTORY + "/job_*.yml") try: # Take the first file if there are many parsed_yaml = self.__parse_data_from_file(job_files[0]) self.image = Setting(parsed_yaml['image']) self.snap = Setting(parsed_yaml['snap']) except (IndexError, KeyError): pass def is_defined(self): if not self.image: return False if not self.snap: return False return True
Make a class to manage job settings
Make a class to manage job settings
Python
mit
projectweekend/Pi-Camera-Time-Lapse,projectweekend/Pi-Camera-Time-Lapse
--- +++ @@ -1,3 +1,4 @@ +import glob import yaml import utils @@ -11,3 +12,39 @@ WORKING_DIRECTORY = "/home/pi/time-lapse" IMAGES_DIRECTORY = WORKING_DIRECTORY + "/images" JOBS_DIRECTORY = WORKING_DIRECTORY + "/jobs" + + +class Setting(object): + + def __init__(self, settings_dict): + self.__dict__.update(settings_dict) + + +class Job(object): + + def __init__(self): + self.image = None + self.snap = None + self.__load_job_data() + + def __parse_data_from_file(self, job_file): + with open('settings.yml') as file_data: + parsed_yaml = yaml.safe_load(file_data) + return parsed_yaml + + def __load_job_data(self): + job_files = glob.glob(JOBS_DIRECTORY + "/job_*.yml") + try: + # Take the first file if there are many + parsed_yaml = self.__parse_data_from_file(job_files[0]) + self.image = Setting(parsed_yaml['image']) + self.snap = Setting(parsed_yaml['snap']) + except (IndexError, KeyError): + pass + + def is_defined(self): + if not self.image: + return False + if not self.snap: + return False + return True
7d4b2af132001927ea42b69650b6b45301ee335f
astrobin/management/commands/notify_new_blog_entry.py
astrobin/management/commands/notify_new_blog_entry.py
from django.core.management.base import BaseCommand from django.contrib.auth.models import User from zinnia.models import Entry from astrobin.notifications import push_notification class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] push_notification( User.objects.all(), 'new_blog_entry', { 'object': entry.title, 'object_url': entry.get_absolute_url() } )
from django.core.management.base import BaseCommand from django.contrib.auth.models import User import persistent_messages from zinnia.models import Entry class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] for u in User.objects.all(): m = persistent_messages.models.Message( user = u, from_user = User.objects.get(username = 'astrobin'), message = '<a href="' + entry.get_absolute_url() + '">New blog entry: <strong>' + entry.title + '</strong></a>', level = persistent_messages.INFO, ) m.save()
Fix management command to send notification about new blog post.
Fix management command to send notification about new blog post.
Python
agpl-3.0
astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin
--- +++ @@ -1,20 +1,20 @@ from django.core.management.base import BaseCommand from django.contrib.auth.models import User +import persistent_messages from zinnia.models import Entry -from astrobin.notifications import push_notification class Command(BaseCommand): help = "Notifies all users about most recent blog entry." def handle(self, *args, **options): entry = Entry.objects.all()[0] - push_notification( - User.objects.all(), - 'new_blog_entry', - { - 'object': entry.title, - 'object_url': entry.get_absolute_url() - } - ) + for u in User.objects.all(): + m = persistent_messages.models.Message( + user = u, + from_user = User.objects.get(username = 'astrobin'), + message = '<a href="' + entry.get_absolute_url() + '">New blog entry: <strong>' + entry.title + '</strong></a>', + level = persistent_messages.INFO, + ) + m.save()
0a04752396bdd57a8c197e2c76e5bda92d0bad1a
reddit_meatspace/utils.py
reddit_meatspace/utils.py
import hashlib from pylons import g def make_secret_code(meetup, user): hash = hashlib.md5(g.SECRET) hash.update(str(meetup._id)) hash.update(str(user._id)) return int(hash.hexdigest()[-8:], 16) % 100
import hashlib from pylons import g def make_secret_code(meetup, user): hash = hashlib.md5(g.secrets["SECRET"]) hash.update(str(meetup._id)) hash.update(str(user._id)) return int(hash.hexdigest()[-8:], 16) % 100
Use the zk secret safe for g.SECRET.
Use the zk secret safe for g.SECRET.
Python
bsd-3-clause
reddit/reddit-plugin-meatspace,reddit/reddit-plugin-meatspace,reddit/reddit-plugin-meatspace
--- +++ @@ -4,7 +4,7 @@ def make_secret_code(meetup, user): - hash = hashlib.md5(g.SECRET) + hash = hashlib.md5(g.secrets["SECRET"]) hash.update(str(meetup._id)) hash.update(str(user._id)) return int(hash.hexdigest()[-8:], 16) % 100
22ce36b227c40ace101db5d9c4e30575adca5f36
tests/settings.py
tests/settings.py
import os from settings import * db = os.environ.get('DB') SECRET_KEY = "This is a test, you don't need secrets" if db == "sqlite": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } elif db == "postgres": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'inboxen', 'USER': 'postgres', }, } else: raise NotImplementedError("Please check tests/settings.py for valid DB values")
from __future__ import absolute_import import os from settings import * db = os.environ.get('DB') SECRET_KEY = "This is a test, you don't need secrets" if db == "sqlite": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } elif db == "postgres": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'inboxen', 'USER': 'postgres', }, } else: raise NotImplementedError("Please check tests/settings.py for valid DB values")
Use absolute imports to avoid module naming issues
Use absolute imports to avoid module naming issues
Python
agpl-3.0
Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/infrastructure,Inboxen/Inboxen,Inboxen/Inboxen
--- +++ @@ -1,3 +1,4 @@ +from __future__ import absolute_import import os from settings import *
eabab4dcb52a8d63c74bb8b785696bc36b8b25e7
site_cfg_template.py
site_cfg_template.py
## # Template file for site configuration - copy it to site_cfg.py: # $ cp site_cfg_template.py site_cfg.py # Force python version (e.g. '2.4'), or left 'auto' for autodetection. python_version = 'auto' # Operating system - one of 'posix', 'windows' or None for automatic # determination. system = None # Extra flags added to the flags supplied by distutils to compile C # extension modules. compile_flags = '-g -O2 -v' # Extra flags added to the flags supplied by distutils to link C # extension modules. link_flags = '' # Can be '' or one or several from '-DDEBUG_FMF', '-DDEBUG_MESH'. For # developers internal use only. debug_flags = '' # Sphinx documentation uses numpydoc extension. Set the path here in case it is # not installed in a standard location. numpydoc_path = None # True for a release, False otherwise. If False, current git commit hash # is appended to version string, if the sources are in a repository. is_release = False # Tetgen executable path. tetgen_path = '/usr/bin/tetgen'
## # Template file for site configuration - copy it to site_cfg.py: # $ cp site_cfg_template.py site_cfg.py # Force python version (e.g. '2.4'), or left 'auto' for autodetection. python_version = 'auto' # Operating system - one of 'posix', 'windows' or None for automatic # determination. system = None # Extra flags added to the flags supplied by distutils to compile C # extension modules. compile_flags = '-g -O2' # Extra flags added to the flags supplied by distutils to link C # extension modules. link_flags = '' # Can be '' or one or several from '-DDEBUG_FMF', '-DDEBUG_MESH'. For # developers internal use only. debug_flags = '' # Sphinx documentation uses numpydoc extension. Set the path here in case it is # not installed in a standard location. numpydoc_path = None # True for a release, False otherwise. If False, current git commit hash # is appended to version string, if the sources are in a repository. is_release = False # Tetgen executable path. tetgen_path = '/usr/bin/tetgen'
Revert "Add verbose flag to compiler options (testing)."
Revert "Add verbose flag to compiler options (testing)." This reverts commit 2406e30851b65cd78981eecd76d966fb17259fa4.
Python
bsd-3-clause
BubuLK/sfepy,sfepy/sfepy,vlukes/sfepy,vlukes/sfepy,rc/sfepy,rc/sfepy,sfepy/sfepy,vlukes/sfepy,BubuLK/sfepy,sfepy/sfepy,BubuLK/sfepy,rc/sfepy
--- +++ @@ -11,7 +11,7 @@ # Extra flags added to the flags supplied by distutils to compile C # extension modules. -compile_flags = '-g -O2 -v' +compile_flags = '-g -O2' # Extra flags added to the flags supplied by distutils to link C # extension modules.
8df3076b6315a74e57ee27fe3478d36737be0ff9
roche/scripts/xml-load.py
roche/scripts/xml-load.py
# coding=utf-8 # # Must be called in roche root dir # import sys import os sys.path.append('.') import roche.settings from os import walk from eulexistdb.db import ExistDB from roche.settings import EXISTDB_SERVER_URL # # Timeout higher? # xmldb = ExistDB(timeout=30) xmldb.createCollection('docker', True) xmldb.createCollection('docker/texts', True) os.chdir('../dublin-store') for (dirpath, dirnames, filenames) in walk('浙江大學圖書館'): xmldb.createCollection('docker/texts' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True)
# coding=utf-8 # # Must be called in roche root dir # import sys import os sys.path.append('.') import roche.settings from os import walk from eulexistdb.db import ExistDB from roche.settings import EXISTDB_SERVER_URL # # Timeout higher? # xmldb = ExistDB(timeout=30) xmldb.createCollection('docker', True) xmldb.createCollection('docker/texts', True) os.chdir('../dublin-store') for (dirpath, dirnames, filenames) in walk('浙江大學圖書館'): xmldb.createCollection('docker/texts' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True) # # Load resources # for (dirpath, dirnames, filenames) in walk('resources'): xmldb.createCollection('docker' + '/' + dirpath, True) if filenames: for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker' + '/' + dirpath + '/' + filename, True)
Load other resources into exist-db
Load other resources into exist-db
Python
mit
beijingren/roche-website,beijingren/roche-website,beijingren/roche-website,beijingren/roche-website
--- +++ @@ -30,3 +30,13 @@ for filename in filenames: with open(dirpath + '/' + filename) as f: xmldb.load(f, 'docker/texts' + '/' + dirpath + '/' + filename, True) + +# +# Load resources +# +for (dirpath, dirnames, filenames) in walk('resources'): + xmldb.createCollection('docker' + '/' + dirpath, True) + if filenames: + for filename in filenames: + with open(dirpath + '/' + filename) as f: + xmldb.load(f, 'docker' + '/' + dirpath + '/' + filename, True)
63a539ff4a3a832286136c40a74b1a8b3db1a5c0
falcom/api/uri/api_querier.py
falcom/api/uri/api_querier.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from time import sleep class APIQuerier: def __init__ (self, uri, url_opener, sleep_time=300, max_tries=0): self.uri = uri self.url_opener = url_opener self.sleep_time = sleep_time self.max_tries = max_tries def get (self, **kwargs): try: return self.__open_uri(kwargs) except ConnectionError: sleep(self.sleep_time) i = 1 while i != self.max_tries: i += 1 try: return self.__open_uri(kwargs) except ConnectionError: sleep(self.sleep_time) return b"" @staticmethod def utf8 (str_or_bytes): if isinstance(str_or_bytes, bytes): return str_or_bytes.decode("utf_8") else: return str_or_bytes def __open_uri (self, kwargs): with self.url_opener(self.uri(**kwargs)) as response: result = self.utf8(response.read()) return result
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from time import sleep class APIQuerier: def __init__ (self, uri, url_opener, sleep_time=300, max_tries=0): self.uri = uri self.url_opener = url_opener self.sleep_time = sleep_time self.max_tries = max_tries def get (self, **kwargs): class SpecialNull: pass result = SpecialNull i = 1 while result is SpecialNull: try: result = self.__open_uri(kwargs) except ConnectionError: sleep(self.sleep_time) if i == self.max_tries: result = b"" else: i += 1 return result @staticmethod def utf8 (str_or_bytes): if isinstance(str_or_bytes, bytes): return str_or_bytes.decode("utf_8") else: return str_or_bytes def __open_uri (self, kwargs): with self.url_opener(self.uri(**kwargs)) as response: result = self.utf8(response.read()) return result
Rewrite get() to be less repetitive but still stupid
Rewrite get() to be less repetitive but still stupid
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
--- +++ @@ -12,23 +12,24 @@ self.max_tries = max_tries def get (self, **kwargs): - try: - return self.__open_uri(kwargs) + class SpecialNull: pass + result = SpecialNull + i = 1 - except ConnectionError: - sleep(self.sleep_time) - - i = 1 - while i != self.max_tries: - i += 1 - + while result is SpecialNull: try: - return self.__open_uri(kwargs) + result = self.__open_uri(kwargs) except ConnectionError: sleep(self.sleep_time) - return b"" + if i == self.max_tries: + result = b"" + + else: + i += 1 + + return result @staticmethod def utf8 (str_or_bytes):
edc88421bec2798d82faeece2df5229888d97db9
contrib/performance/graph.py
contrib/performance/graph.py
import sys, pickle from matplotlib import pyplot import numpy from compare import select def main(): fig = pyplot.figure() ax = fig.add_subplot(111) data = [] for fname in sys.argv[1:]: stats, samples = select( pickle.load(file(fname)), 'vfreebusy', 1, 'urlopen time') data.append(samples) if data: assert len(samples) == len(data[0]) bars = [] color = iter('rgbcmy').next w = 1.0 / len(data) xs = numpy.arange(len(data[0])) for i, s in enumerate(data): bars.append(ax.bar(xs + i * w, s, width=w, color=color())[0]) ax.set_xlabel('sample #') ax.set_ylabel('seconds') ax.legend(bars, sys.argv[1:]) pyplot.show()
import sys, pickle from matplotlib import pyplot import numpy from compare import select def main(): fig = pyplot.figure() ax = fig.add_subplot(111) data = [] for fname in sys.argv[1:]: fname, bench, param, stat = fname.split(',') stats, samples = select( pickle.load(file(fname)), bench, param, stat) data.append(samples) if data: assert len(samples) == len(data[0]) bars = [] color = iter('rgbcmy').next w = 1.0 / len(data) xs = numpy.arange(len(data[0])) for i, s in enumerate(data): bars.append(ax.bar(xs + i * w, s, width=w, color=color())[0]) ax.set_xlabel('sample #') ax.set_ylabel('seconds') ax.legend(bars, sys.argv[1:]) pyplot.show()
Make the bench/param/stat a commandline parameter
Make the bench/param/stat a commandline parameter git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6150 e27351fd-9f3e-4f54-a53b-843176b1656c
Python
apache-2.0
trevor/calendarserver,trevor/calendarserver,trevor/calendarserver
--- +++ @@ -12,8 +12,9 @@ data = [] for fname in sys.argv[1:]: + fname, bench, param, stat = fname.split(',') stats, samples = select( - pickle.load(file(fname)), 'vfreebusy', 1, 'urlopen time') + pickle.load(file(fname)), bench, param, stat) data.append(samples) if data: assert len(samples) == len(data[0])
a4913289ce0672cfe60bb443db469356f970c353
wakatime/projects/projectmap.py
wakatime/projects/projectmap.py
# -*- coding: utf-8 -*- """ wakatime.projects.projectmap ~~~~~~~~~~~~~~~~~~~~~~~~~~ Information from ~/.waka-projectmap mapping folders (relative to home folder) to project names :author: 3onyc :license: BSD, see LICENSE for more details. """ import logging import os from ..packages import simplejson as json from .base import BaseProject log = logging.getLogger(__name__) class ProjectMap(BaseProject): def process(self): self.config = self._load_config() if self.config: log.debug(self.config) return True return False def branch(self): return None def name(self): for path in self._path_generator(): if path in self.config: return self.config[path] return None def _load_config(self): map_path = "%s/.waka-projectmap" % os.environ['HOME'] if os.path.isfile(map_path): with open(map_path) as map_file: try: return json.load(map_file) except (IOError, json.JSONDecodeError) as e: log.exception("ProjectMap Exception: ") return False def _path_generator(self): path = self.path.replace(os.environ['HOME'], '') while path != os.path.dirname(path): yield path path = os.path.dirname(path)
# -*- coding: utf-8 -*- """ wakatime.projects.projectmap ~~~~~~~~~~~~~~~~~~~~~~~~~~ Information from ~/.waka-projectmap mapping folders (relative to home folder) to project names :author: 3onyc :license: BSD, see LICENSE for more details. """ import logging import os from ..packages import simplejson as json from .base import BaseProject log = logging.getLogger(__name__) class ProjectMap(BaseProject): def process(self): if self.config: return True return False def branch(self): return None def name(self): for path in self._path_generator(): if self.config.has_option('projectmap', path): return self.config.get('projectmap', path) return None def _path_generator(self): path = self.path.replace(os.environ['HOME'], '') while path != os.path.dirname(path): yield path path = os.path.dirname(path)
Make ProjectMap use config section
Make ProjectMap use config section
Python
bsd-3-clause
wakatime/wakatime,Djabbz/wakatime,prashanthr/wakatime,Djabbz/wakatime,wakatime/wakatime,Djabbz/wakatime,queenp/wakatime,gandarez/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,queenp/wakatime,Djabbz/wakatime,gandarez/wakatime,wakatime/wakatime,Djabbz/wakatime,prashanthr/wakatime,wangjun/wakatime,Djabbz/wakatime,wakatime/wakatime,Djabbz/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wangjun/wakatime,wakatime/wakatime,wakatime/wakatime
--- +++ @@ -23,9 +23,7 @@ class ProjectMap(BaseProject): def process(self): - self.config = self._load_config() if self.config: - log.debug(self.config) return True return False @@ -35,21 +33,10 @@ def name(self): for path in self._path_generator(): - if path in self.config: - return self.config[path] + if self.config.has_option('projectmap', path): + return self.config.get('projectmap', path) return None - - def _load_config(self): - map_path = "%s/.waka-projectmap" % os.environ['HOME'] - if os.path.isfile(map_path): - with open(map_path) as map_file: - try: - return json.load(map_file) - except (IOError, json.JSONDecodeError) as e: - log.exception("ProjectMap Exception: ") - - return False def _path_generator(self): path = self.path.replace(os.environ['HOME'], '')
f1436f7f5140ea51fd5fc1f231e28f57c69f0cb1
tutorials/urls.py
tutorials/urls.py
from django.conf.urls import include, url from tutorials import views urlpatterns = [ url(r'^$', views.ListTutorials.as_view()), url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()), ]
from django.conf.urls import include, url from markdownx import urls as markdownx from tutorials import views urlpatterns = [ url(r'^$', views.ListTutorials.as_view()), url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()), # this not working correctly - some error in gatherTutorials url(r'/add/', views.NewTutorial.as_view(), name='add_tutorial'), url(r'^markdownx/', include(markdownx)), ]
Add markdownx url, Add add-tutrorial url
Add markdownx url, Add add-tutrorial url
Python
agpl-3.0
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
--- +++ @@ -1,8 +1,12 @@ from django.conf.urls import include, url +from markdownx import urls as markdownx from tutorials import views urlpatterns = [ url(r'^$', views.ListTutorials.as_view()), url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()), + # this not working correctly - some error in gatherTutorials + url(r'/add/', views.NewTutorial.as_view(), name='add_tutorial'), + url(r'^markdownx/', include(markdownx)), ]
6bdc335ebb8ed009cbc926e681ee6be8f475f323
reviewboard/reviews/features.py
reviewboard/reviews/features.py
"""Feature definitions for reviews.""" from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from djblets.features import Feature, FeatureLevel class GeneralCommentsFeature(Feature): """A feature for general comments. General comments allow comments to be created directly on a review request without accompanying file attachment or diff. These can be used to raise issues with the review request itself, such as its summary or description, or general implementation issues. """ feature_id = 'reviews.general_comments' name = _('General Comments') level = FeatureLevel.STABLE summary = _('Allow comments on review requests without an associated file ' 'attachment or diff.') class StatusUpdatesFeature(Feature): """A feature for status updates. A status update is a way for third-party tools to provide feedback on a review request. In the past, this was done just as a normal review. Status updates allow those tools (via some integration like Review Bot) to mark their state (such as pending, success, failure, or error) and then associate that with a review. """ feature_id = 'reviews.status_updates' name = _('Status Updates') summary = _('A way for external tools to do checks on a review request ' 'and report the results of those checks.') general_comments_feature = GeneralCommentsFeature() status_updates_feature = StatusUpdatesFeature()
"""Feature definitions for reviews.""" from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from djblets.features import Feature, FeatureLevel class GeneralCommentsFeature(Feature): """A feature for general comments. General comments allow comments to be created directly on a review request without accompanying file attachment or diff. These can be used to raise issues with the review request itself, such as its summary or description, or general implementation issues. """ feature_id = 'reviews.general_comments' name = _('General Comments') level = FeatureLevel.STABLE summary = _('Allow comments on review requests without an associated file ' 'attachment or diff.') class StatusUpdatesFeature(Feature): """A feature for status updates. A status update is a way for third-party tools to provide feedback on a review request. In the past, this was done just as a normal review. Status updates allow those tools (via some integration like Review Bot) to mark their state (such as pending, success, failure, or error) and then associate that with a review. """ feature_id = 'reviews.status_updates' name = _('Status Updates') level = FeatureLevel.STABLE summary = _('A way for external tools to do checks on a review request ' 'and report the results of those checks.') general_comments_feature = GeneralCommentsFeature() status_updates_feature = StatusUpdatesFeature()
Mark status updates as stable.
Mark status updates as stable. This allows people to actually use the feature without turning it on in their `settings_local.py`. Reviewed at https://reviews.reviewboard.org/r/8569/
Python
mit
sgallagher/reviewboard,brennie/reviewboard,chipx86/reviewboard,chipx86/reviewboard,chipx86/reviewboard,davidt/reviewboard,reviewboard/reviewboard,davidt/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,brennie/reviewboard,sgallagher/reviewboard,davidt/reviewboard,sgallagher/reviewboard,davidt/reviewboard,brennie/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,brennie/reviewboard,reviewboard/reviewboard
--- +++ @@ -34,6 +34,7 @@ feature_id = 'reviews.status_updates' name = _('Status Updates') + level = FeatureLevel.STABLE summary = _('A way for external tools to do checks on a review request ' 'and report the results of those checks.')
f413f5bc2015843a4e74dd969d56bc54f9dbba4e
deconstrst/__init__.py
deconstrst/__init__.py
# -*- coding: utf-8 -*- import sys from sphinxwrapper import build __author__ = 'Ash Wilson' __email__ = 'ash.wilson@rackspace.com' __version__ = '0.1.0' def main(): sys.exit(build(sys.argv)) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- import sys from deconstrst import build __author__ = 'Ash Wilson' __email__ = 'ash.wilson@rackspace.com' __version__ = '0.1.0' def main(): sys.exit(build(sys.argv)) if __name__ == '__main__': main()
Fix an import that missed the renaming sweep.
Fix an import that missed the renaming sweep.
Python
apache-2.0
deconst/preparer-sphinx,ktbartholomew/preparer-sphinx,smashwilson/deconst-preparer-sphinx,deconst/preparer-sphinx,ktbartholomew/preparer-sphinx
--- +++ @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- import sys -from sphinxwrapper import build +from deconstrst import build __author__ = 'Ash Wilson' __email__ = 'ash.wilson@rackspace.com'
68e4cddb0e66bf75f13c0d9ee0e8064acc2c1cd1
heliosinstitution/__init__.py
heliosinstitution/__init__.py
""" Script for create/update app permissions after migrations Author: Shirlei Chaves - shirlei@gmail.com Version 1.0 - 03/2015 with ideas from here: http://www.geekrant.org/2014/04/19/programmatically-create-django-security-groups/ and here: http://devwithpassion.com/felipe/south-django-permissions/ """ from south.signals import post_migrate from django.db.models import signals from django.contrib.auth.models import Group, Permission import models verbosity = 2 def update_permissions_after_migration(**kwargs): """ Permissions must exist in app model, otherwise an error will be thrown """ heliosinstitution_group_permissions = { "Institution Admin" : [ "delegate_institution_mngt", "revoke_institution_mngt", "delegate_election_mngt", "revoke_election_mngt" ], # "Election Admin": [ # "admin_election", # ] } if verbosity>0: print "Initialising data post_migrate" for group in heliosinstitution_group_permissions: role, created = Group.objects.get_or_create(name=group) if verbosity > 1 and created: print 'Creating group', group for perm in heliosinstitution_group_permissions[group]: role.permissions.add(Permission.objects.get(codename=perm)) if verbosity > 1: print 'Permitting', group, 'to', perm role.save() post_migrate.connect(update_permissions_after_migration)
Add initial update permissions after migration
Add initial update permissions after migration
Python
apache-2.0
shirlei/helios-server,shirlei/helios-server,shirlei/helios-server,shirlei/helios-server,shirlei/helios-server
--- +++ @@ -0,0 +1,48 @@ +""" +Script for create/update app permissions after migrations +Author: Shirlei Chaves - shirlei@gmail.com +Version 1.0 - 03/2015 + +with ideas from here: +http://www.geekrant.org/2014/04/19/programmatically-create-django-security-groups/ +and here: +http://devwithpassion.com/felipe/south-django-permissions/ + +""" +from south.signals import post_migrate +from django.db.models import signals +from django.contrib.auth.models import Group, Permission +import models + +verbosity = 2 +def update_permissions_after_migration(**kwargs): + """ + Permissions must exist in app model, otherwise an error + will be thrown + """ + heliosinstitution_group_permissions = { + "Institution Admin" : [ + "delegate_institution_mngt", + "revoke_institution_mngt", + "delegate_election_mngt", + "revoke_election_mngt" + ], +# "Election Admin": [ +# "admin_election", +# ] + + } + if verbosity>0: + print "Initialising data post_migrate" + for group in heliosinstitution_group_permissions: + role, created = Group.objects.get_or_create(name=group) + if verbosity > 1 and created: + print 'Creating group', group + for perm in heliosinstitution_group_permissions[group]: + role.permissions.add(Permission.objects.get(codename=perm)) + if verbosity > 1: + print 'Permitting', group, 'to', perm + role.save() + + +post_migrate.connect(update_permissions_after_migration)
3aa233e0fcf7dea1e089a4bf03197c31b098b5de
apitest.py
apitest.py
#!/usr/bin/env python3 import time import machinepark as mp if __name__ == "__main__": machine_ids = mp.machines_list() sample = {'env': {} } for mid in machine_ids: sample[mid] = {} for i in range(0, 10): start = time.time() mp.query_sample(machine_ids, sample) # Measure timing end = time.time() duration = end - start #print(sample) print('Total machine count {0}'.format(len(machine_ids))) print('Completed in {0} seconds. {1} records per second'.format(duration, len(machine_ids) / duration))
#!/usr/bin/env python3 import time import machinepark as mp if __name__ == "__main__": machine_ids = mp.machines_list() sample = {'envsensor': {} } for mid in machine_ids: sample[mid] = {} for i in range(0, 10): start = time.time() mp.query_sample(machine_ids, sample) # Measure timing end = time.time() duration = end - start #print(sample) print('Total machine count {0}'.format(len(machine_ids))) print('Completed in {0} seconds. {1} records per second'.format(duration, len(machine_ids) / duration))
Adjust the name of environment sensor
Adjust the name of environment sensor
Python
apache-2.0
andreynech/iotchallenge,andreynech/iotchallenge
--- +++ @@ -8,7 +8,7 @@ machine_ids = mp.machines_list() - sample = {'env': {} } + sample = {'envsensor': {} } for mid in machine_ids: sample[mid] = {}
44e64c4f0c0296015fb124cddf87bea2188559fe
stagpy/__main__.py
stagpy/__main__.py
# PYTHON_ARGCOMPLETE_OK """The stagpy module is callable""" from . import config def main(): """StagPy entry point""" args = config.parse_args() args.func(args) if __name__ == '__main__': main()
# PYTHON_ARGCOMPLETE_OK """The stagpy module is callable""" import signal import sys from . import config def sigint_handler(*_): """SIGINT handler""" print('\nSo long, and thanks for all the fish.') sys.exit() def main(): """StagPy entry point""" signal.signal(signal.SIGINT, sigint_handler) args = config.parse_args() args.func(args) if __name__ == '__main__': main()
Handle SIGINT in a clean way
Handle SIGINT in a clean way
Python
apache-2.0
StagPython/StagPy
--- +++ @@ -1,11 +1,20 @@ # PYTHON_ARGCOMPLETE_OK """The stagpy module is callable""" +import signal +import sys from . import config + + +def sigint_handler(*_): + """SIGINT handler""" + print('\nSo long, and thanks for all the fish.') + sys.exit() def main(): """StagPy entry point""" + signal.signal(signal.SIGINT, sigint_handler) args = config.parse_args() args.func(args)
e2574515d9879a5aa023df949031370969dc896c
runtests.py
runtests.py
#!/usr/bin/env python import os import sys import six if six.PY2: import unittest2 as unittest else: import unittest def main(): # Configure python path parent = os.path.dirname(os.path.abspath(__file__)) if not parent in sys.path: sys.path.insert(0, parent) # Discover tests os.environ['DJANGO_SETTINGS_MODULE'] = 'djedi.tests.settings' unittest.defaultTestLoader.discover('djedi') import django if hasattr(django, "setup"): django.setup() # Run tests import django if hasattr(django, 'setup'): django.setup() if django.VERSION < (1,7): from django.test.simple import DjangoTestSuiteRunner as TestRunner else: from django.test.runner import DiscoverRunner as TestRunner runner = TestRunner(verbosity=1, interactive=True, failfast=False) exit_code = runner.run_tests(['djedi']) sys.exit(exit_code) if __name__ == '__main__': main()
#!/usr/bin/env python import os import sys import six if six.PY2: import unittest2 as unittest else: import unittest def main(): # Configure python path parent = os.path.dirname(os.path.abspath(__file__)) if not parent in sys.path: sys.path.insert(0, parent) # Discover tests os.environ['DJANGO_SETTINGS_MODULE'] = 'djedi.tests.settings' unittest.defaultTestLoader.discover('djedi') # Run tests import django if hasattr(django, 'setup'): django.setup() if django.VERSION < (1,7): from django.test.simple import DjangoTestSuiteRunner as TestRunner else: from django.test.runner import DiscoverRunner as TestRunner runner = TestRunner(verbosity=1, interactive=True, failfast=False) exit_code = runner.run_tests(['djedi']) sys.exit(exit_code) if __name__ == '__main__': main()
Remove extra setup() from rebase.
Remove extra setup() from rebase.
Python
bsd-3-clause
andreif/djedi-cms,andreif/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms,andreif/djedi-cms,5monkeys/djedi-cms
--- +++ @@ -19,11 +19,6 @@ os.environ['DJANGO_SETTINGS_MODULE'] = 'djedi.tests.settings' unittest.defaultTestLoader.discover('djedi') - import django - - if hasattr(django, "setup"): - django.setup() - # Run tests import django if hasattr(django, 'setup'):
fdf132c0b7cba6bd00f855b54ab354462c924b5c
nn/embedding/bidirectional_embeddings_to_embedding.py
nn/embedding/bidirectional_embeddings_to_embedding.py
import functools import tensorflow as tf from ..util import static_shape, funcname_scope from .embeddings_to_embedding import embeddings_to_embedding @funcname_scope def bidirectional_embeddings_to_embedding(child_embeddings, **kwargs): child_embeddings_to_embedding = functools.partial( embeddings_to_embedding, **kwargs) with tf.variable_scope("forward"): forward_embedding = child_embeddings_to_embedding(child_embeddings) with tf.variable_scope("backward"): backward_embedding = child_embeddings_to_embedding( _reverse_embedding_sequence(child_embeddings)) return _concat_embeddings(forward_embedding, backward_embedding) def _concat_embeddings(*embeddings): return tf.concat(1, list(embeddings)) def _reverse_embedding_sequence(embedding_sequence): embedding_dim = 1 return tf.concat(embedding_dim, list(reversed(tf.split( embedding_dim, static_shape(embedding_sequence)[embedding_dim], embedding_sequence))))
import functools import tensorflow as tf from ..util import static_shape, static_rank, funcname_scope from .embeddings_to_embedding import embeddings_to_embedding @funcname_scope def bidirectional_embeddings_to_embedding(child_embeddings, **kwargs): child_embeddings_to_embedding = functools.partial( embeddings_to_embedding, **kwargs) with tf.variable_scope("forward"): forward_embedding = child_embeddings_to_embedding(child_embeddings) with tf.variable_scope("backward"): backward_embedding = child_embeddings_to_embedding( _reverse_embedding_sequence(child_embeddings)) return _concat_embeddings(forward_embedding, backward_embedding) def _concat_embeddings(*embeddings): return tf.concat(1, list(embeddings)) def _reverse_embedding_sequence(embedding_sequence): assert static_rank(embedding_sequence) == 3 return tf.reverse(embedding_sequence, [False, True, False])
Use tf.reverse function to reverse embedding sequences
Use tf.reverse function to reverse embedding sequences
Python
unlicense
raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten
--- +++ @@ -1,7 +1,7 @@ import functools import tensorflow as tf -from ..util import static_shape, funcname_scope +from ..util import static_shape, static_rank, funcname_scope from .embeddings_to_embedding import embeddings_to_embedding @@ -28,9 +28,5 @@ def _reverse_embedding_sequence(embedding_sequence): - embedding_dim = 1 - return tf.concat(embedding_dim, - list(reversed(tf.split( - embedding_dim, - static_shape(embedding_sequence)[embedding_dim], - embedding_sequence)))) + assert static_rank(embedding_sequence) == 3 + return tf.reverse(embedding_sequence, [False, True, False])
a576432d045d14308012a4eaa6eaeb12fe004a37
scarplet.py
scarplet.py
""" Functions for determinig best-fit template parameters by convolution with a grid """
""" Functions for determinig best-fit template parameters by convolution with a grid """ import dem import WindowedTemplate as wt import numpy as np from scipy import signal def calculate_best_fit_parameters(dem, template_function, **kwargs): template_args = parse_args(**kwargs) num_angles = 180/ang_stepsize num_ages = (age_max - age_min)/age_stepsize orientations = np.linspace(-np.pi/2, np.pi/2, num_angles) ages = np.linspace(age_min, age_max, num_ages) for this_alpha in orientations: for this_age in ages: template_args['alpha'] = this_alpha template_args['age'] = this_age curv = dem._calculate_directional_laplacian(this_alpha) amplitude, snr = match_template(curv, template_function, template_args) if 'noiselevel' in kwargs: snr = snr/noiselevel best_snr = (best_snr > snr)*best_snr + (best_snr < snr)*snr best_alpha = (best_snr > snr)*best_alpha + (best_snr < snr)*this_alpha best_age = (best_snr > snr)*best_age + (best_snr < snr)*this_age
Add generic grid search function
Add generic grid search function
Python
mit
rmsare/scarplet,stgl/scarplet
--- +++ @@ -1,4 +1,34 @@ """ Functions for determinig best-fit template parameters by convolution with a grid """ +import dem +import WindowedTemplate as wt +import numpy as np +from scipy import signal +def calculate_best_fit_parameters(dem, template_function, **kwargs): + + template_args = parse_args(**kwargs) + + num_angles = 180/ang_stepsize + num_ages = (age_max - age_min)/age_stepsize + orientations = np.linspace(-np.pi/2, np.pi/2, num_angles) + ages = np.linspace(age_min, age_max, num_ages) + + for this_alpha in orientations: + for this_age in ages: + + template_args['alpha'] = this_alpha + template_args['age'] = this_age + + curv = dem._calculate_directional_laplacian(this_alpha) + + amplitude, snr = match_template(curv, template_function, template_args) + + if 'noiselevel' in kwargs: + snr = snr/noiselevel + + best_snr = (best_snr > snr)*best_snr + (best_snr < snr)*snr + best_alpha = (best_snr > snr)*best_alpha + (best_snr < snr)*this_alpha + best_age = (best_snr > snr)*best_age + (best_snr < snr)*this_age +
90d6c6ed4f2846ef009ee95217a69cc061623135
meinberlin/apps/offlineevents/templatetags/offlineevent_tags.py
meinberlin/apps/offlineevents/templatetags/offlineevent_tags.py
from django import template from adhocracy4.modules.models import Module from adhocracy4.phases.models import Phase from meinberlin.apps.offlineevents.models import OfflineEvent register = template.Library() @register.assignment_tag def offlineevents_and_modules_sorted(project): modules = list(project.module_set.all()) events = list(OfflineEvent.objects.filter(project=project)) res = modules + events res_sorted = sorted( res, key=lambda x: x.first_phase_start_date if isinstance(x, Module) else x.date) return res_sorted @register.filter def is_phase(obj): return isinstance(obj, Phase) @register.filter def is_module(obj): return isinstance(obj, Module) @register.filter def is_offlineevent(obj): return isinstance(obj, OfflineEvent)
from functools import cmp_to_key from django import template from adhocracy4.modules.models import Module from adhocracy4.phases.models import Phase from meinberlin.apps.offlineevents.models import OfflineEvent register = template.Library() @register.assignment_tag def offlineevents_and_modules_sorted(project): modules = list(project.module_set.all()) events = list(OfflineEvent.objects.filter(project=project)) res = modules + events return sorted(res, key=cmp_to_key(_cmp)) def _cmp(x, y): x = x.first_phase_start_date if isinstance(x, Module) else x.date if x is None: return 1 y = y.first_phase_start_date if isinstance(y, Module) else y.date if y is None: return -1 return (x > y) - (y < x) @register.filter def is_phase(obj): return isinstance(obj, Phase) @register.filter def is_module(obj): return isinstance(obj, Module) @register.filter def is_offlineevent(obj): return isinstance(obj, OfflineEvent)
Sort modules without start dates to the future
Sort modules without start dates to the future Modules without a start date (phases dates are not set) will be sorted after every other module or offlineevent.
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
--- +++ @@ -1,3 +1,5 @@ +from functools import cmp_to_key + from django import template from adhocracy4.modules.models import Module @@ -12,10 +14,19 @@ modules = list(project.module_set.all()) events = list(OfflineEvent.objects.filter(project=project)) res = modules + events - res_sorted = sorted( - res, key=lambda x: x.first_phase_start_date if - isinstance(x, Module) else x.date) - return res_sorted + return sorted(res, key=cmp_to_key(_cmp)) + + +def _cmp(x, y): + x = x.first_phase_start_date if isinstance(x, Module) else x.date + if x is None: + return 1 + + y = y.first_phase_start_date if isinstance(y, Module) else y.date + if y is None: + return -1 + + return (x > y) - (y < x) @register.filter
b2f6d9c5fec4316dbceb25bd91cb5831065c1957
string/compress.py
string/compress.py
# Compress string using counts of repeated characters def compress_str(str): output = "" curr_char = "" char_count = "" for i in str: if curr_char != str[i]: output = output + curr_char + char_count # add new unique character and its count to our output curr_char = str[i] # move on to the next character in string char_count = 1 # reset count to 1 else: # add to repeated count if there is a match char_count += 1
# Compress string using counts of repeated characters def compress_str(string): output = "" char_count = 1 # add first character output += string[0] for i in range(len(string)-1): # doesn't do character count for last group of a unique character if string[i] == string[i+1]: char_count += 1 else: output += str(char_count) + string[i+1] # add count and next unique character char_count = 1 # reset character count # account for count of last character output += str(char_count) print output # test cases compress_str("ssssssss") # prints "s8" compress_str("abbcccdddd") # prints "a1b2c3d4"
Rewrite method and add test cases
Rewrite method and add test cases
Python
mit
derekmpham/interview-prep,derekmpham/interview-prep
--- +++ @@ -1,15 +1,25 @@ # Compress string using counts of repeated characters -def compress_str(str): +def compress_str(string): output = "" - curr_char = "" - char_count = "" + char_count = 1 - for i in str: + # add first character + output += string[0] - if curr_char != str[i]: - output = output + curr_char + char_count # add new unique character and its count to our output - curr_char = str[i] # move on to the next character in string - char_count = 1 # reset count to 1 - else: # add to repeated count if there is a match + for i in range(len(string)-1): # doesn't do character count for last group of a unique character + if string[i] == string[i+1]: char_count += 1 + else: + output += str(char_count) + string[i+1] # add count and next unique character + char_count = 1 # reset character count + + # account for count of last character + output += str(char_count) + + print output + + +# test cases +compress_str("ssssssss") # prints "s8" +compress_str("abbcccdddd") # prints "a1b2c3d4"
a61148a71a022b6877af0445f799f3dfa3eb6136
BinPy/examples/source/algorithms/make_boolean_function_example.py
BinPy/examples/source/algorithms/make_boolean_function_example.py
# coding: utf-8 ### An example to demostrate the usage of make boolean function. # In[1]: from __future__ import print_function from BinPy.algorithms.makebooleanfunction import * # In[2]: # Usage of make_boolean() function logical_expression, gate_form = make_boolean(['A', 'B', 'C'], [1, 4, 7], minterms=True) # In[3]: # Print the logical function print(logical_expression) # In[4]: # Print the gate form print(gate_form) # In[5]: # Another example logical_expression, gate_form = make_boolean(['A', 'B', 'C', 'D'], [1, 4, 7, 0], maxterms=True) # In[6]: # Print the logical function print(logical_expression) # In[7]: # Print the gate form print(gate_form)
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <headingcell level=2> # An example to demostrate the usage of make boolean function. # <codecell> from __future__ import print_function from BinPy.algorithms.makebooleanfunction import * # <codecell> # Usage of make_boolean() function logical_expression, gate_form = make_boolean(['A', 'B', 'C'], [1, 4, 7], minterms=True) # <codecell> # Print the logical function print(logical_expression) # <codecell> # Print the gate form print(gate_form) # <codecell> # Another example logical_expression, gate_form = make_boolean(['A', 'B', 'C', 'D'], [1, 4, 7, 0], maxterms=True) # <codecell> # Print the logical function print(logical_expression) # <codecell> # Print the gate form print(gate_form)
Update python sources for algorithms
Update python sources for algorithms
Python
bsd-3-clause
daj0ker/BinPy,rajathkumarmp/BinPy,yashu-seth/BinPy,BinPy/BinPy,rajathkumarmp/BinPy,BinPy/BinPy,daj0ker/BinPy,yashu-seth/BinPy
--- +++ @@ -1,45 +1,41 @@ +# -*- coding: utf-8 -*- +# <nbformat>3.0</nbformat> -# coding: utf-8 +# <headingcell level=2> -### An example to demostrate the usage of make boolean function. +# An example to demostrate the usage of make boolean function. -# In[1]: +# <codecell> from __future__ import print_function from BinPy.algorithms.makebooleanfunction import * - -# In[2]: +# <codecell> # Usage of make_boolean() function logical_expression, gate_form = make_boolean(['A', 'B', 'C'], [1, 4, 7], minterms=True) - -# In[3]: +# <codecell> # Print the logical function print(logical_expression) - -# In[4]: +# <codecell> # Print the gate form print(gate_form) - -# In[5]: +# <codecell> # Another example logical_expression, gate_form = make_boolean(['A', 'B', 'C', 'D'], [1, 4, 7, 0], maxterms=True) - -# In[6]: +# <codecell> # Print the logical function print(logical_expression) - -# In[7]: +# <codecell> # Print the gate form print(gate_form)
519d1f23682b6815c41c2ac34df775ea2e333eab
jasmin_notifications/views.py
jasmin_notifications/views.py
""" Module defining views for the JASMIN notifications app. """ __author__ = "Matt Pryor" __copyright__ = "Copyright 2015 UK Science and Technology Facilities Council" from django.views.decorators.http import require_safe from django import http from django.shortcuts import redirect from django.utils import timezone from django.contrib.auth.decorators import login_required from .models import Notification, UserNotification def _handle_notification(request, notification): if not notification.followed_at: notification.followed_at = timezone.now() notification.save() return redirect(notification.link) @login_required def _handle_user_notification(request, notification): # For user notifications, the user must match the logged in user if request.user != notification.user: raise http.Http404("Notification does not exist") return _handle_notification(request, notification) @require_safe def follow(request, uuid): """ Handler for ``/<uuid>/``. Responds to GET requests only. Marks the specified notification as read before redirecting to the link. """ # First, try to find a notification with the UUID notification = Notification.objects.filter(uuid = uuid).first() if not notification: raise http.Http404("Notification does not exist") # If we have a user notification, the user must match the logged in user if isinstance(notification, UserNotification): return _handle_user_notification(request, notification) else: return _handle_notification(request, notification)
""" Module defining views for the JASMIN notifications app. """ __author__ = "Matt Pryor" __copyright__ = "Copyright 2015 UK Science and Technology Facilities Council" from django.views.decorators.http import require_safe from django import http from django.shortcuts import redirect from django.utils import timezone from django.contrib.auth.decorators import login_required from .models import Notification, UserNotification @require_safe def follow(request, uuid): """ Handler for ``/<uuid>/``. Responds to GET requests only. Marks all the notifications as read that have the same user and link before redirecting to the link. """ # First, try to find a notification with the UUID notification = Notification.objects.filter(uuid = uuid).first() if not notification: raise http.Http404("Notification does not exist") if isinstance(notification, UserNotification): # For user notifications, the user must match the logged in user if request.user != notification.user: raise http.Http404("Notification does not exist") # Update the followed_at time for all the notifications for the same user # and link UserNotification.objects.filter(link = notification.link, user = notification.user, followed_at__isnull = True) \ .update(followed_at = timezone.now()) else: # For email notifications, just update this notification if not notification.followed_at: notification.followed_at = timezone.now() notification.save() return redirect(notification.link)
Mark all similar notifications as followed when following one
Mark all similar notifications as followed when following one
Python
mit
cedadev/jasmin-notifications,cedadev/jasmin-notifications
--- +++ @@ -14,19 +14,6 @@ from .models import Notification, UserNotification -def _handle_notification(request, notification): - if not notification.followed_at: - notification.followed_at = timezone.now() - notification.save() - return redirect(notification.link) - -@login_required -def _handle_user_notification(request, notification): - # For user notifications, the user must match the logged in user - if request.user != notification.user: - raise http.Http404("Notification does not exist") - return _handle_notification(request, notification) - @require_safe def follow(request, uuid): """ @@ -34,14 +21,26 @@ Responds to GET requests only. - Marks the specified notification as read before redirecting to the link. + Marks all the notifications as read that have the same user and link before + redirecting to the link. """ # First, try to find a notification with the UUID notification = Notification.objects.filter(uuid = uuid).first() if not notification: raise http.Http404("Notification does not exist") - # If we have a user notification, the user must match the logged in user if isinstance(notification, UserNotification): - return _handle_user_notification(request, notification) + # For user notifications, the user must match the logged in user + if request.user != notification.user: + raise http.Http404("Notification does not exist") + # Update the followed_at time for all the notifications for the same user + # and link + UserNotification.objects.filter(link = notification.link, + user = notification.user, + followed_at__isnull = True) \ + .update(followed_at = timezone.now()) else: - return _handle_notification(request, notification) + # For email notifications, just update this notification + if not notification.followed_at: + notification.followed_at = timezone.now() + notification.save() + return redirect(notification.link)
ccdb5001a450859ae9eb85f1c2c90a9a80fa0ce1
eforge/wiki/urls.py
eforge/wiki/urls.py
# -*- coding: utf-8 -*- # EForge project management system, Copyright © 2010, Element43 # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # from django.conf.urls.defaults import * patterns = patterns('eforge.wiki.views', url(r'^(?P<name>[a-zA-Z_/ ]+)$', 'wiki_page', name='wiki-page'), url(r'^$', 'wiki_page', name='wiki-home'), )
# -*- coding: utf-8 -*- # EForge project management system, Copyright © 2010, Element43 # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # from django.conf.urls.defaults import * patterns = patterns('eforge.wiki.views', url(r'^(?P<name>[\w]+)$', 'wiki_page', name='wiki-page'), url(r'^$', 'wiki_page', name='wiki-home'), )
Update wiki to be a little more flexible with naming
Update wiki to be a little more flexible with naming
Python
isc
oshepherd/eforge,oshepherd/eforge,oshepherd/eforge
--- +++ @@ -17,6 +17,6 @@ from django.conf.urls.defaults import * patterns = patterns('eforge.wiki.views', - url(r'^(?P<name>[a-zA-Z_/ ]+)$', 'wiki_page', name='wiki-page'), - url(r'^$', 'wiki_page', name='wiki-home'), + url(r'^(?P<name>[\w]+)$', 'wiki_page', name='wiki-page'), + url(r'^$', 'wiki_page', name='wiki-home'), )
98393be0011f4e4227e6f5e86db68533af8b78e0
webserver/profiles/models.py
webserver/profiles/models.py
from django.db import models from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from django.contrib.auth.models import User from django.conf import settings import markdown import bleach class UserProfile(models.Model): user = models.OneToOneField(User) about_me = models.TextField() rendered_about_me = models.TextField(editable=False, null=True) @models.permalink def get_absolute_url(self): return ('view_profile', (), {'username': self.user.username}) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(pre_save, sender=UserProfile) def user_profile_pre_save(sender, instance, **kwargs): # Render the about_me field as HTML instead of markdown rendered = markdown.markdown(instance.about_me, safe_mode='escape') clean_rendered = bleach.clean(rendered, tags=settings.ALLOWED_HTML_TAGS, attributes=settings.ALLOWED_HTML_ATTRS) instance.rendered_about_me = clean_rendered
from django.db import models from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from django.contrib.auth.models import User from django.conf import settings from django.core.validators import MaxLengthValidator import markdown import bleach class UserProfile(models.Model): user = models.OneToOneField(User) about_me = models.TextField(validators=[MaxLengthValidator(500)]) rendered_about_me = models.TextField(editable=False, null=True) @models.permalink def get_absolute_url(self): return ('view_profile', (), {'username': self.user.username}) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(pre_save, sender=UserProfile) def user_profile_pre_save(sender, instance, **kwargs): # Render the about_me field as HTML instead of markdown rendered = markdown.markdown(instance.about_me, safe_mode='escape') clean_rendered = bleach.clean(rendered, tags=settings.ALLOWED_HTML_TAGS, attributes=settings.ALLOWED_HTML_ATTRS) instance.rendered_about_me = clean_rendered
Add maximum length validator to about_me
Add maximum length validator to about_me
Python
bsd-3-clause
siggame/webserver,siggame/webserver,siggame/webserver
--- +++ @@ -3,6 +3,7 @@ from django.dispatch import receiver from django.contrib.auth.models import User from django.conf import settings +from django.core.validators import MaxLengthValidator import markdown import bleach @@ -11,7 +12,7 @@ class UserProfile(models.Model): user = models.OneToOneField(User) - about_me = models.TextField() + about_me = models.TextField(validators=[MaxLengthValidator(500)]) rendered_about_me = models.TextField(editable=False, null=True)
0d37ada90d4648f1e45cc3aa95dace014a26c599
components/includes/utilities.py
components/includes/utilities.py
import random import json import SocketExtend as SockExt import config as conf import parser as p def ping(sock): try: rand = random.randint(1, 99999) data = {'request':'ping', 'contents': {'value':rand}} SockExt.send_msg(sock, json.dumps(data)) result = json.loads(SockExt.recv_msg(sock)) if result['return'] == rand: return True else: return False except Exception as e: print "Exception while pinging: ", e return False def multiping(port, auths=[]): result = True for a_ip in auths: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #s.settimeout(120.0) sock.connect((a_ip, int(port))) if not ping(sock): result = False sock.shutdown(socket.SHUT_RDWR) sock.close() return result def alive(port, machines=[]): attempted = 0 success = False while (attempted < conf.tries): try: if utilities.multiping(port, machines): success = True print "hey" break except Exception as e: print "ouups" attempted += 1 return success
import random import json import time import SocketExtend as SockExt import config as conf import parser as p def ping(sock): try: rand = random.randint(1, 99999) data = {'request':'ping', 'contents': {'value':rand}} SockExt.send_msg(sock, json.dumps(data)) result = json.loads(SockExt.recv_msg(sock)) if result['return'] == rand: return True else: return False except Exception as e: print "Exception while pinging: ", e return False def multiping(port, auths=[]): result = True for a_ip in auths: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #s.settimeout(120.0) sock.connect((a_ip, int(port))) if not ping(sock): result = False sock.shutdown(socket.SHUT_RDWR) sock.close() return result def alive(port, machines=[]): attempted = 0 success = False while (attempted < conf.tries): try: if utilities.multiping(port, machines): success = True print "hey" break except Exception as e: print "ouups" time.sleep(1) attempted += 1 return success
Clean up, comments, liveness checking, robust data transfer
Clean up, comments, liveness checking, robust data transfer
Python
bsd-2-clause
mavroudisv/Crux
--- +++ @@ -1,5 +1,6 @@ import random import json +import time import SocketExtend as SockExt import config as conf @@ -46,6 +47,7 @@ break except Exception as e: print "ouups" + time.sleep(1) attempted += 1 return success
f4415c9ba2df6f0cd511986d78e454194017db2e
en-2018-04-22-on-incomplete-http-reads-and-the-requests-library-in-python/clients/python/client-with-check.py
en-2018-04-22-on-incomplete-http-reads-and-the-requests-library-in-python/clients/python/client-with-check.py
#!/usr/bin/env python3 # # An HTTP client that checks that the content of the response has at least # Content-Length bytes. # # For requests 2.x (not needed for requests 3.x). # import requests import sys response = requests.get('http://localhost:8080/') if not response.ok: sys.exit('error: HTTP {}'.format(response.status_code)) # Check that we have read all the data as the requests library does not # currently enforce this. expected_length = response.headers.get('Content-Length') if expected_length is not None: # We cannot use len(response.content) as this would not work when the body # of the response was compressed (e.g. when the response has # `Content-Encoding: gzip`). actual_length = response.raw.tell() expected_length = int(expected_length) if actual_length < expected_length: raise IOError( 'incomplete read ({} bytes read, {} more expected)'.format( actual_length, expected_length - actual_length ) ) print(response.headers) print(response.content) print(len(response.content))
#!/usr/bin/env python3 # # An HTTP client that checks that the content of the response has at least # Content-Length bytes. # # For requests 2.x (should not be needed for requests 3.x). # import requests import sys response = requests.get('http://localhost:8080/') if not response.ok: sys.exit('error: HTTP {}'.format(response.status_code)) # Check that we have read all the data as the requests library does not # currently enforce this. expected_length = response.headers.get('Content-Length') if expected_length is not None: # We cannot use len(response.content) as this would not work when the body # of the response was compressed (e.g. when the response has # `Content-Encoding: gzip`). actual_length = response.raw.tell() expected_length = int(expected_length) if actual_length < expected_length: raise IOError( 'incomplete read ({} bytes read, {} more expected)'.format( actual_length, expected_length - actual_length ) ) print(response.headers) print(response.content) print(len(response.content))
Make a statement concerning requests 3.x more precise.
en-2018-04-22: Make a statement concerning requests 3.x more precise. requests 3 has not yet been released, so it may theoretically happen that the fix will be also needed for requests 3.x.
Python
bsd-3-clause
s3rvac/blog,s3rvac/blog,s3rvac/blog,s3rvac/blog
--- +++ @@ -3,7 +3,7 @@ # An HTTP client that checks that the content of the response has at least # Content-Length bytes. # -# For requests 2.x (not needed for requests 3.x). +# For requests 2.x (should not be needed for requests 3.x). # import requests
c129e600b91ac0c35e26847ef5b1df75a1dec695
fmn/filters/generic.py
fmn/filters/generic.py
# Generic filters for FMN import fedmsg def user_filter(config, message, fasnick=None, *args, **kw): """ Filters the messages by the user that performed the action. Use this filter to filter out messages that are associated with a specified user. """ fasnick = kw.get('fasnick', fasnick) if fasnick: return fasnick in fedmsg.meta.msg2usernames(message)
# Generic filters for FMN import fedmsg def user_filter(config, message, fasnick=None, *args, **kw): """ All messages of user Use this filter to filter out messages that are associated with a specified user. """ fasnick = kw.get('fasnick', fasnick) if fasnick: return fasnick in fedmsg.meta.msg2usernames(message)
Update the documentation title for the user_filter
Update the documentation title for the user_filter
Python
lgpl-2.1
jeremycline/fmn,jeremycline/fmn,jeremycline/fmn
--- +++ @@ -3,7 +3,7 @@ def user_filter(config, message, fasnick=None, *args, **kw): - """ Filters the messages by the user that performed the action. + """ All messages of user Use this filter to filter out messages that are associated with a specified user.
12b3c2e99878a586602410a599d18fdebd0f4a3c
jetcomcrawl/modes/items.py
jetcomcrawl/modes/items.py
from bs4 import BeautifulSoup import logging from jetcomcrawl import browser import jetcomcrawl.libs.queue class Worker(object): def __init__(self): self.queue_categories = jetcomcrawl.libs.queue.Queue('queue_categories') self.queue_items = jetcomcrawl.libs.queue.Queue('queue_items') def work(self): '''Keeps running indefinitely, retrieving jobs from sqs''' while True: # TODO: Handle no items left in queue data = self.queue_categories.retrieve() cid = data['cid'] page = data['page'] logging.info('Finding products for category {}, page {}'.format(cid, page)) html = browser.get('https://jet.com/search/results?category={}&page={}'.format(cid, page)) try: soup = BeautifulSoup(html.text, 'html.parser') results = [] for item in soup.find('div', {'class': 'products'}).findAll('div', {'class': 'product mobile'}): url = item.a['href'] uid = url.split('/')[-1] results.append({'uid': uid, 'url': url}) except: logging.info(html.text) raise logging.info('{} products found for category {}, page {}, inserting into sqs'.format(len(results), cid, page)) self.queue_items.insert_bulk(results) self.queue_categories.remove_processed()
from bs4 import BeautifulSoup import logging from jetcomcrawl import browser import jetcomcrawl.libs.queue class Worker(object): def __init__(self): self.queue_categories = jetcomcrawl.libs.queue.Queue('queue_categories') self.queue_items = jetcomcrawl.libs.queue.Queue('queue_items') def work(self): '''Keeps running indefinitely, retrieving jobs from sqs''' while True: # TODO: Handle no items left in queue data = self.queue_categories.retrieve() cid = data['cid'] page = data['page'] logging.info('Finding products for category {}, page {}'.format(cid, page)) html = browser.get('https://jet.com/search/results?category={}&page={}'.format(cid, page)) try: soup = BeautifulSoup(html.text, 'html.parser') if soup.find('div', {'class': 'no-results'}): logging.info('Skipping process of {}:{}. No results available'.format(cid, page)) else: results = [] for item in soup.find('div', {'class': 'products'}).findAll('div', {'class': 'product mobile'}): url = item.a['href'] uid = url.split('/')[-1] results.append({'uid': uid, 'url': url}) except: logging.info(html.text) raise logging.info('{} products found for category {}, page {}, inserting into sqs'.format(len(results), cid, page)) self.queue_items.insert_bulk(results) self.queue_categories.remove_processed()
Handle no results from category page
Handle no results from category page
Python
mit
tdickman/jetcom-crawl
--- +++ @@ -22,11 +22,14 @@ try: soup = BeautifulSoup(html.text, 'html.parser') - results = [] - for item in soup.find('div', {'class': 'products'}).findAll('div', {'class': 'product mobile'}): - url = item.a['href'] - uid = url.split('/')[-1] - results.append({'uid': uid, 'url': url}) + if soup.find('div', {'class': 'no-results'}): + logging.info('Skipping process of {}:{}. No results available'.format(cid, page)) + else: + results = [] + for item in soup.find('div', {'class': 'products'}).findAll('div', {'class': 'product mobile'}): + url = item.a['href'] + uid = url.split('/')[-1] + results.append({'uid': uid, 'url': url}) except: logging.info(html.text) raise
2515a49f3ceae6de3e3de68bac9ec3f12fc2eba8
redbot/message/headers/x_pad.py
redbot/message/headers/x_pad.py
#!/usr/bin/env python from redbot.message import headers class x_pad(headers.HttpHeader): canonical_name = "X-Pad" description = """\ The `%(field_name)s` header is used to "pad" the response header size. Very old versions of the Netscape browser had a bug whereby a response whose headers were exactly 256 or 257 bytes long, the browser would consider the response (e.g., an image) invalid. Since the affected browsers (specifically, Netscape 2.x, 3.x and 4.0 up to beta 2) are no longer widely used, it's probably safe to omit this header.""" list_header = False deprecated = False valid_in_requests = False valid_in_responses = True
#!/usr/bin/env python from redbot.message import headers class x_pad(headers.HttpHeader): canonical_name = "X-Pad" description = """\ The `%(field_name)s` header is used to "pad" the response header size. Very old versions of the Netscape browser had a bug whereby a response whose headers were exactly 256 or 257 bytes long, the browser would consider the response (e.g., an image) invalid. Since the affected browsers (specifically, Netscape 2.x, 3.x and 4.0 up to beta 2) are no longer widely used, it's safe to omit this header.""" list_header = False deprecated = False valid_in_requests = False valid_in_responses = True
Update x-pad; it really isn't necessary
Update x-pad; it really isn't necessary Fixes #229
Python
mit
mnot/redbot,mnot/redbot,mnot/redbot
--- +++ @@ -12,7 +12,7 @@ 256 or 257 bytes long, the browser would consider the response (e.g., an image) invalid. Since the affected browsers (specifically, Netscape 2.x, 3.x and 4.0 up to beta 2) are no longer - widely used, it's probably safe to omit this header.""" + widely used, it's safe to omit this header.""" list_header = False deprecated = False valid_in_requests = False
fe7e841c166ebc227e00baca4c8a72fb04ce0693
src/mcedit2/util/directories.py
src/mcedit2/util/directories.py
import os import sys def getUserFilesDirectory(): exe = sys.executable if hasattr(sys, 'frozen'): folder = os.path.dirname(exe) else: script = sys.argv[0] if exe.endswith("python") or exe.endswith("python.exe"): folder = os.path.dirname(script) else: folder = os.path.dirname(exe) dataDir = os.path.join(folder, "MCEdit User Data") if not os.path.exists(dataDir): os.makedirs(dataDir) return dataDir
import os import sys def getUserFilesDirectory(): exe = sys.executable if hasattr(sys, 'frozen'): folder = os.path.dirname(exe) else: script = sys.argv[0] if exe.endswith("python") or exe.endswith("python.exe"): folder = os.path.dirname(os.path.dirname(os.path.dirname(script))) # from src/mcedit, ../../ else: folder = os.path.dirname(exe) dataDir = os.path.join(folder, "MCEdit User Data") if not os.path.exists(dataDir): os.makedirs(dataDir) return dataDir
Put data folder in ./ instead of ./src/mcedit when running from source (xxx work on this)
Put data folder in ./ instead of ./src/mcedit when running from source (xxx work on this)
Python
bsd-3-clause
Rubisk/mcedit2,vorburger/mcedit2,vorburger/mcedit2,Rubisk/mcedit2
--- +++ @@ -8,7 +8,7 @@ else: script = sys.argv[0] if exe.endswith("python") or exe.endswith("python.exe"): - folder = os.path.dirname(script) + folder = os.path.dirname(os.path.dirname(os.path.dirname(script))) # from src/mcedit, ../../ else: folder = os.path.dirname(exe)
72dcd015a001dc86cde96d35e5f25f88904f9715
reviewboard/hostingsvcs/fake.py
reviewboard/hostingsvcs/fake.py
from __future__ import unicode_literals from reviewboard.hostingsvcs.service import HostingService class FakeHostingService(HostingService): """A hosting service that is not provided by Review Board. Fake hosting services are intended to be used to advertise for Beanbag, Inc.'s Power Pack extension. """ hosting_service_id = None class FakeAWSCodeCommitHostingService(FakeHostingService): name = 'AWS CodeCommit' supported_scmtools = ['Git'] hosting_service_id = 'aws-codecommit' class FakeBitbucketServerHostingService(FakeHostingService): name = 'Bitbucket Server' supported_scmtools = ['Git'] hosting_service_id = 'bitbucket-server' class FakeGitHubEnterpriseHostingService(FakeHostingService): name = 'GitHub Enterprise' supported_scmtools = ['Git'] hosting_service_id = 'github-enterprise' class FakeVisualStudioTeamServicesHostingService(FakeHostingService): name = 'VisualStudio.com' supported_scmtools = [ 'Team Foundation Server', 'Team Foundation Server (git)', ] hosting_service_id = 'visual-studio-online' FAKE_HOSTING_SERVICES = { 'rbpowerpack.hostingsvcs.aws_codecommit.AWSCodeCommit': FakeAWSCodeCommitHostingService, 'rbpowerpack.hostingsvcs.bitbucketserver.BitbucketServer': FakeBitbucketServerHostingService, 'rbpowerpack.hostingsvcs.githubenterprise.GitHubEnterprise': FakeGitHubEnterpriseHostingService, 'rbpowerpack.hostingsvcs.visualstudio.VisualStudioTeamServices': FakeVisualStudioTeamServicesHostingService, }
from __future__ import unicode_literals from reviewboard.hostingsvcs.service import HostingService class FakeHostingService(HostingService): """A hosting service that is not provided by Review Board. Fake hosting services are intended to be used to advertise for Beanbag, Inc.'s Power Pack extension. """ hosting_service_id = None class FakeAWSCodeCommitHostingService(FakeHostingService): name = 'AWS CodeCommit' supported_scmtools = ['Git'] hosting_service_id = 'aws-codecommit' class FakeBitbucketServerHostingService(FakeHostingService): name = 'Bitbucket Server' supported_scmtools = ['Git'] hosting_service_id = 'bitbucket-server' class FakeGitHubEnterpriseHostingService(FakeHostingService): name = 'GitHub Enterprise' supported_scmtools = ['Git'] hosting_service_id = 'github-enterprise' class FakeVisualStudioTeamServicesHostingService(FakeHostingService): name = 'VisualStudio.com' supported_scmtools = [ 'Team Foundation Server', 'Team Foundation Server (git)', ] hosting_service_id = 'visual-studio-online' FAKE_HOSTING_SERVICES = { 'rbpowerpack.hostingsvcs.aws_codecommit.AWSCodeCommit': FakeAWSCodeCommitHostingService, 'rbpowerpack.hostingsvcs.bitbucket_server.BitbucketServer': FakeBitbucketServerHostingService, 'rbpowerpack.hostingsvcs.githubenterprise.GitHubEnterprise': FakeGitHubEnterpriseHostingService, 'rbpowerpack.hostingsvcs.visualstudio.VisualStudioTeamServices': FakeVisualStudioTeamServicesHostingService, }
Fix Bitbucket Server appearing twice in the repository list.
Fix Bitbucket Server appearing twice in the repository list. When Power Pack is installed, Bitbucket Server appears twice in the repository form's hosting list. This is because the fake entry was using the wrong module path for Bitbucket Server. This fixes that to use the right path, showing only a single entry. Testing Done: Loaded the repository form. Saw only a single, correct entry. Reviewed at https://reviews.reviewboard.org/r/9822/
Python
mit
chipx86/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,chipx86/reviewboard
--- +++ @@ -43,7 +43,7 @@ FAKE_HOSTING_SERVICES = { 'rbpowerpack.hostingsvcs.aws_codecommit.AWSCodeCommit': FakeAWSCodeCommitHostingService, - 'rbpowerpack.hostingsvcs.bitbucketserver.BitbucketServer': + 'rbpowerpack.hostingsvcs.bitbucket_server.BitbucketServer': FakeBitbucketServerHostingService, 'rbpowerpack.hostingsvcs.githubenterprise.GitHubEnterprise': FakeGitHubEnterpriseHostingService,
2a00e0b25ebbcac58b7e65efbfcd88bd0539c3e7
metakernel/magics/cd_magic.py
metakernel/magics/cd_magic.py
# Copyright (c) Metakernel Development Team. # Distributed under the terms of the Modified BSD License. from metakernel import Magic import os class CDMagic(Magic): def line_cd(self, path): """ %cd PATH - change current directory of session This line magic is used to change the directory of the notebook or console. Note that this is not the same directory as used by the %shell magics. Example: %cd .. """ try: os.chdir(path) retval = os.path.abspath(path) except Exception as e: self.kernel.Error(str(e)) retval = None if retval: self.kernel.Print(retval) def register_magics(kernel): kernel.register_magics(CDMagic)
# Copyright (c) Metakernel Development Team. # Distributed under the terms of the Modified BSD License. from metakernel import Magic import os class CDMagic(Magic): def line_cd(self, path): """ %cd PATH - change current directory of session This line magic is used to change the directory of the notebook or console. Note that this is not the same directory as used by the %shell magics. Example: %cd .. """ path = os.path.expanduser(path) try: os.chdir(path) retval = os.path.abspath(path) except Exception as e: self.kernel.Error(str(e)) retval = None if retval: self.kernel.Print(retval) def register_magics(kernel): kernel.register_magics(CDMagic)
Fix cd magic for ~ paths and add test
Fix cd magic for ~ paths and add test
Python
bsd-3-clause
Calysto/metakernel
--- +++ @@ -20,6 +20,7 @@ Example: %cd .. """ + path = os.path.expanduser(path) try: os.chdir(path) retval = os.path.abspath(path)
21c7232081483c05752e6db3d60692a04d482d24
dakota/tests/test_dakota_base.py
dakota/tests/test_dakota_base.py
#!/usr/bin/env python # # Tests for dakota.dakota_base module. # # Call with: # $ nosetests -sv # # Mark Piper (mark.piper@colorado.edu) import os import filecmp from nose.tools import * from dakota.dakota_base import DakotaBase # Fixtures ------------------------------------------------------------- def setup_module(): """Called before any tests are performed.""" print('\n*** DakotaBase tests') def teardown_module(): """Called after all tests have completed.""" pass # Tests ---------------------------------------------------------------- @raises(TypeError) def test_instantiate(): """Test whether DakotaBase fails to instantiate.""" d = DakotaBase()
#!/usr/bin/env python # # Tests for dakota.dakota_base module. # # Call with: # $ nosetests -sv # # Mark Piper (mark.piper@colorado.edu) from nose.tools import * from dakota.dakota_base import DakotaBase # Helpers -------------------------------------------------------------- class Concrete(DakotaBase): """A subclass of DakotaBase used for testing.""" def __init__(self): DakotaBase.__init__(self) # Fixtures ------------------------------------------------------------- def setup_module(): """Called before any tests are performed.""" print('\n*** DakotaBase tests') global c c = Concrete() def teardown_module(): """Called after all tests have completed.""" pass # Tests ---------------------------------------------------------------- @raises(TypeError) def test_instantiate(): """Test whether DakotaBase fails to instantiate.""" d = DakotaBase() def test_environment_block(): """Test type of environment_block method results.""" s = c.environment_block() assert_true(type(s) is str) def test_method_block(): """Test type of method_block method results.""" s = c.method_block() assert_true(type(s) is str) def test_variables_block(): """Test type of variables_block method results.""" s = c.variables_block() assert_true(type(s) is str) def test_interface_block(): """Test type of interface_block method results.""" s = c.interface_block() assert_true(type(s) is str) def test_responses_block(): """Test type of responses_block method results.""" s = c.responses_block() assert_true(type(s) is str) def test_autogenerate_descriptors(): """Test autogenerate_descriptors method.""" c.n_variables, c.n_responses = 1, 1 c.autogenerate_descriptors() assert_true(len(c.variable_descriptors) == 1) assert_true(len(c.response_descriptors) == 1)
Add tests for dakota.dakota_base module
Add tests for dakota.dakota_base module Make a subclass of DakotaBase to use for testing. Add tests for the "block" sections used to define an input file.
Python
mit
csdms/dakota,csdms/dakota
--- +++ @@ -7,17 +7,23 @@ # # Mark Piper (mark.piper@colorado.edu) -import os -import filecmp from nose.tools import * from dakota.dakota_base import DakotaBase +# Helpers -------------------------------------------------------------- + +class Concrete(DakotaBase): + """A subclass of DakotaBase used for testing.""" + def __init__(self): + DakotaBase.__init__(self) # Fixtures ------------------------------------------------------------- def setup_module(): """Called before any tests are performed.""" print('\n*** DakotaBase tests') + global c + c = Concrete() def teardown_module(): """Called after all tests have completed.""" @@ -29,3 +35,35 @@ def test_instantiate(): """Test whether DakotaBase fails to instantiate.""" d = DakotaBase() + +def test_environment_block(): + """Test type of environment_block method results.""" + s = c.environment_block() + assert_true(type(s) is str) + +def test_method_block(): + """Test type of method_block method results.""" + s = c.method_block() + assert_true(type(s) is str) + +def test_variables_block(): + """Test type of variables_block method results.""" + s = c.variables_block() + assert_true(type(s) is str) + +def test_interface_block(): + """Test type of interface_block method results.""" + s = c.interface_block() + assert_true(type(s) is str) + +def test_responses_block(): + """Test type of responses_block method results.""" + s = c.responses_block() + assert_true(type(s) is str) + +def test_autogenerate_descriptors(): + """Test autogenerate_descriptors method.""" + c.n_variables, c.n_responses = 1, 1 + c.autogenerate_descriptors() + assert_true(len(c.variable_descriptors) == 1) + assert_true(len(c.response_descriptors) == 1)
170293123c89696bbdcfca0cbc72233ea03f90c8
real_estate_agency/real_estate_agency/views.py
real_estate_agency/real_estate_agency/views.py
from django.shortcuts import render,render_to_response from django.template import RequestContext from new_buildings.models import Builder, ResidentalComplex, NewApartment from feedback.models import Feedback from company.views import about_company_in_digits_context_processor def corporation_benefit_plan(request): return render(request, 'corporation_benefit_plan.html') def index(request): feedbacks = Feedback.objects.all()[:4] context = { 'feedbacks': feedbacks, } context.update(about_company_in_digits_context_processor(request)) return render(request, 'index.html', context, ) def privacy_policy(request): return render(request, 'privacy_policy.html') def thanks(request): return render(request, 'thanks.html')
from django.shortcuts import render,render_to_response from django.template import RequestContext from new_buildings.models import Builder, ResidentalComplex, NewApartment from new_buildings.forms import SearchForm from feedback.models import Feedback from company.views import about_company_in_digits_context_processor def corporation_benefit_plan(request): return render(request, 'corporation_benefit_plan.html') def index(request): feedbacks = Feedback.objects.all()[:4] context = { 'feedbacks': feedbacks, 'form': SearchForm, } context.update(about_company_in_digits_context_processor(request)) return render(request, 'index.html', context, ) def privacy_policy(request): return render(request, 'privacy_policy.html') def thanks(request): return render(request, 'thanks.html')
Add form content to the index page.
Add form content to the index page.
Python
mit
Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency
--- +++ @@ -2,6 +2,7 @@ from django.template import RequestContext from new_buildings.models import Builder, ResidentalComplex, NewApartment +from new_buildings.forms import SearchForm from feedback.models import Feedback from company.views import about_company_in_digits_context_processor @@ -13,6 +14,7 @@ feedbacks = Feedback.objects.all()[:4] context = { 'feedbacks': feedbacks, + 'form': SearchForm, } context.update(about_company_in_digits_context_processor(request)) return render(request,
21b91eeade40d750da12cc42e89ab157911ed403
src/utils/run_check.py
src/utils/run_check.py
def check_argv(argv): """Check if arguments are ok. When executing, there must be argument switch for test/live. There also must be filename. Method returns set(is_correct, filename, is_test) """`` python_file_name = argv[0] usage_msg = "Usage: python %s [-test | -live] filename.txt" % python_file_name is_test = True if len(argv) > 1: if '-test' in argv: is_test = True elif '-live' in argv: is_test = False else: print usage_msg return (False, None, is_test) if len(argv) < 3: print usage_msg return (False, None, is_test) else: filename = argv[2] return (True, filename, is_test) else: print usage_msg return (False, None, is_test)
def check_argv(argv): """Check if arguments are ok. When executing, there must be argument switch for test/live. There also must be filename. Method returns set(is_correct, filename, is_test) """ python_file_name = argv[0] usage_msg = "Usage: python %s [-test | -live] filename.txt" % python_file_name is_test = True if len(argv) > 1: if '-test' in argv: is_test = True elif '-live' in argv: is_test = False else: print usage_msg return (False, None, is_test) if len(argv) < 3: print usage_msg return (False, None, is_test) else: filename = argv[2] return (True, filename, is_test) else: print usage_msg return (False, None, is_test)
Remove forgotten comment quotation marks
Remove forgotten comment quotation marks
Python
mit
ThePavolC/CleanJira
--- +++ @@ -4,7 +4,7 @@ When executing, there must be argument switch for test/live. There also must be filename. Method returns set(is_correct, filename, is_test) - """`` + """ python_file_name = argv[0] usage_msg = "Usage: python %s [-test | -live] filename.txt" % python_file_name is_test = True
a149c8664ed8f44ab9118a85440d95239362edf2
src/ansible/tests/test_views.py
src/ansible/tests/test_views.py
from django.core.urlresolvers import reverse from django.test import TestCase from ansible.models import Playbook class PlaybookListViewTest(TestCase): fixtures = ['initial_data.json'] def test_view_url_exists_at_desired_location(self): resp = self.client.get('/playbooks/') self.assertEqual(resp.status_code, 200) def test_view_playbook_list_url_accessible_by_name(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) def test_view_playbook_detail_url_accessible_by_name(self): resp = self.client.get( reverse('ansible:playbook-detail', kwargs={'pk':1}) ) self.assertEqual(resp.status_code, 200) def test_view_uses_correct_template(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, 'ansible/playbook_list.html')
from django.core.urlresolvers import reverse from django.test import TestCase from ansible.models import Playbook class PlaybookListViewTest(TestCase): fixtures = ['initial_data.json'] def test_view_url_exists_at_desired_location(self): resp = self.client.get('/playbooks/') self.assertEqual(resp.status_code, 200) def test_view_playbook_list_url_accessible_by_name(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) def test_view_playbook_list_has_create_playbook_link(self): resp = self.client.get(reverse('ansible:playbook-create')) self.assertEqual(resp.status_code, 200) def test_view_playbook_detail_url_accessible_by_name(self): resp = self.client.get( reverse('ansible:playbook-detail', kwargs={'pk':1}) ) self.assertEqual(resp.status_code, 200) def test_view_uses_correct_template(self): resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, 'ansible/playbook_list.html')
Test to make sure link to create playbook exists
Test to make sure link to create playbook exists
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
--- +++ @@ -15,6 +15,10 @@ resp = self.client.get(reverse('ansible:playbook-list')) self.assertEqual(resp.status_code, 200) + def test_view_playbook_list_has_create_playbook_link(self): + resp = self.client.get(reverse('ansible:playbook-create')) + self.assertEqual(resp.status_code, 200) + def test_view_playbook_detail_url_accessible_by_name(self): resp = self.client.get( reverse('ansible:playbook-detail', kwargs={'pk':1})
76981dc76d17b51c73682f84ba94ae4d6329d66d
scripts/wait_for_postgres.py
scripts/wait_for_postgres.py
"""Wait up to 30 seconds for postgres to be available. This is useful when running in docker, as the first time we create a postgres volume it takes a few seconds to become ready. """ import time from os import environ import psycopg2 if __name__ == '__main__': elapsed = 0 while elapsed < 30: try: psycopg2.connect( host=environ['DB_HOST'], user=environ['DB_USER'], password=environ['DB_PASS'], database=environ['DB_NAME']) break except (psycopg2.OperationalError): if elapsed == 0: print "Waiting for postgres to start..." time.sleep(1) elapsed += 1
"""Wait up to 30 seconds for postgres to be available. This is useful when running in docker, as the first time we create a postgres volume it takes a few seconds to become ready. """ import time import os import psycopg2 import dotenv if __name__ == '__main__': env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path) elapsed = 0 while elapsed < 30: try: psycopg2.connect( host=os.environ['DB_HOST'], user=os.environ['DB_USER'], password=os.environ['DB_PASS'], database=os.environ['DB_NAME']) break except (psycopg2.OperationalError): if elapsed == 0: print "Waiting for postgres to start..." time.sleep(1) elapsed += 1
Fix bug in script that blocks Travis on postgres ready state
Fix bug in script that blocks Travis on postgres ready state
Python
mit
ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing
--- +++ @@ -5,18 +5,26 @@ """ import time -from os import environ +import os import psycopg2 +import dotenv + if __name__ == '__main__': + env_path = os.path.join( + os.path.dirname(os.path.realpath(__file__)), + '..', 'environment' + ) + + dotenv.read_dotenv(env_path) elapsed = 0 while elapsed < 30: try: psycopg2.connect( - host=environ['DB_HOST'], - user=environ['DB_USER'], - password=environ['DB_PASS'], - database=environ['DB_NAME']) + host=os.environ['DB_HOST'], + user=os.environ['DB_USER'], + password=os.environ['DB_PASS'], + database=os.environ['DB_NAME']) break except (psycopg2.OperationalError): if elapsed == 0:
5a4ff0b4da37a97e6ef86074dde63b47ba553ad8
test/typing.py
test/typing.py
#!/usr/bin/env python from stella import stella from random import randint from test import * def return_bool(): return True def return_arg(x): return x def equality(a,b): return a==b def test1(): make_eq_test(return_bool, ()) @mark.parametrize('arg', single_args([True, False, 0, 1, 42.0, -42.5])) def test2(arg): make_eq_test(return_arg, arg) @mark.parametrize('args', [(True, True), (1,1), (42.0, 42.0), (1,2), (2.0, -2.0), (True, False), (randint(0, 10000000), randint(-10000 , 1000000))]) def test3(args): make_eq_test(equality, args) if __name__ == '__main__': print(stella(return_bool)())
#!/usr/bin/env python from stella import stella from random import randint from test import * def return_bool(): return True def return_arg(x): return x def equality(a,b): return a==b def test1(): make_eq_test(return_bool, ()) @mark.parametrize('arg', single_args([True, False, 0, 1, 42.0, -42.5])) def test2(arg): make_eq_test(return_arg, arg) @mark.parametrize('args', [(True, True), (1,1), (42.0, 42.0), (1,2), (2.0, -2.0), (True, False), (randint(0, 10000000), randint(-10000 , 1000000))]) def test3(args): make_eq_test(equality, args) @mark.parametrize('args', [(False, 1), (42.0, True), (1, 1.0), (randint(0, 10000000), float(randint(-10000 , 1000000)))]) @mark.xfail() def test3fail(args): make_eq_test(equality, args) if __name__ == '__main__': print(stella(return_bool)())
Add a test that automatic type promotions are not allowed.
Add a test that automatic type promotions are not allowed.
Python
apache-2.0
squisher/stella,squisher/stella,squisher/stella,squisher/stella
--- +++ @@ -19,5 +19,10 @@ def test3(args): make_eq_test(equality, args) +@mark.parametrize('args', [(False, 1), (42.0, True), (1, 1.0), (randint(0, 10000000), float(randint(-10000 , 1000000)))]) +@mark.xfail() +def test3fail(args): + make_eq_test(equality, args) + if __name__ == '__main__': print(stella(return_bool)())
70098ce0c9db57cb82b97bc9fee8a799fb355e98
chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py
chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py
# Copyright (c) 2010 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 def run_once(self): password_file = '%s/sync_password.txt' % self.bindir self.run_chrome_test('sync_integration_tests', ('--password-file-for-test=%s ' + '--test-terminate-timeout=300000') % password_file)
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 binary_to_run = 'sync_integration_tests' cmd_line_params = '--test-terminate-timeout=120000' def run_once(self): self.run_chrome_test(self.binary_to_run, self.cmd_line_params)
Make the sync integration tests self-contained on autotest
Make the sync integration tests self-contained on autotest In the past, the sync integration tests used to require a password file stored on every test device in order to do a gaia sign in using production gaia servers. This caused the tests to be brittle. As of today, the sync integration tests no longer rely on a password file, with gaia sign in being stubbed out locally. This patch reconfigures the tests on autotest, so that it no longer looks for a local password file. In addition, the tests run much faster now, and therefore, we reduce the max timeout to a more reasonable 2 minutes (in the extreme case). BUG=chromium-os:11294, chromium-os:9262 TEST=sync_integration_tests Review URL: http://codereview.chromium.org/6387004 git-svn-id: http://src.chromium.org/svn/trunk/src@72561 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: e54b28430f7b301e04eb5b02ce667019df4434bf
Python
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
--- +++ @@ -1,4 +1,4 @@ -# Copyright (c) 2010 The Chromium Authors. All rights reserved. +# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. @@ -7,9 +7,8 @@ class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 + binary_to_run = 'sync_integration_tests' + cmd_line_params = '--test-terminate-timeout=120000' + def run_once(self): - password_file = '%s/sync_password.txt' % self.bindir - - self.run_chrome_test('sync_integration_tests', - ('--password-file-for-test=%s ' + - '--test-terminate-timeout=300000') % password_file) + self.run_chrome_test(self.binary_to_run, self.cmd_line_params)
9fcff13a4438268aa76cf2817bca1086258a083b
src/mr_landmark_mapper.py
src/mr_landmark_mapper.py
#!/usr/bin/env python import sys import json import codecs import zipimport importer = zipimport.zipimporter('landmark.mod') extraction = importer.load_module('extraction') postprocessing = importer.load_module('postprocessing') from extraction.Landmark import RuleSet current_id = None with codecs.open("lib/rules.zip", "r", "utf-8") as myfile: json_str = myfile.read().encode('utf-8') json_object = json.loads(json_str) rules = RuleSet(json_object) # input comes from STDIN for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() idx = line.find("\t") if idx != -1: key = line[0:idx] value = line[idx+1:] try: body_json = json.loads(value, encoding='utf-8') if body_json.get("html"): html = body_json["html"] extraction_list = rules.extract(html) print key + "\t" + json.dumps(extraction_list) except: pass exit(0)
#!/usr/bin/env python import sys import json import codecs import zipimport importer = zipimport.zipimporter('landmark.mod') extraction = importer.load_module('extraction') postprocessing = importer.load_module('postprocessing') from extraction.Landmark import RuleSet current_id = None with codecs.open("rules.txt", "r", "utf-8") as myfile: json_str = myfile.read().encode('utf-8') #sys.stderr.write("Got rules:" + json_str) json_object = json.loads(json_str) rules = RuleSet(json_object) # input comes from STDIN for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() sys.stderr.write("Got line:" + line) if len(line) > 0: try: body_json = json.loads(line, encoding='utf-8') if body_json.get("html"): html = body_json["html"] key = body_json["@id"] sys.stderr.write("Got html:" + html) extraction_list = rules.extract(html) print key + "\t" + json.dumps(extraction_list) except: pass exit(0)
Change mapper to use SequenceFileAsJSONInputBatchFormat
Change mapper to use SequenceFileAsJSONInputBatchFormat
Python
apache-2.0
usc-isi-i2/landmark-extraction,usc-isi-i2/landmark-extraction,usc-isi-i2/landmark-extraction
--- +++ @@ -13,8 +13,9 @@ current_id = None -with codecs.open("lib/rules.zip", "r", "utf-8") as myfile: +with codecs.open("rules.txt", "r", "utf-8") as myfile: json_str = myfile.read().encode('utf-8') +#sys.stderr.write("Got rules:" + json_str) json_object = json.loads(json_str) rules = RuleSet(json_object) @@ -22,15 +23,15 @@ for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() - idx = line.find("\t") - if idx != -1: - key = line[0:idx] - value = line[idx+1:] + sys.stderr.write("Got line:" + line) + if len(line) > 0: try: - body_json = json.loads(value, encoding='utf-8') + body_json = json.loads(line, encoding='utf-8') if body_json.get("html"): html = body_json["html"] - extraction_list = rules.extract(html) + key = body_json["@id"] + sys.stderr.write("Got html:" + html) + extraction_list = rules.extract(html) print key + "\t" + json.dumps(extraction_list) except: pass
ca43f30998290193290177f4c55c1c8577123974
arcutils/sessions.py
arcutils/sessions.py
from __future__ import absolute_import from random import random import logging from django.conf import settings from django.utils.importlib import import_module from django.core.exceptions import ImproperlyConfigured from django.core.signals import request_started logger = logging.getLogger(__name__) def clear_expired_sessions(sender, **kwargs): """ Triggered by the request_started signal, this function calls the clear_expired method on the session backend, with a certain probability (similar to how PHP clears sessions) """ if random() <= clear_expired_sessions.probability: try: clear_expired_sessions.engine.SessionStore.clear_expired() logger.debug('Sessions cleared') except NotImplementedError: logger.debug('Session engine "%s" does ont support clearing expired sessions.' % settings.SESSION_ENGINE) def patch_sessions(num_requests): """ Connects the clear_expired_sessions function to the request_started signal, and does a little configuration calculations and checking. """ if num_requests < 1: raise ImproperlyConfigured('The num_requests setting must be > 0') clear_expired_sessions.engine = import_module(settings.SESSION_ENGINE) clear_expired_sessions.probability = 1.0 / num_requests request_started.connect(clear_expired_sessions)
from __future__ import absolute_import from random import random import logging try: # Python >= 2.7 import importlib except ImportError: # Python < 2.7; will be removed in Django 1.9 from django.utils import importlib from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.signals import request_started logger = logging.getLogger(__name__) def clear_expired_sessions(sender, **kwargs): """ Triggered by the request_started signal, this function calls the clear_expired method on the session backend, with a certain probability (similar to how PHP clears sessions) """ if random() <= clear_expired_sessions.probability: try: clear_expired_sessions.engine.SessionStore.clear_expired() logger.debug('Sessions cleared') except NotImplementedError: logger.debug('Session engine "%s" does ont support clearing expired sessions.' % settings.SESSION_ENGINE) def patch_sessions(num_requests): """ Connects the clear_expired_sessions function to the request_started signal, and does a little configuration calculations and checking. """ if num_requests < 1: raise ImproperlyConfigured('The num_requests setting must be > 0') clear_expired_sessions.engine = importlib.import_module(settings.SESSION_ENGINE) clear_expired_sessions.probability = 1.0 / num_requests request_started.connect(clear_expired_sessions)
Make importlib import compatible w/ Django>=1.8
Make importlib import compatible w/ Django>=1.8 For Django 1.8, this just squelches a DeprecationWarning. For 1.9, this will stop an ImportError.
Python
mit
mdj2/django-arcutils,PSU-OIT-ARC/django-arcutils,wylee/django-arcutils,mdj2/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils
--- +++ @@ -2,8 +2,14 @@ from random import random import logging +try: + # Python >= 2.7 + import importlib +except ImportError: + # Python < 2.7; will be removed in Django 1.9 + from django.utils import importlib + from django.conf import settings -from django.utils.importlib import import_module from django.core.exceptions import ImproperlyConfigured from django.core.signals import request_started @@ -33,6 +39,6 @@ if num_requests < 1: raise ImproperlyConfigured('The num_requests setting must be > 0') - clear_expired_sessions.engine = import_module(settings.SESSION_ENGINE) + clear_expired_sessions.engine = importlib.import_module(settings.SESSION_ENGINE) clear_expired_sessions.probability = 1.0 / num_requests request_started.connect(clear_expired_sessions)
4c00345ec0a66363d3b9d7e423e2fcd19aa2a307
ditto/core/context_processors.py
ditto/core/context_processors.py
from .apps import ditto_apps from ..flickr import app_settings def ditto(request): return { 'enabled_apps': ditto_apps.enabled(), 'DITTO_FLICKR_USE_LOCAL_MEDIA': app_settings.DITTO_FLICKR_USE_LOCAL_MEDIA, }
from .apps import ditto_apps from ..flickr import app_settings def ditto(request): return { 'enabled_apps': ditto_apps.enabled() }
Remove unused 'DITTO_FLICKR_USE_LOCAL_MEDIA' in context_processor
Remove unused 'DITTO_FLICKR_USE_LOCAL_MEDIA' in context_processor
Python
mit
philgyford/django-ditto,philgyford/django-ditto,philgyford/django-ditto
--- +++ @@ -4,8 +4,6 @@ def ditto(request): return { - 'enabled_apps': ditto_apps.enabled(), - 'DITTO_FLICKR_USE_LOCAL_MEDIA': - app_settings.DITTO_FLICKR_USE_LOCAL_MEDIA, + 'enabled_apps': ditto_apps.enabled() }
760a952851664232b11ad95acb8884dda59308a4
sysrev/widgets.py
sysrev/widgets.py
from django.forms import widgets from django.utils.safestring import * # See static/js/querywidget.js class QueryWidget(widgets.Textarea): def __init__(self, attrs=None): default_attrs = {'class': "queryWidget"} if attrs: default_attrs.update(attrs) super(QueryWidget, self).__init__(default_attrs) def script(self): return mark_safe("<script src='/static/js/querywidget.js' type='text/javascript' defer></script>") def render(self, name, value, attrs=None): textAreaHtml = super(QueryWidget, self).render(name, value, attrs) return self.script() + textAreaHtml
from django.forms import widgets from django.utils.safestring import * # See static/js/querywidget.js class QueryWidget(widgets.Textarea): def __init__(self, attrs=None): default_attrs = {'class': "queryWidget"} if attrs: default_attrs.update(attrs) super(QueryWidget, self).__init__(default_attrs) def script(self): return mark_safe("<noscript>Please enable javascript to use the query editor. Without it enabled, you can only " "use the advanced editor</noscript>" "<script src='/static/js/querywidget.js' type='text/javascript' defer></script>") def render(self, name, value, attrs=None): textAreaHtml = super(QueryWidget, self).render(name, value, attrs) return self.script() + textAreaHtml
Add <noscript> message to indicate that only the advanced query editor is available.
Add <noscript> message to indicate that only the advanced query editor is available.
Python
mit
iliawnek/SystematicReview,iliawnek/SystematicReview,iliawnek/SystematicReview,iliawnek/SystematicReview
--- +++ @@ -10,7 +10,9 @@ super(QueryWidget, self).__init__(default_attrs) def script(self): - return mark_safe("<script src='/static/js/querywidget.js' type='text/javascript' defer></script>") + return mark_safe("<noscript>Please enable javascript to use the query editor. Without it enabled, you can only " + "use the advanced editor</noscript>" + "<script src='/static/js/querywidget.js' type='text/javascript' defer></script>") def render(self, name, value, attrs=None): textAreaHtml = super(QueryWidget, self).render(name, value, attrs)
7f41a424143334a8c8e1ccbd768c911f8e6ffb31
transform_quandl_xjpx_archive.py
transform_quandl_xjpx_archive.py
# -*- coding: utf-8 -*- """ ``` # 1. $ cp -r ~/.zipline/data/quandl-xjpx/2016-12-28T08\;14\;58.046694 \ /tmp/quandl-xjpx/ # 2. $ python transform_quandl_xjpx_archive.py ``` """ import tarfile with tarfile.open('/tmp/quandl-xjpx.tar', 'w') as f: f.add('/tmp/quandl-xjpx')
# -*- coding: utf-8 -*- """ ``` # 1. $ cp -r ~/.zipline/data/quandl-xjpx/2016-12-28T08\;14\;58.046694 \ /tmp/quandl-xjpx/ # 2. $ python transform_quandl_xjpx_archive.py ``` """ import tarfile import os with tarfile.open('/tmp/quandl-xjpx.tar', 'w') as f: os.chdir('/tmp/quandl-xjpx') for fn in os.listdir('.'): f.add(fn)
Fix bug on transform quandl archive
Fix bug on transform quandl archive
Python
apache-2.0
magne-max/zipline-ja,magne-max/zipline-ja
--- +++ @@ -10,7 +10,10 @@ ``` """ import tarfile +import os with tarfile.open('/tmp/quandl-xjpx.tar', 'w') as f: - f.add('/tmp/quandl-xjpx') + os.chdir('/tmp/quandl-xjpx') + for fn in os.listdir('.'): + f.add(fn)
812f1fec796e4c7d86731d5e3e91293fb1b0296b
scripts/europeana-meta.py
scripts/europeana-meta.py
from __future__ import print_function import sys, os from re import sub import zipfile, json # from pyspark import SparkContext # from pyspark.sql import SQLContext # from pyspark.sql import Row # from pyspark.sql.types import StringType def getSeries(fname): with zipfile.ZipFile(fname, 'r') as zf: names = zf.namelist() mfile = [f for f in names if f.endswith('.metadata.json')] series = fname if len(mfile) > 0: m = json.loads(zf.read(mfile[0])) series = m['identifier'][0] return m if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: europeana.py <input> <output>", file=sys.stderr) exit(-1) # sc = SparkContext(appName="Europeana Import") # sqlContext = SQLContext(sc) x = [os.path.join(d[0], f) for d in os.walk(sys.argv[1]) for f in d[2] if f.endswith('zip')] for f in x: print(json.dumps(getSeries(f))) # sc.parallelize(x, 200).flatMap(getSeries).toDF().write.save(sys.argv[2]) # sc.stop()
from __future__ import print_function import sys, os from re import sub import zipfile, json # from pyspark import SparkContext # from pyspark.sql import SQLContext # from pyspark.sql import Row # from pyspark.sql.types import StringType def getSeries(fname): with zipfile.ZipFile(fname, 'r') as zf: names = zf.namelist() mfile = [f for f in names if f.endswith('.metadata.json')] series = 'europeana/' + sub('^.*newspapers-by-country/', '', sub('[\x80-\xff]', '', fname).replace('.zip', '')) if len(mfile) > 0: m = json.loads(zf.read(mfile[0])) return {'series': series, 'title': m['title'][0], 'lang': m['language']} if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: europeana.py <input> <output>", file=sys.stderr) exit(-1) # sc = SparkContext(appName="Europeana Import") # sqlContext = SQLContext(sc) x = [os.path.join(d[0], f) for d in os.walk(sys.argv[1]) for f in d[2] if f.endswith('zip')] for f in x: print(json.dumps(getSeries(f))) # sc.parallelize(x, 200).flatMap(getSeries).toDF().write.save(sys.argv[2]) # sc.stop()
Use file path as Europeana series name.
Use file path as Europeana series name.
Python
apache-2.0
ViralTexts/vt-passim,ViralTexts/vt-passim,ViralTexts/vt-passim
--- +++ @@ -13,11 +13,11 @@ with zipfile.ZipFile(fname, 'r') as zf: names = zf.namelist() mfile = [f for f in names if f.endswith('.metadata.json')] - series = fname + series = 'europeana/' + sub('^.*newspapers-by-country/', '', + sub('[\x80-\xff]', '', fname).replace('.zip', '')) if len(mfile) > 0: m = json.loads(zf.read(mfile[0])) - series = m['identifier'][0] - return m + return {'series': series, 'title': m['title'][0], 'lang': m['language']} if __name__ == "__main__": if len(sys.argv) < 2:
0ec5aeca33676172f458ec6761282157dcb19635
tests/test_set_pref.py
tests/test_set_pref.py
# tests.test_set_pref import nose.tools as nose import yvs.set_pref as yvs def test_set_language(): """should set preferred language""" new_language = 'es' yvs.main('language:{}'.format(new_language)) user_prefs = yvs.shared.get_user_prefs() nose.assert_equal(user_prefs['language'], new_language) bible = yvs.shared.get_bible_data(user_prefs['language']) nose.assert_equal(user_prefs['version'], bible['default_version']) def test_set_version(): """should set preferred version""" new_version = 59 yvs.main('version:{}'.format(new_version)) user_prefs = yvs.shared.get_user_prefs() nose.assert_equal(user_prefs['version'], new_version)
# tests.test_set_pref import nose.tools as nose import yvs.set_pref as yvs def test_set_language(): """should set preferred language""" new_language = 'es' yvs.main('language:{}'.format(new_language)) user_prefs = yvs.shared.get_user_prefs() nose.assert_equal(user_prefs['language'], new_language) bible = yvs.shared.get_bible_data(user_prefs['language']) nose.assert_equal(user_prefs['version'], bible['default_version']) def test_set_version(): """should set preferred version""" new_version = 59 yvs.main('version:{}'.format(new_version)) user_prefs = yvs.shared.get_user_prefs() nose.assert_equal(user_prefs['version'], new_version) def test_set_search_engine(): """should set preferred search engine""" new_search_engine = 'yahoo' yvs.main('searchEngine:{}'.format(new_search_engine)) user_prefs = yvs.shared.get_user_prefs() nose.assert_equal(user_prefs['searchEngine'], new_search_engine)
Add test for setting preferred search engine
Add test for setting preferred search engine
Python
mit
caleb531/youversion-suggest,caleb531/youversion-suggest
--- +++ @@ -20,3 +20,11 @@ yvs.main('version:{}'.format(new_version)) user_prefs = yvs.shared.get_user_prefs() nose.assert_equal(user_prefs['version'], new_version) + + +def test_set_search_engine(): + """should set preferred search engine""" + new_search_engine = 'yahoo' + yvs.main('searchEngine:{}'.format(new_search_engine)) + user_prefs = yvs.shared.get_user_prefs() + nose.assert_equal(user_prefs['searchEngine'], new_search_engine)
9d65dbb84126a26e8e6dfe31179087f75134f564
tests/integration/auth_tests.py
tests/integration/auth_tests.py
from django.test import TestCase from django.contrib.auth import authenticate, get_user_model from django.core import mail User = get_user_model() class TestEmailAuthBackendWhenUsersShareAnEmail(TestCase): def test_authenticates_when_passwords_are_different(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password=username) user = authenticate(username=email, password='user1') self.assertTrue(user is not None) def test_rejects_when_passwords_match(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password='password') user = authenticate(username=email, password='password') self.assertTrue(user is None) def test_mails_admins_when_passwords_match(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password='password') authenticate(username=email, password='password') self.assertEqual(1, len(mail.outbox))
from django.test import TestCase from django.contrib.auth import authenticate from django.core import mail from oscar.core.compat import get_user_model User = get_user_model() class TestEmailAuthBackendWhenUsersShareAnEmail(TestCase): def test_authenticates_when_passwords_are_different(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password=username) user = authenticate(username=email, password='user1') self.assertTrue(user is not None) def test_rejects_when_passwords_match(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password='password') user = authenticate(username=email, password='password') self.assertTrue(user is None) def test_mails_admins_when_passwords_match(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password='password') authenticate(username=email, password='password') self.assertEqual(1, len(mail.outbox))
Load User model from compatibility layer
Load User model from compatibility layer
Python
bsd-3-clause
jinnykoo/wuyisj.com,josesanch/django-oscar,itbabu/django-oscar,kapt/django-oscar,Jannes123/django-oscar,nickpack/django-oscar,bnprk/django-oscar,marcoantoniooliveira/labweb,lijoantony/django-oscar,ahmetdaglarbas/e-commerce,marcoantoniooliveira/labweb,itbabu/django-oscar,manevant/django-oscar,bschuon/django-oscar,faratro/django-oscar,DrOctogon/unwash_ecom,bnprk/django-oscar,makielab/django-oscar,michaelkuty/django-oscar,spartonia/django-oscar,jinnykoo/wuyisj.com,okfish/django-oscar,pasqualguerrero/django-oscar,pasqualguerrero/django-oscar,QLGu/django-oscar,WadeYuChen/django-oscar,jinnykoo/wuyisj,mexeniz/django-oscar,mexeniz/django-oscar,saadatqadri/django-oscar,adamend/django-oscar,dongguangming/django-oscar,QLGu/django-oscar,spartonia/django-oscar,anentropic/django-oscar,jmt4/django-oscar,QLGu/django-oscar,ka7eh/django-oscar,spartonia/django-oscar,solarissmoke/django-oscar,kapari/django-oscar,nfletton/django-oscar,vovanbo/django-oscar,monikasulik/django-oscar,ahmetdaglarbas/e-commerce,WadeYuChen/django-oscar,eddiep1101/django-oscar,nfletton/django-oscar,bschuon/django-oscar,rocopartners/django-oscar,solarissmoke/django-oscar,mexeniz/django-oscar,taedori81/django-oscar,saadatqadri/django-oscar,jmt4/django-oscar,sasha0/django-oscar,adamend/django-oscar,WillisXChen/django-oscar,kapari/django-oscar,faratro/django-oscar,WillisXChen/django-oscar,machtfit/django-oscar,DrOctogon/unwash_ecom,dongguangming/django-oscar,josesanch/django-oscar,ademuk/django-oscar,WadeYuChen/django-oscar,michaelkuty/django-oscar,jmt4/django-oscar,QLGu/django-oscar,rocopartners/django-oscar,elliotthill/django-oscar,Bogh/django-oscar,WillisXChen/django-oscar,rocopartners/django-oscar,taedori81/django-oscar,saadatqadri/django-oscar,bschuon/django-oscar,jinnykoo/christmas,pdonadeo/django-oscar,okfish/django-oscar,binarydud/django-oscar,okfish/django-oscar,amirrpp/django-oscar,binarydud/django-oscar,Bogh/django-oscar,pdonadeo/django-oscar,WillisXChen/django-oscar,sonofatailor/django-oscar,eddiep1101/django-oscar,manevant/django-oscar,Jannes123/django-oscar,MatthewWilkes/django-oscar,ahmetdaglarbas/e-commerce,itbabu/django-oscar,manevant/django-oscar,bnprk/django-oscar,itbabu/django-oscar,michaelkuty/django-oscar,jinnykoo/wuyisj.com,jlmadurga/django-oscar,binarydud/django-oscar,vovanbo/django-oscar,john-parton/django-oscar,elliotthill/django-oscar,john-parton/django-oscar,jinnykoo/christmas,bschuon/django-oscar,ademuk/django-oscar,lijoantony/django-oscar,WillisXChen/django-oscar,thechampanurag/django-oscar,kapari/django-oscar,Jannes123/django-oscar,elliotthill/django-oscar,ka7eh/django-oscar,Idematica/django-oscar,taedori81/django-oscar,anentropic/django-oscar,django-oscar/django-oscar,ka7eh/django-oscar,nickpack/django-oscar,makielab/django-oscar,bnprk/django-oscar,adamend/django-oscar,ademuk/django-oscar,django-oscar/django-oscar,michaelkuty/django-oscar,anentropic/django-oscar,nickpack/django-oscar,makielab/django-oscar,jinnykoo/wuyisj.com,sasha0/django-oscar,solarissmoke/django-oscar,Jannes123/django-oscar,manevant/django-oscar,nfletton/django-oscar,django-oscar/django-oscar,john-parton/django-oscar,nickpack/django-oscar,MatthewWilkes/django-oscar,ka7eh/django-oscar,DrOctogon/unwash_ecom,marcoantoniooliveira/labweb,sonofatailor/django-oscar,mexeniz/django-oscar,faratro/django-oscar,django-oscar/django-oscar,anentropic/django-oscar,eddiep1101/django-oscar,MatthewWilkes/django-oscar,faratro/django-oscar,jlmadurga/django-oscar,sasha0/django-oscar,jinnykoo/wuyisj,ahmetdaglarbas/e-commerce,spartonia/django-oscar,jinnykoo/wuyisj,dongguangming/django-oscar,sonofatailor/django-oscar,jlmadurga/django-oscar,john-parton/django-oscar,sasha0/django-oscar,machtfit/django-oscar,nfletton/django-oscar,ademuk/django-oscar,okfish/django-oscar,amirrpp/django-oscar,eddiep1101/django-oscar,machtfit/django-oscar,solarissmoke/django-oscar,rocopartners/django-oscar,WillisXChen/django-oscar,kapt/django-oscar,Bogh/django-oscar,thechampanurag/django-oscar,jmt4/django-oscar,jinnykoo/wuyisj,jlmadurga/django-oscar,Idematica/django-oscar,dongguangming/django-oscar,kapt/django-oscar,sonofatailor/django-oscar,monikasulik/django-oscar,monikasulik/django-oscar,pdonadeo/django-oscar,lijoantony/django-oscar,lijoantony/django-oscar,amirrpp/django-oscar,monikasulik/django-oscar,pdonadeo/django-oscar,marcoantoniooliveira/labweb,makielab/django-oscar,Idematica/django-oscar,MatthewWilkes/django-oscar,pasqualguerrero/django-oscar,pasqualguerrero/django-oscar,Bogh/django-oscar,thechampanurag/django-oscar,WadeYuChen/django-oscar,taedori81/django-oscar,jinnykoo/christmas,vovanbo/django-oscar,amirrpp/django-oscar,vovanbo/django-oscar,adamend/django-oscar,josesanch/django-oscar,saadatqadri/django-oscar,thechampanurag/django-oscar,kapari/django-oscar,binarydud/django-oscar
--- +++ @@ -1,6 +1,8 @@ from django.test import TestCase -from django.contrib.auth import authenticate, get_user_model +from django.contrib.auth import authenticate from django.core import mail + +from oscar.core.compat import get_user_model User = get_user_model()
7ab7eae4254f8ee62b3a8620982c72b07c2299e4
tests/__init__.py
tests/__init__.py
import threading import time DEFAULT_SLEEP = 0.01 class CustomError(Exception): pass def defer(callback, *args, **kwargs): sleep = kwargs.pop('sleep', DEFAULT_SLEEP) expected_return = kwargs.pop('expected_return', None) call = kwargs.pop('call', True) def func(): time.sleep(sleep) if call: assert expected_return == callback(*args, **kwargs) else: print("generator is not re-called") t = threading.Thread(target=func) t.start() def wait_until_finished(wrapper, timeout=1, sleep=DEFAULT_SLEEP): start_time = time.time() while time.time() < start_time + timeout: # Relies on .has_terminated, but shouldn't be a problem if wrapper.has_terminated(): return time.sleep(sleep) raise RuntimeError("Has not been collected within %ss" % timeout) class State(object): """Helper class to keep track of a test's state.""" def __init__(self): self.reset() def inc(self): self.counter += 1 def reset(self): self.counter = 0 self.run = False
import threading import time DEFAULT_SLEEP = 0.01 class CustomError(Exception): pass def defer(callback, *args, sleep=DEFAULT_SLEEP, expected_return=None, call=True, **kwargs): def func(): time.sleep(sleep) if call: assert expected_return == callback(*args, **kwargs) else: print("generator is not re-called") t = threading.Thread(target=func) t.start() def wait_until_finished(wrapper, timeout=1, sleep=DEFAULT_SLEEP): start_time = time.time() while time.time() < start_time + timeout: # Relies on .has_terminated, but shouldn't be a problem if wrapper.has_terminated(): return time.sleep(sleep) raise RuntimeError("Has not been collected within %ss" % timeout) class State(object): """Helper class to keep track of a test's state.""" def __init__(self): self.reset() def inc(self): self.counter += 1 def reset(self): self.counter = 0 self.run = False
Use named kwargs after *args
Use named kwargs after *args Another Python 3 thing.
Python
mit
FichteFoll/resumeback
--- +++ @@ -9,11 +9,9 @@ pass -def defer(callback, *args, **kwargs): - sleep = kwargs.pop('sleep', DEFAULT_SLEEP) - expected_return = kwargs.pop('expected_return', None) - call = kwargs.pop('call', True) - +def defer(callback, *args, + sleep=DEFAULT_SLEEP, expected_return=None, call=True, + **kwargs): def func(): time.sleep(sleep) if call:
a5beccfa3574f4fcb1b6030737b728e65803791f
numpy/array_api/_typing.py
numpy/array_api/_typing.py
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = [ "Array", "Device", "Dtype", "SupportsDLPack", "SupportsBufferProtocol", "PyCapsule", ] from typing import Any, Literal, Sequence, Type, Union from . import ( Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, ) # This should really be recursive, but that isn't supported yet. See the # similar comment in numpy/typing/_array_like.py NestedSequence = Sequence[Sequence[Any]] Device = Literal["cpu"] Dtype = Type[ Union[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64] ] SupportsDLPack = Any SupportsBufferProtocol = Any PyCapsule = Any
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = [ "Array", "Device", "Dtype", "SupportsDLPack", "SupportsBufferProtocol", "PyCapsule", ] import sys from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING from . import Array from numpy import ( dtype, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, ) # This should really be recursive, but that isn't supported yet. See the # similar comment in numpy/typing/_array_like.py NestedSequence = Sequence[Sequence[Any]] Device = Literal["cpu"] if TYPE_CHECKING or sys.version_info >= (3, 9): Dtype = dtype[Union[ int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, ]] else: Dtype = dtype SupportsDLPack = Any SupportsBufferProtocol = Any PyCapsule = Any
Fix invalid parameter types used in `Dtype`
MAINT: Fix invalid parameter types used in `Dtype`
Python
bsd-3-clause
anntzer/numpy,charris/numpy,mattip/numpy,endolith/numpy,mhvk/numpy,charris/numpy,mhvk/numpy,jakirkham/numpy,seberg/numpy,endolith/numpy,pdebuyl/numpy,jakirkham/numpy,rgommers/numpy,seberg/numpy,numpy/numpy,rgommers/numpy,anntzer/numpy,charris/numpy,pdebuyl/numpy,endolith/numpy,mhvk/numpy,seberg/numpy,endolith/numpy,rgommers/numpy,rgommers/numpy,mattip/numpy,anntzer/numpy,mhvk/numpy,jakirkham/numpy,mattip/numpy,pdebuyl/numpy,pdebuyl/numpy,mhvk/numpy,numpy/numpy,charris/numpy,jakirkham/numpy,mattip/numpy,anntzer/numpy,jakirkham/numpy,numpy/numpy,numpy/numpy,seberg/numpy
--- +++ @@ -15,10 +15,12 @@ "PyCapsule", ] -from typing import Any, Literal, Sequence, Type, Union +import sys +from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING -from . import ( - Array, +from . import Array +from numpy import ( + dtype, int8, int16, int32, @@ -36,9 +38,22 @@ NestedSequence = Sequence[Sequence[Any]] Device = Literal["cpu"] -Dtype = Type[ - Union[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64] -] +if TYPE_CHECKING or sys.version_info >= (3, 9): + Dtype = dtype[Union[ + int8, + int16, + int32, + int64, + uint8, + uint16, + uint32, + uint64, + float32, + float64, + ]] +else: + Dtype = dtype + SupportsDLPack = Any SupportsBufferProtocol = Any PyCapsule = Any
6c497109cee9c3fa69ca9be118f8546f7696a937
tests/conftest.py
tests/conftest.py
"""Common fixtures and configurations for this test directory.""" import os import shutil import sys import pytest @pytest.fixture('module') def cwd_module_dir(): """Change current directory to this module's folder to access inputs and write outputs.""" cwd = os.getcwd() os.chdir(os.path.dirname(__file__)) yield os.chdir(cwd) @pytest.fixture(scope='module') def pygen_output_dir(cwd_module_dir): """Return an empty output directory, part of syspath to allow importing generated code.""" path = 'output' shutil.rmtree(path, ignore_errors=True) sys.path.append(path) yield path sys.path.remove(path) shutil.rmtree(path, ignore_errors=False)
"""Common fixtures and configurations for this test directory.""" import os import shutil import sys import pytest @pytest.fixture(scope='module') def cwd_module_dir(): """Change current directory to this module's folder to access inputs and write outputs.""" cwd = os.getcwd() os.chdir(os.path.dirname(__file__)) yield os.chdir(cwd) @pytest.fixture(scope='module') def pygen_output_dir(cwd_module_dir): """Return an empty output directory, part of syspath to allow importing generated code.""" path = 'output' shutil.rmtree(path, ignore_errors=True) sys.path.append(path) yield path sys.path.remove(path) shutil.rmtree(path, ignore_errors=False)
Fix tests setupt for new pytest
Fix tests setupt for new pytest
Python
bsd-3-clause
pyecore/pyecoregen
--- +++ @@ -6,7 +6,7 @@ import pytest -@pytest.fixture('module') +@pytest.fixture(scope='module') def cwd_module_dir(): """Change current directory to this module's folder to access inputs and write outputs.""" cwd = os.getcwd()