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
|
---|---|---|---|---|---|---|---|---|---|---|
4b56e0da85cec4aa89b8105c3a7ca416a2f7919e | wdim/client/blob.py | wdim/client/blob.py | import json
import hashlib
from wdim import orm
from wdim.orm import fields
from wdim.orm import exceptions
class Blob(orm.Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data):
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
return await super(Blob, cls).create(_id=sha, data=data)
except exceptions.UniqueViolation:
return await cls.load(sha)
@property
def hash(self):
return self._id
| import json
import hashlib
from typing import Any, Dict
from wdim import orm
from wdim.orm import fields
from wdim.orm import exceptions
class Blob(orm.Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data: Dict[str, Any]) -> 'Blob':
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
return await super(Blob, cls).create(_id=sha, data=data)
except exceptions.UniqueViolation:
return await cls.load(sha)
@property
def hash(self) -> str:
return self._id
def __getitem__(self, key):
return self.data[key]
| Allow Blob to be accessed with __getitem__ | Allow Blob to be accessed with __getitem__
| Python | mit | chrisseto/Still | ---
+++
@@ -1,5 +1,6 @@
import json
import hashlib
+from typing import Any, Dict
from wdim import orm
from wdim.orm import fields
@@ -14,7 +15,7 @@
data = fields.DictField()
@classmethod
- async def create(cls, data):
+ async def create(cls, data: Dict[str, Any]) -> 'Blob':
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
@@ -23,5 +24,8 @@
return await cls.load(sha)
@property
- def hash(self):
+ def hash(self) -> str:
return self._id
+
+ def __getitem__(self, key):
+ return self.data[key] |
a78445cfada5cc1f77a7887dc5241071bef69989 | compass/tests/test_models.py | compass/tests/test_models.py | from django.test import TestCase
from compass.models import (Category,
Book)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestCase(TestCase):
def test_can_add_book(self):
category = Category.create(title="Mock Category")
Book.create(title="Mock Book", category=category)
self.assertEqual(Book.find("Mock Book").count(), 1)
| from django.test import TestCase
from compass.models import (Category,
Book, Compass)
class CategoryTestCase(TestCase):
def test_can_add_category(self,):
Category.create(title="Mock Category")
self.assertEqual(Category.find("Mock Category").count(), 1)
class BookTestCase(TestCase):
def test_can_add_book(self):
category = Category.create(title="Mock Category")
Book.create(title="Mock Book", category=category)
self.assertEqual(Book.find("Mock Book").count(), 1)
class CompassTestCase(TestCase):
def test_correct_title_if_not_title_and_category(self,):
heading = Compass.heading(title="", category="")
self.assertEqual(heading, "All books")
def test_correct_title_if_not_category(self,):
heading = Compass.heading(title="Title 1", category="")
self.assertEqual(heading, "All book titles like Title 1")
def test_correct_title_if_not_title(self,):
heading = Compass.heading(title="", category="Category 1")
self.assertEqual(heading, "All book titles under Category 1")
| Test correct heading returned in search results | Test correct heading returned in search results
| Python | mit | andela-osule/bookworm,andela-osule/bookworm | ---
+++
@@ -1,6 +1,6 @@
from django.test import TestCase
from compass.models import (Category,
- Book)
+ Book, Compass)
class CategoryTestCase(TestCase):
@@ -14,3 +14,17 @@
category = Category.create(title="Mock Category")
Book.create(title="Mock Book", category=category)
self.assertEqual(Book.find("Mock Book").count(), 1)
+
+
+class CompassTestCase(TestCase):
+ def test_correct_title_if_not_title_and_category(self,):
+ heading = Compass.heading(title="", category="")
+ self.assertEqual(heading, "All books")
+
+ def test_correct_title_if_not_category(self,):
+ heading = Compass.heading(title="Title 1", category="")
+ self.assertEqual(heading, "All book titles like Title 1")
+
+ def test_correct_title_if_not_title(self,):
+ heading = Compass.heading(title="", category="Category 1")
+ self.assertEqual(heading, "All book titles under Category 1") |
e299906aae483f1cb6deaff83a68519a042b92e6 | stripe/stripe_response.py | stripe/stripe_response.py | from __future__ import absolute_import, division, print_function
import json
class StripeResponse:
def __init__(self, body, code, headers):
self.body = body
self.code = code
self.headers = headers
self.data = json.loads(body)
@property
def idempotency_key(self):
try:
return self.headers['idempotency-key']
except KeyError:
return None
@property
def request_id(self):
try:
return self.headers['request-id']
except KeyError:
return None
| from __future__ import absolute_import, division, print_function
import json
class StripeResponse(object):
def __init__(self, body, code, headers):
self.body = body
self.code = code
self.headers = headers
self.data = json.loads(body)
@property
def idempotency_key(self):
try:
return self.headers['idempotency-key']
except KeyError:
return None
@property
def request_id(self):
try:
return self.headers['request-id']
except KeyError:
return None
| Make StripeResponse a new-style class | Make StripeResponse a new-style class
| Python | mit | stripe/stripe-python | ---
+++
@@ -3,8 +3,7 @@
import json
-class StripeResponse:
-
+class StripeResponse(object):
def __init__(self, body, code, headers):
self.body = body
self.code = code |
eaa2ef92eba11d44bf5159342e314b932d79f58d | fedora/__init__.py | fedora/__init__.py | # Copyright 2008 Red Hat, Inc.
# This file is part of python-fedora
#
# python-fedora is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# python-fedora is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with python-fedora; if not, see <http://www.gnu.org/licenses/>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
'''
Python Fedora
Modules to communicate with and help implement Fedora Services.
'''
import gettext
translation = gettext.translation('python-fedora', '/usr/share/locale',
fallback=True)
_ = translation.ugettext
from fedora import release
__version__ = release.VERSION
# Needed for our unit tests
from fedora.wsgi.test import websetup
__all__ = ('_', 'release', '__version__',
'accounts', 'client', 'tg', 'websetup')
| # Copyright 2008 Red Hat, Inc.
# This file is part of python-fedora
#
# python-fedora is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# python-fedora is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with python-fedora; if not, see <http://www.gnu.org/licenses/>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
'''
Python Fedora
Modules to communicate with and help implement Fedora Services.
'''
import gettext
translation = gettext.translation('python-fedora', '/usr/share/locale',
fallback=True)
_ = translation.ugettext
from fedora import release
__version__ = release.VERSION
__all__ = ('_', 'release', '__version__',
'accounts', 'client', 'tg', 'websetup')
| Undo the webtest import... it's causing runtime failiure and unittests are currently broken anyway. | Undo the webtest import... it's causing runtime failiure and unittests are
currently broken anyway.
| Python | lgpl-2.1 | fedora-infra/python-fedora | ---
+++
@@ -31,8 +31,5 @@
from fedora import release
__version__ = release.VERSION
-# Needed for our unit tests
-from fedora.wsgi.test import websetup
-
__all__ = ('_', 'release', '__version__',
'accounts', 'client', 'tg', 'websetup') |
b4061152064269f8848c374cf81a867a9c0a7388 | latex/errors.py | latex/errors.py | import re
LATEX_ERR_RE = re.compile(r'(?P<filename>[^:]+):(?P<line>[0-9]*):'
r'\s*(?P<error>.*)')
def parse_log(log, context_size=3):
lines = log.split('\n')
errors = []
for n, line in enumerate(lines):
m = LATEX_ERR_RE.match(line)
if m:
err = m.groupdict().copy()
err['context'] = lines[n:n+context_size]
err['line'] = int(err['line'])
errors.append(err)
return errors
| import re
LATEX_ERR_RE = re.compile(r'(?P<filename>[^:]+):(?P<line>[0-9]*):'
r'\s*(?P<error>.*)')
def parse_log(log, context_size=3):
lines = log.splitlines()
errors = []
for n, line in enumerate(lines):
m = LATEX_ERR_RE.match(line)
if m:
err = m.groupdict().copy()
err['context'] = lines[n:n+context_size]
err['line'] = int(err['line'])
errors.append(err)
return errors
| Use splitlines instead of split on new line. | Use splitlines instead of split on new line.
| Python | bsd-3-clause | mbr/latex | ---
+++
@@ -5,7 +5,7 @@
def parse_log(log, context_size=3):
- lines = log.split('\n')
+ lines = log.splitlines()
errors = []
for n, line in enumerate(lines): |
662287761b8549a86d3fb8c05ec37d47491da120 | flatblocks/urls.py | flatblocks/urls.py | from django.contrib.admin.views.decorators import staff_member_required
from django.urls import re_path
from flatblocks.views import edit
urlpatterns = [
re_path("^edit/(?P<pk>\d+)/$", staff_member_required(edit), name="flatblocks-edit"),
]
| from django.contrib.admin.views.decorators import staff_member_required
from django.urls import re_path
from flatblocks.views import edit
urlpatterns = [
re_path(
r"^edit/(?P<pk>\d+)/$",
staff_member_required(edit),
name="flatblocks-edit",
),
]
| Use raw string notation for regular expression. | Use raw string notation for regular expression.
| Python | bsd-3-clause | funkybob/django-flatblocks,funkybob/django-flatblocks | ---
+++
@@ -3,5 +3,9 @@
from flatblocks.views import edit
urlpatterns = [
- re_path("^edit/(?P<pk>\d+)/$", staff_member_required(edit), name="flatblocks-edit"),
+ re_path(
+ r"^edit/(?P<pk>\d+)/$",
+ staff_member_required(edit),
+ name="flatblocks-edit",
+ ),
] |
1cc6ec9f328d3ce045a4a1a50138b11c0b23cc3a | pyfr/ctypesutil.py | pyfr/ctypesutil.py | # -*- coding: utf-8 -*-
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
lname = platform_libname(name)
sdirs = platform_libdirs()
# First attempt to utilise the system search path
try:
return ctypes.CDLL(lname)
# Otherwise, if this fails then run our own search
except OSError:
for sd in sdirs:
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
| # -*- coding: utf-8 -*-
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
# If an explicit override has been given then use it
lpath = os.environ.get('PYFR_{0}_LIBRARY_PATH'.format(name.upper()))
if lpath:
return ctypes.CDLL(lpath)
# Otherwise synthesise the library name and start searching
lname = platform_libname(name)
# Start with system search path
try:
return ctypes.CDLL(lname)
# ..and if this fails then run our own search
except OSError:
for sd in platform_libdirs():
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
| Enable library paths to be explicitly specified. | Enable library paths to be explicitly specified.
All shared libraries loaded through the load_library function
can bow be specified explicitly through a suitable environmental
variable
PYFR_<LIB>_LIBRARY_PATH=/path/to/lib.here
where <LIB> corresponds to the name of the library, e.g. METIS.
| Python | bsd-3-clause | BrianVermeire/PyFR | ---
+++
@@ -14,15 +14,20 @@
def load_library(name):
+ # If an explicit override has been given then use it
+ lpath = os.environ.get('PYFR_{0}_LIBRARY_PATH'.format(name.upper()))
+ if lpath:
+ return ctypes.CDLL(lpath)
+
+ # Otherwise synthesise the library name and start searching
lname = platform_libname(name)
- sdirs = platform_libdirs()
- # First attempt to utilise the system search path
+ # Start with system search path
try:
return ctypes.CDLL(lname)
- # Otherwise, if this fails then run our own search
+ # ..and if this fails then run our own search
except OSError:
- for sd in sdirs:
+ for sd in platform_libdirs():
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError: |
8237291e194aa900857fe382d0b8cefb7806c331 | ocradmin/ocrmodels/models.py | ocradmin/ocrmodels/models.py | from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
# OCR model, erm, model
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User)
derived_from = models.ForeignKey("self", null=True, blank=True)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True)
public = models.BooleanField(default=True)
file = models.FileField(upload_to="models")
type = models.CharField(max_length=20,
choices=[("char", "Character"), ("lang", "Language")])
app = models.CharField(max_length=20,
choices=[("ocropus", "Ocropus"), ("tesseract", "Tesseract")])
def __unicode__(self):
"""
String representation.
"""
return self.name
| from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
# OCR model, erm, model
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User)
derived_from = models.ForeignKey("self", null=True, blank=True)
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(null=True, blank=True)
created_on = models.DateField(auto_now_add=True)
updated_on = models.DateField(null=True, blank=True)
public = models.BooleanField(default=True)
file = models.FileField(upload_to="models")
type = models.CharField(max_length=20,
choices=[("char", "Character"), ("lang", "Language")])
app = models.CharField(max_length=20,
choices=[("ocropus", "Ocropus"), ("tesseract", "Tesseract")])
def __unicode__(self):
"""
String representation.
"""
return "<%s: %s>" % (self.__class__.__name__, self.name)
| Improve unicode method. Whitespace cleanup | Improve unicode method. Whitespace cleanup
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium | ---
+++
@@ -23,11 +23,10 @@
app = models.CharField(max_length=20,
choices=[("ocropus", "Ocropus"), ("tesseract", "Tesseract")])
-
def __unicode__(self):
"""
String representation.
"""
- return self.name
+ return "<%s: %s>" % (self.__class__.__name__, self.name)
-
+ |
146d9eb75b55298886a3860976b19be5b42825b2 | deriva/core/base_cli.py | deriva/core/base_cli.py | import argparse
import logging
from . import init_logging
class BaseCLI(object):
def __init__(self, description, epilog, version=None):
assert version
self.version = version
self.parser = argparse.ArgumentParser(description=description, epilog=epilog)
self.parser.add_argument(
'--version', action='version', version=self.version, help="Print version and exit.")
self.parser.add_argument(
'--quiet', action="store_true", help="Suppress logging output.")
self.parser.add_argument(
'--debug', action="store_true", help="Enable debug logging output.")
self.parser.add_argument(
'--host', metavar='<fqhn>', help="Optional fully qualified host name to connect to.")
self.parser.add_argument(
'--config-file', metavar='<file>', help="Optional path to a configuration file.")
self.parser.add_argument(
'--credential-file', metavar='<file>', help="Optional path to a credential file.")
def remove_options(self, options):
for option in options:
for action in self.parser._actions:
if vars(action)['option_strings'][0] == option:
self.parser._handle_conflict_resolve(None, [(option, action)])
break
def parse_cli(self):
args = self.parser.parse_args()
init_logging(level=logging.ERROR if args.quiet else (logging.DEBUG if args.debug else logging.INFO))
return args
| import argparse
import logging
from . import init_logging
class BaseCLI(object):
def __init__(self, description, epilog, version=None):
assert version, "A valid version string is required"
self.version = version
self.parser = argparse.ArgumentParser(description=description, epilog=epilog)
self.parser.add_argument(
'--version', action='version', version=self.version, help="Print version and exit.")
self.parser.add_argument(
'--quiet', action="store_true", help="Suppress logging output.")
self.parser.add_argument(
'--debug', action="store_true", help="Enable debug logging output.")
self.parser.add_argument(
'--host', metavar='<fqhn>', help="Optional fully qualified host name to connect to.")
self.parser.add_argument(
'--config-file', metavar='<file>', help="Optional path to a configuration file.")
self.parser.add_argument(
'--credential-file', metavar='<file>', help="Optional path to a credential file.")
def remove_options(self, options):
for option in options:
for action in self.parser._actions:
if vars(action)['option_strings'][0] == option:
self.parser._handle_conflict_resolve(None, [(option, action)])
break
def parse_cli(self):
args = self.parser.parse_args()
init_logging(level=logging.ERROR if args.quiet else (logging.DEBUG if args.debug else logging.INFO))
return args
| Add some detail text to assertion. | Add some detail text to assertion.
| Python | apache-2.0 | informatics-isi-edu/deriva-py | ---
+++
@@ -7,7 +7,8 @@
class BaseCLI(object):
def __init__(self, description, epilog, version=None):
- assert version
+ assert version, "A valid version string is required"
+
self.version = version
self.parser = argparse.ArgumentParser(description=description, epilog=epilog) |
e26b95803707e74dba2cc451476466eefc156f8f | tests/test_coefficient.py | tests/test_coefficient.py | # -*- coding: utf-8 -*-
from nose.tools import assert_equal
from openfisca_france.model.prelevements_obligatoires.prelevements_sociaux.cotisations_sociales.allegements import *
from openfisca_core.periods import *
from openfisca_france import FranceTaxBenefitSystem
def test_coefficient_proratisation_only_contract_periods():
tax_benefit_system = FranceTaxBenefitSystem()
scenario = tax_benefit_system.new_scenario()
scenario.init_single_entity(period='2017-11',
parent1=dict(salaire_de_base=2300,
effectif_entreprise=1,
code_postal_entreprise="75001",
categorie_salarie=u'prive_non_cadre',
contrat_de_travail_debut='2017-11-1',
contrat_de_travail_fin='2017-11-30',
allegement_fillon_mode_recouvrement=u'progressif'))
simulation = scenario.new_simulation()
assert_equal(simulation.calculate('coefficient_proratisation','2017-11'),1)
assert_equal(simulation.calculate('coefficient_proratisation','2017-12'),0)
assert_equal(simulation.calculate('coefficient_proratisation','2017-10'),0)
assert_equal(simulation.calculate_add('coefficient_proratisation','2017'),1)
| # -*- coding: utf-8 -*-
from nose.tools import assert_equal
from openfisca_france.model.prelevements_obligatoires.prelevements_sociaux.cotisations_sociales.allegements import *
from openfisca_core.periods import *
from openfisca_france import FranceTaxBenefitSystem
def test_coefficient_proratisation_only_contract_periods():
tax_benefit_system = FranceTaxBenefitSystem()
scenario = tax_benefit_system.new_scenario()
scenario.init_single_entity(period='2017-11',
parent1=dict(salaire_de_base=2300,
effectif_entreprise=1,
code_postal_entreprise="75001",
categorie_salarie=u'prive_non_cadre',
contrat_de_travail_debut='2017-11-1',
contrat_de_travail_fin='2017-12-01',
allegement_fillon_mode_recouvrement=u'progressif'))
simulation = scenario.new_simulation()
assert_equal(simulation.calculate('coefficient_proratisation','2017-11'),1)
assert_equal(simulation.calculate('coefficient_proratisation','2017-12'),0)
assert_equal(simulation.calculate('coefficient_proratisation','2017-10'),0)
assert_equal(simulation.calculate_add('coefficient_proratisation','2017'),1)
| Fix evaluation date & test period | Fix evaluation date & test period
| Python | agpl-3.0 | sgmap/openfisca-france,sgmap/openfisca-france,antoinearnoud/openfisca-france,antoinearnoud/openfisca-france | ---
+++
@@ -15,7 +15,7 @@
code_postal_entreprise="75001",
categorie_salarie=u'prive_non_cadre',
contrat_de_travail_debut='2017-11-1',
- contrat_de_travail_fin='2017-11-30',
+ contrat_de_travail_fin='2017-12-01',
allegement_fillon_mode_recouvrement=u'progressif'))
simulation = scenario.new_simulation()
assert_equal(simulation.calculate('coefficient_proratisation','2017-11'),1) |
02df4f76b61556edc04869e8e70bf63c3df75ef3 | humbug/backends.py | humbug/backends.py | from django.contrib.auth.models import User
class EmailAuthBackend(object):
"""
Email Authentication Backend
Allows a user to sign in using an email/password pair rather than
a username/password pair.
"""
def authenticate(self, username=None, password=None):
""" Authenticate a user based on email address as the user name. """
if username is None or password is None:
# Return immediately. Otherwise we will look for a SQL row with
# NULL username. While that's probably harmless, it's needless
# exposure.
return None
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
""" Get a User object from the user_id. """
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
| from django.contrib.auth.models import User
class EmailAuthBackend(object):
"""
Email Authentication Backend
Allows a user to sign in using an email/password pair rather than
a username/password pair.
"""
def authenticate(self, username=None, password=None):
""" Authenticate a user based on email address as the user name. """
if username is None or password is None:
# Return immediately. Otherwise we will look for a SQL row with
# NULL username. While that's probably harmless, it's needless
# exposure.
return None
try:
user = User.objects.get(email__iexact=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
""" Get a User object from the user_id. """
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
| Allow case-insensitive email addresses when doing authentication | Allow case-insensitive email addresses when doing authentication
(imported from commit b52e39c7f706a2107b5d86e8e18293a46ed9e6ff)
| Python | apache-2.0 | armooo/zulip,qq1012803704/zulip,ikasumiwt/zulip,hj3938/zulip,nicholasbs/zulip,kou/zulip,pradiptad/zulip,jackrzhang/zulip,codeKonami/zulip,alliejones/zulip,Vallher/zulip,bastianh/zulip,natanovia/zulip,so0k/zulip,noroot/zulip,lfranchi/zulip,bitemyapp/zulip,wavelets/zulip,showell/zulip,codeKonami/zulip,praveenaki/zulip,dnmfarrell/zulip,mahim97/zulip,arpitpanwar/zulip,proliming/zulip,schatt/zulip,MariaFaBella85/zulip,grave-w-grave/zulip,akuseru/zulip,KJin99/zulip,wdaher/zulip,peguin40/zulip,avastu/zulip,PaulPetring/zulip,m1ssou/zulip,grave-w-grave/zulip,xuxiao/zulip,huangkebo/zulip,udxxabp/zulip,swinghu/zulip,TigorC/zulip,codeKonami/zulip,dattatreya303/zulip,arpitpanwar/zulip,synicalsyntax/zulip,kou/zulip,shubhamdhama/zulip,willingc/zulip,wweiradio/zulip,shaunstanislaus/zulip,AZtheAsian/zulip,kaiyuanheshang/zulip,isht3/zulip,easyfmxu/zulip,shaunstanislaus/zulip,mahim97/zulip,vabs22/zulip,suxinde2009/zulip,vabs22/zulip,jessedhillon/zulip,umkay/zulip,glovebx/zulip,zacps/zulip,zwily/zulip,KJin99/zulip,Galexrt/zulip,nicholasbs/zulip,ApsOps/zulip,synicalsyntax/zulip,so0k/zulip,itnihao/zulip,schatt/zulip,jonesgithub/zulip,hj3938/zulip,jerryge/zulip,Diptanshu8/zulip,EasonYi/zulip,punchagan/zulip,technicalpickles/zulip,joyhchen/zulip,aakash-cr7/zulip,adnanh/zulip,qq1012803704/zulip,yocome/zulip,wangdeshui/zulip,rht/zulip,blaze225/zulip,susansls/zulip,proliming/zulip,ashwinirudrappa/zulip,levixie/zulip,zofuthan/zulip,LeeRisk/zulip,stamhe/zulip,yocome/zulip,tdr130/zulip,KJin99/zulip,joshisa/zulip,joshisa/zulip,Jianchun1/zulip,peiwei/zulip,wdaher/zulip,joshisa/zulip,JanzTam/zulip,amyliu345/zulip,ufosky-server/zulip,pradiptad/zulip,cosmicAsymmetry/zulip,bluesea/zulip,yocome/zulip,kokoar/zulip,cosmicAsymmetry/zulip,Diptanshu8/zulip,firstblade/zulip,timabbott/zulip,amallia/zulip,bowlofstew/zulip,so0k/zulip,hj3938/zulip,jainayush975/zulip,Gabriel0402/zulip,KJin99/zulip,seapasulli/zulip,hayderimran7/zulip,MariaFaBella85/zulip,wangdeshui/zulip,m1ssou/zulip,Batterfii/zulip,jrowan/zulip,zwily/zulip,fw1121/zulip,so0k/zulip,arpitpanwar/zulip,j831/zulip,souravbadami/zulip,joyhchen/zulip,hackerkid/zulip,hustlzp/zulip,udxxabp/zulip,hengqujushi/zulip,tbutter/zulip,ipernet/zulip,glovebx/zulip,hafeez3000/zulip,peiwei/zulip,alliejones/zulip,sharmaeklavya2/zulip,arpith/zulip,PaulPetring/zulip,dotcool/zulip,qq1012803704/zulip,levixie/zulip,aliceriot/zulip,natanovia/zulip,levixie/zulip,Galexrt/zulip,Juanvulcano/zulip,yuvipanda/zulip,Frouk/zulip,udxxabp/zulip,Cheppers/zulip,showell/zulip,jeffcao/zulip,TigorC/zulip,dawran6/zulip,saitodisse/zulip,kou/zulip,MayB/zulip,nicholasbs/zulip,deer-hope/zulip,gkotian/zulip,ericzhou2008/zulip,dhcrzf/zulip,gkotian/zulip,easyfmxu/zulip,praveenaki/zulip,swinghu/zulip,tdr130/zulip,souravbadami/zulip,tommyip/zulip,zorojean/zulip,Galexrt/zulip,suxinde2009/zulip,ApsOps/zulip,shubhamdhama/zulip,isht3/zulip,amyliu345/zulip,peiwei/zulip,niftynei/zulip,KJin99/zulip,huangkebo/zulip,qq1012803704/zulip,dxq-git/zulip,seapasulli/zulip,jackrzhang/zulip,dnmfarrell/zulip,dotcool/zulip,zhaoweigg/zulip,aps-sids/zulip,gigawhitlocks/zulip,dawran6/zulip,m1ssou/zulip,xuanhan863/zulip,dxq-git/zulip,bitemyapp/zulip,hj3938/zulip,arpith/zulip,hengqujushi/zulip,ufosky-server/zulip,brockwhittaker/zulip,bitemyapp/zulip,shubhamdhama/zulip,ikasumiwt/zulip,bowlofstew/zulip,hackerkid/zulip,aps-sids/zulip,bssrdf/zulip,bastianh/zulip,littledogboy/zulip,shaunstanislaus/zulip,deer-hope/zulip,firstblade/zulip,rishig/zulip,xuxiao/zulip,hengqujushi/zulip,synicalsyntax/zulip,m1ssou/zulip,hayderimran7/zulip,Qgap/zulip,johnnygaddarr/zulip,PhilSk/zulip,vikas-parashar/zulip,ufosky-server/zulip,guiquanz/zulip,yuvipanda/zulip,jonesgithub/zulip,ApsOps/zulip,JPJPJPOPOP/zulip,Qgap/zulip,umkay/zulip,sup95/zulip,johnny9/zulip,yuvipanda/zulip,xuanhan863/zulip,nicholasbs/zulip,ikasumiwt/zulip,esander91/zulip,bitemyapp/zulip,so0k/zulip,sonali0901/zulip,themass/zulip,rishig/zulip,johnnygaddarr/zulip,voidException/zulip,he15his/zulip,souravbadami/zulip,babbage/zulip,alliejones/zulip,bluesea/zulip,j831/zulip,rht/zulip,deer-hope/zulip,PhilSk/zulip,gigawhitlocks/zulip,xuanhan863/zulip,calvinleenyc/zulip,souravbadami/zulip,willingc/zulip,kokoar/zulip,adnanh/zulip,RobotCaleb/zulip,reyha/zulip,PhilSk/zulip,EasonYi/zulip,AZtheAsian/zulip,tiansiyuan/zulip,babbage/zulip,Suninus/zulip,sonali0901/zulip,calvinleenyc/zulip,tbutter/zulip,ryanbackman/zulip,jimmy54/zulip,MayB/zulip,deer-hope/zulip,andersk/zulip,lfranchi/zulip,ApsOps/zulip,jrowan/zulip,arpitpanwar/zulip,fw1121/zulip,LAndreas/zulip,proliming/zulip,johnnygaddarr/zulip,EasonYi/zulip,MariaFaBella85/zulip,technicalpickles/zulip,yuvipanda/zulip,kaiyuanheshang/zulip,voidException/zulip,KingxBanana/zulip,hackerkid/zulip,zwily/zulip,itnihao/zulip,hustlzp/zulip,ericzhou2008/zulip,luyifan/zulip,babbage/zulip,umkay/zulip,Juanvulcano/zulip,amallia/zulip,wweiradio/zulip,ufosky-server/zulip,dhcrzf/zulip,isht3/zulip,krtkmj/zulip,hustlzp/zulip,developerfm/zulip,MayB/zulip,itnihao/zulip,ahmadassaf/zulip,mahim97/zulip,isht3/zulip,RobotCaleb/zulip,vabs22/zulip,m1ssou/zulip,ryansnowboarder/zulip,hafeez3000/zulip,samatdav/zulip,ipernet/zulip,fw1121/zulip,christi3k/zulip,voidException/zulip,SmartPeople/zulip,udxxabp/zulip,thomasboyt/zulip,kokoar/zulip,hustlzp/zulip,PhilSk/zulip,jainayush975/zulip,bssrdf/zulip,seapasulli/zulip,xuxiao/zulip,ericzhou2008/zulip,Drooids/zulip,Galexrt/zulip,amyliu345/zulip,fw1121/zulip,jphilipsen05/zulip,joshisa/zulip,yuvipanda/zulip,zachallaun/zulip,mdavid/zulip,Suninus/zulip,zacps/zulip,vikas-parashar/zulip,verma-varsha/zulip,reyha/zulip,DazWorrall/zulip,ipernet/zulip,AZtheAsian/zulip,Batterfii/zulip,saitodisse/zulip,akuseru/zulip,bastianh/zulip,dotcool/zulip,bluesea/zulip,fw1121/zulip,jeffcao/zulip,Juanvulcano/zulip,huangkebo/zulip,tommyip/zulip,vakila/zulip,armooo/zulip,PaulPetring/zulip,he15his/zulip,DazWorrall/zulip,Qgap/zulip,xuxiao/zulip,shrikrishnaholla/zulip,willingc/zulip,mahim97/zulip,rht/zulip,firstblade/zulip,zacps/zulip,easyfmxu/zulip,zachallaun/zulip,j831/zulip,samatdav/zulip,thomasboyt/zulip,Drooids/zulip,cosmicAsymmetry/zulip,fw1121/zulip,pradiptad/zulip,bluesea/zulip,deer-hope/zulip,Qgap/zulip,arpith/zulip,Jianchun1/zulip,jerryge/zulip,natanovia/zulip,paxapy/zulip,eeshangarg/zulip,Batterfii/zulip,Gabriel0402/zulip,PaulPetring/zulip,hustlzp/zulip,wweiradio/zulip,yuvipanda/zulip,yocome/zulip,Jianchun1/zulip,nicholasbs/zulip,akuseru/zulip,huangkebo/zulip,showell/zulip,brainwane/zulip,guiquanz/zulip,yocome/zulip,LAndreas/zulip,armooo/zulip,ryansnowboarder/zulip,zofuthan/zulip,Vallher/zulip,babbage/zulip,shubhamdhama/zulip,themass/zulip,ryanbackman/zulip,bssrdf/zulip,bitemyapp/zulip,hafeez3000/zulip,SmartPeople/zulip,EasonYi/zulip,jphilipsen05/zulip,lfranchi/zulip,avastu/zulip,punchagan/zulip,shubhamdhama/zulip,willingc/zulip,MariaFaBella85/zulip,brainwane/zulip,Gabriel0402/zulip,shaunstanislaus/zulip,Galexrt/zulip,jessedhillon/zulip,ipernet/zulip,jonesgithub/zulip,TigorC/zulip,praveenaki/zulip,huangkebo/zulip,ApsOps/zulip,ipernet/zulip,peguin40/zulip,hengqujushi/zulip,jimmy54/zulip,AZtheAsian/zulip,willingc/zulip,schatt/zulip,peiwei/zulip,DazWorrall/zulip,zorojean/zulip,gigawhitlocks/zulip,rishig/zulip,kokoar/zulip,jessedhillon/zulip,karamcnair/zulip,Suninus/zulip,moria/zulip,rht/zulip,Frouk/zulip,pradiptad/zulip,synicalsyntax/zulip,rishig/zulip,ikasumiwt/zulip,xuanhan863/zulip,amanharitsh123/zulip,ufosky-server/zulip,stamhe/zulip,PaulPetring/zulip,grave-w-grave/zulip,sharmaeklavya2/zulip,stamhe/zulip,RobotCaleb/zulip,saitodisse/zulip,atomic-labs/zulip,developerfm/zulip,udxxabp/zulip,zorojean/zulip,wavelets/zulip,jessedhillon/zulip,dwrpayne/zulip,johnnygaddarr/zulip,littledogboy/zulip,arpitpanwar/zulip,thomasboyt/zulip,andersk/zulip,levixie/zulip,mohsenSy/zulip,RobotCaleb/zulip,zofuthan/zulip,ashwinirudrappa/zulip,kou/zulip,showell/zulip,hafeez3000/zulip,Gabriel0402/zulip,Vallher/zulip,alliejones/zulip,punchagan/zulip,schatt/zulip,joyhchen/zulip,wavelets/zulip,he15his/zulip,JPJPJPOPOP/zulip,amallia/zulip,brainwane/zulip,ashwinirudrappa/zulip,timabbott/zulip,LeeRisk/zulip,hackerkid/zulip,peiwei/zulip,hengqujushi/zulip,Diptanshu8/zulip,tbutter/zulip,jimmy54/zulip,Drooids/zulip,jeffcao/zulip,noroot/zulip,sup95/zulip,JanzTam/zulip,aliceriot/zulip,gkotian/zulip,joyhchen/zulip,EasonYi/zulip,lfranchi/zulip,armooo/zulip,arpitpanwar/zulip,developerfm/zulip,nicholasbs/zulip,jackrzhang/zulip,Galexrt/zulip,jackrzhang/zulip,hayderimran7/zulip,wavelets/zulip,moria/zulip,qq1012803704/zulip,karamcnair/zulip,stamhe/zulip,timabbott/zulip,AZtheAsian/zulip,shubhamdhama/zulip,vakila/zulip,sonali0901/zulip,voidException/zulip,zulip/zulip,ikasumiwt/zulip,rht/zulip,dwrpayne/zulip,suxinde2009/zulip,shrikrishnaholla/zulip,arpith/zulip,joyhchen/zulip,samatdav/zulip,zachallaun/zulip,Cheppers/zulip,christi3k/zulip,timabbott/zulip,SmartPeople/zulip,xuanhan863/zulip,pradiptad/zulip,timabbott/zulip,adnanh/zulip,brainwane/zulip,isht3/zulip,tbutter/zulip,easyfmxu/zulip,umkay/zulip,ahmadassaf/zulip,wangdeshui/zulip,armooo/zulip,mohsenSy/zulip,atomic-labs/zulip,luyifan/zulip,saitodisse/zulip,sharmaeklavya2/zulip,gkotian/zulip,wweiradio/zulip,samatdav/zulip,Drooids/zulip,zachallaun/zulip,jimmy54/zulip,KingxBanana/zulip,peiwei/zulip,bitemyapp/zulip,xuanhan863/zulip,codeKonami/zulip,ryanbackman/zulip,firstblade/zulip,natanovia/zulip,bluesea/zulip,zofuthan/zulip,natanovia/zulip,kou/zulip,wangdeshui/zulip,jphilipsen05/zulip,DazWorrall/zulip,brockwhittaker/zulip,dxq-git/zulip,ufosky-server/zulip,susansls/zulip,firstblade/zulip,wdaher/zulip,shaunstanislaus/zulip,esander91/zulip,armooo/zulip,verma-varsha/zulip,LeeRisk/zulip,huangkebo/zulip,johnny9/zulip,eastlhu/zulip,showell/zulip,KJin99/zulip,rishig/zulip,moria/zulip,hayderimran7/zulip,Batterfii/zulip,andersk/zulip,aps-sids/zulip,dattatreya303/zulip,Jianchun1/zulip,codeKonami/zulip,mahim97/zulip,dawran6/zulip,arpith/zulip,aps-sids/zulip,bitemyapp/zulip,TigorC/zulip,zwily/zulip,bastianh/zulip,lfranchi/zulip,JanzTam/zulip,wavelets/zulip,johnnygaddarr/zulip,zulip/zulip,tommyip/zulip,punchagan/zulip,joshisa/zulip,brockwhittaker/zulip,armooo/zulip,paxapy/zulip,KingxBanana/zulip,eeshangarg/zulip,sonali0901/zulip,zulip/zulip,cosmicAsymmetry/zulip,littledogboy/zulip,technicalpickles/zulip,andersk/zulip,Suninus/zulip,j831/zulip,Batterfii/zulip,synicalsyntax/zulip,tommyip/zulip,lfranchi/zulip,hayderimran7/zulip,zwily/zulip,zhaoweigg/zulip,SmartPeople/zulip,Suninus/zulip,RobotCaleb/zulip,jrowan/zulip,paxapy/zulip,ikasumiwt/zulip,Cheppers/zulip,samatdav/zulip,willingc/zulip,dhcrzf/zulip,sharmaeklavya2/zulip,kokoar/zulip,MayB/zulip,xuanhan863/zulip,akuseru/zulip,umkay/zulip,moria/zulip,luyifan/zulip,zorojean/zulip,vikas-parashar/zulip,thomasboyt/zulip,niftynei/zulip,dnmfarrell/zulip,sonali0901/zulip,ericzhou2008/zulip,umkay/zulip,krtkmj/zulip,bowlofstew/zulip,glovebx/zulip,paxapy/zulip,technicalpickles/zulip,tbutter/zulip,tiansiyuan/zulip,jainayush975/zulip,themass/zulip,avastu/zulip,reyha/zulip,MariaFaBella85/zulip,Frouk/zulip,timabbott/zulip,mansilladev/zulip,gkotian/zulip,vaidap/zulip,m1ssou/zulip,luyifan/zulip,sonali0901/zulip,pradiptad/zulip,aliceriot/zulip,calvinleenyc/zulip,krtkmj/zulip,jeffcao/zulip,jackrzhang/zulip,punchagan/zulip,Juanvulcano/zulip,alliejones/zulip,amanharitsh123/zulip,johnny9/zulip,jerryge/zulip,themass/zulip,jonesgithub/zulip,christi3k/zulip,cosmicAsymmetry/zulip,easyfmxu/zulip,ashwinirudrappa/zulip,praveenaki/zulip,mdavid/zulip,LeeRisk/zulip,MayB/zulip,technicalpickles/zulip,schatt/zulip,hustlzp/zulip,xuxiao/zulip,avastu/zulip,reyha/zulip,developerfm/zulip,dotcool/zulip,jimmy54/zulip,itnihao/zulip,itnihao/zulip,guiquanz/zulip,shrikrishnaholla/zulip,SmartPeople/zulip,susansls/zulip,kaiyuanheshang/zulip,ashwinirudrappa/zulip,aakash-cr7/zulip,thomasboyt/zulip,bluesea/zulip,zorojean/zulip,zwily/zulip,synicalsyntax/zulip,JPJPJPOPOP/zulip,avastu/zulip,aliceriot/zulip,sharmaeklavya2/zulip,PhilSk/zulip,developerfm/zulip,LeeRisk/zulip,aakash-cr7/zulip,Cheppers/zulip,wangdeshui/zulip,bssrdf/zulip,timabbott/zulip,jeffcao/zulip,ryansnowboarder/zulip,punchagan/zulip,m1ssou/zulip,tommyip/zulip,zhaoweigg/zulip,Drooids/zulip,blaze225/zulip,stamhe/zulip,mansilladev/zulip,Juanvulcano/zulip,shaunstanislaus/zulip,dotcool/zulip,peguin40/zulip,EasonYi/zulip,alliejones/zulip,johnnygaddarr/zulip,jessedhillon/zulip,jonesgithub/zulip,Frouk/zulip,Vallher/zulip,zhaoweigg/zulip,deer-hope/zulip,hj3938/zulip,zorojean/zulip,seapasulli/zulip,krtkmj/zulip,natanovia/zulip,kaiyuanheshang/zulip,bowlofstew/zulip,Qgap/zulip,ahmadassaf/zulip,peiwei/zulip,jimmy54/zulip,esander91/zulip,ericzhou2008/zulip,wweiradio/zulip,AZtheAsian/zulip,schatt/zulip,MariaFaBella85/zulip,brainwane/zulip,wangdeshui/zulip,karamcnair/zulip,shrikrishnaholla/zulip,moria/zulip,vaidap/zulip,Galexrt/zulip,peguin40/zulip,aliceriot/zulip,jessedhillon/zulip,huangkebo/zulip,amyliu345/zulip,swinghu/zulip,technicalpickles/zulip,ApsOps/zulip,eeshangarg/zulip,aps-sids/zulip,MariaFaBella85/zulip,ericzhou2008/zulip,babbage/zulip,gigawhitlocks/zulip,TigorC/zulip,dnmfarrell/zulip,luyifan/zulip,ipernet/zulip,eeshangarg/zulip,niftynei/zulip,wweiradio/zulip,so0k/zulip,gigawhitlocks/zulip,susansls/zulip,themass/zulip,ahmadassaf/zulip,cosmicAsymmetry/zulip,gkotian/zulip,gigawhitlocks/zulip,dotcool/zulip,jonesgithub/zulip,ericzhou2008/zulip,dnmfarrell/zulip,littledogboy/zulip,akuseru/zulip,mdavid/zulip,easyfmxu/zulip,dhcrzf/zulip,niftynei/zulip,mohsenSy/zulip,voidException/zulip,ahmadassaf/zulip,ryanbackman/zulip,xuxiao/zulip,wdaher/zulip,grave-w-grave/zulip,DazWorrall/zulip,verma-varsha/zulip,vaidap/zulip,andersk/zulip,yocome/zulip,seapasulli/zulip,Frouk/zulip,mohsenSy/zulip,christi3k/zulip,zacps/zulip,LAndreas/zulip,mdavid/zulip,ApsOps/zulip,johnny9/zulip,swinghu/zulip,ryansnowboarder/zulip,xuxiao/zulip,vaidap/zulip,showell/zulip,johnny9/zulip,jackrzhang/zulip,Cheppers/zulip,Batterfii/zulip,hackerkid/zulip,luyifan/zulip,tiansiyuan/zulip,eastlhu/zulip,souravbadami/zulip,peguin40/zulip,LAndreas/zulip,guiquanz/zulip,avastu/zulip,noroot/zulip,mansilladev/zulip,thomasboyt/zulip,Diptanshu8/zulip,dawran6/zulip,bastianh/zulip,technicalpickles/zulip,littledogboy/zulip,zulip/zulip,bowlofstew/zulip,vaidap/zulip,proliming/zulip,mansilladev/zulip,praveenaki/zulip,hafeez3000/zulip,jerryge/zulip,karamcnair/zulip,noroot/zulip,samatdav/zulip,umkay/zulip,ryansnowboarder/zulip,Gabriel0402/zulip,ufosky-server/zulip,joyhchen/zulip,Diptanshu8/zulip,reyha/zulip,seapasulli/zulip,jphilipsen05/zulip,hengqujushi/zulip,bssrdf/zulip,andersk/zulip,proliming/zulip,tbutter/zulip,jrowan/zulip,paxapy/zulip,isht3/zulip,Gabriel0402/zulip,glovebx/zulip,esander91/zulip,nicholasbs/zulip,KJin99/zulip,niftynei/zulip,Drooids/zulip,dxq-git/zulip,dhcrzf/zulip,jessedhillon/zulip,luyifan/zulip,gigawhitlocks/zulip,glovebx/zulip,dwrpayne/zulip,Frouk/zulip,bowlofstew/zulip,firstblade/zulip,guiquanz/zulip,willingc/zulip,hafeez3000/zulip,moria/zulip,natanovia/zulip,swinghu/zulip,itnihao/zulip,tdr130/zulip,babbage/zulip,Suninus/zulip,tiansiyuan/zulip,suxinde2009/zulip,avastu/zulip,dnmfarrell/zulip,dattatreya303/zulip,KingxBanana/zulip,jainayush975/zulip,itnihao/zulip,rht/zulip,mansilladev/zulip,dxq-git/zulip,adnanh/zulip,amallia/zulip,LeeRisk/zulip,alliejones/zulip,jainayush975/zulip,MayB/zulip,Batterfii/zulip,vikas-parashar/zulip,ryansnowboarder/zulip,dwrpayne/zulip,ryanbackman/zulip,sup95/zulip,calvinleenyc/zulip,karamcnair/zulip,mdavid/zulip,jainayush975/zulip,wdaher/zulip,ahmadassaf/zulip,aakash-cr7/zulip,zachallaun/zulip,jrowan/zulip,calvinleenyc/zulip,saitodisse/zulip,RobotCaleb/zulip,dwrpayne/zulip,sup95/zulip,mdavid/zulip,seapasulli/zulip,souravbadami/zulip,kaiyuanheshang/zulip,ahmadassaf/zulip,KingxBanana/zulip,zorojean/zulip,eeshangarg/zulip,brainwane/zulip,codeKonami/zulip,guiquanz/zulip,christi3k/zulip,noroot/zulip,zofuthan/zulip,jimmy54/zulip,amanharitsh123/zulip,andersk/zulip,dwrpayne/zulip,dhcrzf/zulip,littledogboy/zulip,yuvipanda/zulip,dattatreya303/zulip,Jianchun1/zulip,kaiyuanheshang/zulip,levixie/zulip,hengqujushi/zulip,joshisa/zulip,hustlzp/zulip,LeeRisk/zulip,jphilipsen05/zulip,saitodisse/zulip,jerryge/zulip,atomic-labs/zulip,kou/zulip,qq1012803704/zulip,Vallher/zulip,amallia/zulip,kaiyuanheshang/zulip,wweiradio/zulip,proliming/zulip,guiquanz/zulip,RobotCaleb/zulip,amanharitsh123/zulip,wavelets/zulip,grave-w-grave/zulip,Frouk/zulip,wdaher/zulip,jeffcao/zulip,christi3k/zulip,wdaher/zulip,schatt/zulip,he15his/zulip,tbutter/zulip,proliming/zulip,deer-hope/zulip,rht/zulip,ashwinirudrappa/zulip,mohsenSy/zulip,blaze225/zulip,pradiptad/zulip,easyfmxu/zulip,verma-varsha/zulip,bssrdf/zulip,johnny9/zulip,eastlhu/zulip,DazWorrall/zulip,tommyip/zulip,hj3938/zulip,grave-w-grave/zulip,ipernet/zulip,firstblade/zulip,karamcnair/zulip,kokoar/zulip,blaze225/zulip,saitodisse/zulip,zofuthan/zulip,Diptanshu8/zulip,brockwhittaker/zulip,qq1012803704/zulip,synicalsyntax/zulip,adnanh/zulip,he15his/zulip,themass/zulip,stamhe/zulip,aps-sids/zulip,zulip/zulip,LAndreas/zulip,amanharitsh123/zulip,ryansnowboarder/zulip,vakila/zulip,j831/zulip,tommyip/zulip,joshisa/zulip,shrikrishnaholla/zulip,rishig/zulip,j831/zulip,praveenaki/zulip,swinghu/zulip,DazWorrall/zulip,glovebx/zulip,vabs22/zulip,zwily/zulip,vakila/zulip,jrowan/zulip,zulip/zulip,glovebx/zulip,dxq-git/zulip,mansilladev/zulip,TigorC/zulip,voidException/zulip,eastlhu/zulip,hackerkid/zulip,suxinde2009/zulip,zacps/zulip,sharmaeklavya2/zulip,krtkmj/zulip,aliceriot/zulip,zulip/zulip,vabs22/zulip,noroot/zulip,voidException/zulip,hj3938/zulip,MayB/zulip,amanharitsh123/zulip,dattatreya303/zulip,calvinleenyc/zulip,mdavid/zulip,rishig/zulip,praveenaki/zulip,verma-varsha/zulip,akuseru/zulip,PhilSk/zulip,arpith/zulip,dhcrzf/zulip,brainwane/zulip,stamhe/zulip,ikasumiwt/zulip,vakila/zulip,aps-sids/zulip,he15his/zulip,wangdeshui/zulip,shubhamdhama/zulip,eastlhu/zulip,amyliu345/zulip,Cheppers/zulip,hafeez3000/zulip,esander91/zulip,he15his/zulip,developerfm/zulip,Jianchun1/zulip,atomic-labs/zulip,tdr130/zulip,kokoar/zulip,zacps/zulip,eastlhu/zulip,bastianh/zulip,niftynei/zulip,amallia/zulip,punchagan/zulip,showell/zulip,suxinde2009/zulip,tdr130/zulip,Qgap/zulip,tdr130/zulip,zofuthan/zulip,bastianh/zulip,paxapy/zulip,akuseru/zulip,jerryge/zulip,kou/zulip,Vallher/zulip,jerryge/zulip,themass/zulip,jeffcao/zulip,jackrzhang/zulip,amyliu345/zulip,tiansiyuan/zulip,mahim97/zulip,adnanh/zulip,Vallher/zulip,dxq-git/zulip,eeshangarg/zulip,gkotian/zulip,noroot/zulip,karamcnair/zulip,EasonYi/zulip,arpitpanwar/zulip,KingxBanana/zulip,esander91/zulip,bssrdf/zulip,krtkmj/zulip,peguin40/zulip,bluesea/zulip,JanzTam/zulip,tiansiyuan/zulip,jphilipsen05/zulip,hayderimran7/zulip,developerfm/zulip,jonesgithub/zulip,swinghu/zulip,atomic-labs/zulip,zhaoweigg/zulip,vaidap/zulip,moria/zulip,sup95/zulip,dattatreya303/zulip,vabs22/zulip,LAndreas/zulip,susansls/zulip,shaunstanislaus/zulip,vikas-parashar/zulip,amallia/zulip,levixie/zulip,littledogboy/zulip,eeshangarg/zulip,brockwhittaker/zulip,PaulPetring/zulip,vakila/zulip,vakila/zulip,yocome/zulip,tiansiyuan/zulip,verma-varsha/zulip,udxxabp/zulip,dwrpayne/zulip,Juanvulcano/zulip,atomic-labs/zulip,zachallaun/zulip,hackerkid/zulip,vikas-parashar/zulip,levixie/zulip,sup95/zulip,wavelets/zulip,codeKonami/zulip,bowlofstew/zulip,reyha/zulip,JPJPJPOPOP/zulip,SmartPeople/zulip,dawran6/zulip,ryanbackman/zulip,zachallaun/zulip,atomic-labs/zulip,suxinde2009/zulip,susansls/zulip,LAndreas/zulip,JanzTam/zulip,JPJPJPOPOP/zulip,lfranchi/zulip,aakash-cr7/zulip,thomasboyt/zulip,JPJPJPOPOP/zulip,Gabriel0402/zulip,hayderimran7/zulip,Cheppers/zulip,fw1121/zulip,Suninus/zulip,dnmfarrell/zulip,Qgap/zulip,esander91/zulip,aakash-cr7/zulip,johnny9/zulip,eastlhu/zulip,babbage/zulip,Drooids/zulip,adnanh/zulip,aliceriot/zulip,so0k/zulip,johnnygaddarr/zulip,krtkmj/zulip,brockwhittaker/zulip,shrikrishnaholla/zulip,blaze225/zulip,PaulPetring/zulip,mansilladev/zulip,udxxabp/zulip,JanzTam/zulip,dawran6/zulip,ashwinirudrappa/zulip,dotcool/zulip,tdr130/zulip,zhaoweigg/zulip,zhaoweigg/zulip,shrikrishnaholla/zulip,mohsenSy/zulip,blaze225/zulip,JanzTam/zulip | ---
+++
@@ -17,7 +17,7 @@
return None
try:
- user = User.objects.get(email=username)
+ user = User.objects.get(email__iexact=username)
if user.check_password(password):
return user
except User.DoesNotExist: |
7a99695c7612609de294a6905820fad3e41afc43 | marketpulse/devices/models.py | marketpulse/devices/models.py | from django.db import models
class Device(models.Model):
"""Model for FfxOS devices data."""
model = models.CharField(max_length=120)
manufacturer = models.CharField(max_length=120)
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
| from django.db import models
class Device(models.Model):
"""Model for FfxOS devices data."""
model = models.CharField(max_length=120)
manufacturer = models.CharField(max_length=120)
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
class Meta:
ordering = ['manufacturer', 'model']
| Order devices by manufacturer and model. | Order devices by manufacturer and model.
| Python | mpl-2.0 | johngian/marketpulse,akatsoulas/marketpulse,johngian/marketpulse,mozilla/marketpulse,mozilla/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse | ---
+++
@@ -9,3 +9,6 @@
def __unicode__(self):
return '{0}, {1}'.format(self.manufacturer, self.model)
+
+ class Meta:
+ ordering = ['manufacturer', 'model'] |
a760beb8d66222b456b160344eb0b4b7fccbf84a | Lib/test/test_linuxaudiodev.py | Lib/test/test_linuxaudiodev.py | from test_support import verbose, findfile, TestFailed
import linuxaudiodev
import errno
import os
def play_sound_file(path):
fp = open(path, 'r')
data = fp.read()
fp.close()
try:
a = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg[0] in (errno.EACCES, errno.ENODEV):
raise ImportError, msg
raise TestFailed, msg
else:
a.write(data)
a.close()
def test():
play_sound_file(findfile('audiotest.au'))
test()
| from test_support import verbose, findfile, TestFailed, TestSkipped
import linuxaudiodev
import errno
import os
def play_sound_file(path):
fp = open(path, 'r')
data = fp.read()
fp.close()
try:
a = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg[0] in (errno.EACCES, errno.ENODEV):
raise TestSkipped, msg
raise TestFailed, msg
else:
a.write(data)
a.close()
def test():
play_sound_file(findfile('audiotest.au'))
test()
| Raise TestSkipped, not ImportError. Honesty's the best policy. | Raise TestSkipped, not ImportError.
Honesty's the best policy.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -1,4 +1,4 @@
-from test_support import verbose, findfile, TestFailed
+from test_support import verbose, findfile, TestFailed, TestSkipped
import linuxaudiodev
import errno
import os
@@ -11,7 +11,7 @@
a = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg[0] in (errno.EACCES, errno.ENODEV):
- raise ImportError, msg
+ raise TestSkipped, msg
raise TestFailed, msg
else:
a.write(data) |
70db9410173183c83d80ca23e56ceb0d627fcbae | scripts/indices.py | scripts/indices.py | # Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('external_accounts', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
('username', ASCENDING),
])
db['node'].create_index([
('is_deleted', ASCENDING),
('is_collection', ASCENDING),
('is_public', ASCENDING),
('institution_id', ASCENDING),
('is_registration', ASCENDING),
('contributors', ASCENDING),
])
db['node'].create_index([
('tags', ASCENDING),
('is_public', ASCENDING),
('is_deleted', ASCENDING),
('institution_id', ASCENDING),
])
| # Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['storedfilenode'].create_index([
('tags', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('external_accounts', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
('username', ASCENDING),
])
db['node'].create_index([
('is_deleted', ASCENDING),
('is_collection', ASCENDING),
('is_public', ASCENDING),
('institution_id', ASCENDING),
('is_registration', ASCENDING),
('contributors', ASCENDING),
])
db['node'].create_index([
('tags', ASCENDING),
('is_public', ASCENDING),
('is_deleted', ASCENDING),
('institution_id', ASCENDING),
])
| Add index on file tags field | Add index on file tags field
| Python | apache-2.0 | baylee-d/osf.io,abought/osf.io,Johnetordoff/osf.io,felliott/osf.io,alexschiller/osf.io,mluo613/osf.io,brianjgeiger/osf.io,crcresearch/osf.io,aaxelb/osf.io,wearpants/osf.io,hmoco/osf.io,mfraezz/osf.io,caseyrollins/osf.io,leb2dg/osf.io,emetsger/osf.io,caneruguz/osf.io,alexschiller/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,wearpants/osf.io,laurenrevere/osf.io,abought/osf.io,acshi/osf.io,brianjgeiger/osf.io,SSJohns/osf.io,chrisseto/osf.io,DanielSBrown/osf.io,felliott/osf.io,laurenrevere/osf.io,caneruguz/osf.io,mluke93/osf.io,chennan47/osf.io,SSJohns/osf.io,crcresearch/osf.io,SSJohns/osf.io,mluke93/osf.io,hmoco/osf.io,chrisseto/osf.io,kwierman/osf.io,samchrisinger/osf.io,mluo613/osf.io,emetsger/osf.io,jnayak1/osf.io,monikagrabowska/osf.io,alexschiller/osf.io,erinspace/osf.io,wearpants/osf.io,crcresearch/osf.io,chennan47/osf.io,caneruguz/osf.io,caneruguz/osf.io,rdhyee/osf.io,Nesiehr/osf.io,pattisdr/osf.io,cslzchen/osf.io,samchrisinger/osf.io,chennan47/osf.io,samchrisinger/osf.io,cslzchen/osf.io,Nesiehr/osf.io,aaxelb/osf.io,mluke93/osf.io,amyshi188/osf.io,cslzchen/osf.io,icereval/osf.io,cwisecarver/osf.io,mattclark/osf.io,abought/osf.io,HalcyonChimera/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,amyshi188/osf.io,aaxelb/osf.io,alexschiller/osf.io,TomBaxter/osf.io,zamattiac/osf.io,leb2dg/osf.io,monikagrabowska/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,mluo613/osf.io,binoculars/osf.io,emetsger/osf.io,adlius/osf.io,amyshi188/osf.io,DanielSBrown/osf.io,zamattiac/osf.io,pattisdr/osf.io,mfraezz/osf.io,leb2dg/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,sloria/osf.io,saradbowman/osf.io,mattclark/osf.io,mfraezz/osf.io,mluo613/osf.io,chrisseto/osf.io,acshi/osf.io,abought/osf.io,hmoco/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,emetsger/osf.io,SSJohns/osf.io,cwisecarver/osf.io,caseyrollins/osf.io,jnayak1/osf.io,adlius/osf.io,acshi/osf.io,adlius/osf.io,felliott/osf.io,erinspace/osf.io,Johnetordoff/osf.io,mluo613/osf.io,binoculars/osf.io,hmoco/osf.io,caseyrollins/osf.io,mattclark/osf.io,monikagrabowska/osf.io,erinspace/osf.io,mfraezz/osf.io,jnayak1/osf.io,TomBaxter/osf.io,chrisseto/osf.io,Nesiehr/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,amyshi188/osf.io,samchrisinger/osf.io,jnayak1/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,kwierman/osf.io,kwierman/osf.io,Nesiehr/osf.io,mluke93/osf.io,acshi/osf.io,kwierman/osf.io,adlius/osf.io,aaxelb/osf.io,cwisecarver/osf.io,rdhyee/osf.io,baylee-d/osf.io,acshi/osf.io,pattisdr/osf.io,alexschiller/osf.io,zamattiac/osf.io,brianjgeiger/osf.io,DanielSBrown/osf.io,binoculars/osf.io,zamattiac/osf.io,TomBaxter/osf.io,icereval/osf.io,sloria/osf.io,wearpants/osf.io,felliott/osf.io,icereval/osf.io,monikagrabowska/osf.io | ---
+++
@@ -4,6 +4,9 @@
from pymongo import ASCENDING, DESCENDING
+db['storedfilenode'].create_index([
+ ('tags', ASCENDING),
+])
db['user'].create_index([
('emails', ASCENDING), |
ecbabd56f6afc4474402d3293bf11e3b6eb2e8f4 | server/__init__.py | server/__init__.py | import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import(
genRESTEndPointsForSlicerCLIsInSubDirs,
genRESTEndPointsForSlicerCLIsInDocker
)
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsRoot = Webroot(_template)
histomicsRoot.updateHtmlVars(girderRoot.vars)
histomicsRoot.updateHtmlVars({'title': 'HistomicsTK'})
info['serverRoot'].histomicstk = histomicsRoot
info['serverRoot'].girder = girderRoot
# cliRootDir = os.path.dirname(__file__)
# genRESTEndPointsForSlicerCLIsInSubDirs(info, 'HistomicsTK', cliRootDir)
genRESTEndPointsForSlicerCLIsInDocker(info,
'HistomicsTK',
'dsarchive/histomicstk') | import os
from girder.utility.webroot import Webroot
from .rest_slicer_cli import(
genRESTEndPointsForSlicerCLIsInSubDirs,
genRESTEndPointsForSlicerCLIsInDocker
)
_template = os.path.join(
os.path.dirname(__file__),
'webroot.mako'
)
def load(info):
girderRoot = info['serverRoot']
histomicsRoot = Webroot(_template)
histomicsRoot.updateHtmlVars(girderRoot.vars)
histomicsRoot.updateHtmlVars({'title': 'HistomicsTK'})
info['serverRoot'].histomicstk = histomicsRoot
info['serverRoot'].girder = girderRoot
# cliRootDir = os.path.dirname(__file__)
# genRESTEndPointsForSlicerCLIsInSubDirs(info, 'HistomicsTK', cliRootDir)
_ = genRESTEndPointsForSlicerCLIsInDocker(
info, 'HistomicsTK', 'dsarchive/histomicstk'
) | Switch to generating REST end points from docker image | Switch to generating REST end points from docker image
| Python | apache-2.0 | DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK | ---
+++
@@ -25,6 +25,6 @@
# cliRootDir = os.path.dirname(__file__)
# genRESTEndPointsForSlicerCLIsInSubDirs(info, 'HistomicsTK', cliRootDir)
- genRESTEndPointsForSlicerCLIsInDocker(info,
- 'HistomicsTK',
- 'dsarchive/histomicstk')
+ _ = genRESTEndPointsForSlicerCLIsInDocker(
+ info, 'HistomicsTK', 'dsarchive/histomicstk'
+ ) |
56dc9af410907780faba79699d274bef96a18675 | functionaltests/common/base.py | functionaltests/common/base.py | """
Copyright 2015 Rackspace
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 tempest_lib.base
from functionaltests.common.config import read_config
class BaseDesignateTest(tempest_lib.base.BaseTestCase):
def __init__(self, *args, **kwargs):
super(BaseDesignateTest, self).__init__(*args, **kwargs)
@classmethod
def setUpClass(cls):
super(BaseDesignateTest, cls).setUpClass()
read_config()
| """
Copyright 2015 Rackspace
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 tempest_lib.base
from functionaltests.common.config import read_config
class BaseDesignateTest(tempest_lib.base.BaseTestCase):
@classmethod
def setUpClass(cls):
super(BaseDesignateTest, cls).setUpClass()
read_config()
| Remove unnecessary __init__ from functionaltests | Remove unnecessary __init__ from functionaltests
The __init__ just passes the same arguments, so it is not necessary
to implement it. This patch removes it for the cleanup.
Change-Id: Ib465356c47d06bfc66bef69126b089be24d19474
| Python | apache-2.0 | openstack/designate,openstack/designate,openstack/designate | ---
+++
@@ -21,9 +21,6 @@
class BaseDesignateTest(tempest_lib.base.BaseTestCase):
- def __init__(self, *args, **kwargs):
- super(BaseDesignateTest, self).__init__(*args, **kwargs)
-
@classmethod
def setUpClass(cls):
super(BaseDesignateTest, cls).setUpClass() |
40ca8cde872704438fecd22ae98bc7db610de1f9 | services/flickr.py | services/flickr.py | import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/oauth/request_token'
authorize_url = 'http://www.flickr.com/services/oauth/authorize'
access_token_url = 'http://www.flickr.com/services/oauth/access_token'
api_domain = 'api.flickr.com'
available_permissions = [
# (None, 'access only your public photos'),
# ('read', 'access your public and private photos'),
# ('write', 'upload, edit and replace your photos'),
('delete', 'upload, edit, replace and delete your photos'),
]
https = False
def get_authorize_params(self, redirect_uri):
params = super(Flickr, self).get_authorize_params(redirect_uri)
params['perms'] = self.available_permissions[0][0]
return params
def get_user_id(self, key):
url = u'/services/rest/?method=flickr.people.getLimits'
url += u'&format=json&nojsoncallback=1'
r = self.api(key, self.api_domain, url)
return r.json[u'person'][u'nsid']
| import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/oauth/request_token'
authorize_url = 'http://www.flickr.com/services/oauth/authorize'
access_token_url = 'http://www.flickr.com/services/oauth/access_token'
api_domain = 'api.flickr.com'
available_permissions = [
(None, 'access only your public photos'),
('read', 'access your public and private photos'),
('write', 'upload, edit and replace your photos'),
('delete', 'upload, edit, replace and delete your photos'),
]
permissions_widget = 'radio'
https = False
def get_authorize_params(self, redirect_uri, scopes):
params = super(Flickr, self).get_authorize_params(redirect_uri, scopes)
if any(scopes):
params['perms'] = scopes[0]
return params
def get_user_id(self, key):
url = u'/services/rest/?method=flickr.people.getLimits'
url += u'&format=json&nojsoncallback=1'
r = self.api(key, self.api_domain, url)
return r.json[u'person'][u'nsid']
| Rewrite Flickr to use the new scope selection system | Rewrite Flickr to use the new scope selection system
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org | ---
+++
@@ -14,17 +14,21 @@
api_domain = 'api.flickr.com'
available_permissions = [
- # (None, 'access only your public photos'),
- # ('read', 'access your public and private photos'),
- # ('write', 'upload, edit and replace your photos'),
+ (None, 'access only your public photos'),
+ ('read', 'access your public and private photos'),
+ ('write', 'upload, edit and replace your photos'),
('delete', 'upload, edit, replace and delete your photos'),
]
+ permissions_widget = 'radio'
https = False
- def get_authorize_params(self, redirect_uri):
- params = super(Flickr, self).get_authorize_params(redirect_uri)
- params['perms'] = self.available_permissions[0][0]
+ def get_authorize_params(self, redirect_uri, scopes):
+ params = super(Flickr, self).get_authorize_params(redirect_uri, scopes)
+
+ if any(scopes):
+ params['perms'] = scopes[0]
+
return params
def get_user_id(self, key): |
267b0634546c55ebb42d6b1b9c3deca9d7408cc2 | run_tests.py | run_tests.py | #!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation
TEST_PATH Path to package containing test modules"""
def main(sdk_path, test_path):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover(test_path)
unittest2.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) != 2:
print 'Error: Exactly 2 arguments required.'
parser.print_help()
sys.exit(1)
SDK_PATH = args[0]
TEST_PATH = "tests"
main(SDK_PATH, TEST_PATH) | #!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path, test_path):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover(test_path)
unittest2.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) != 1:
print 'Error: Exactly 1 argument required.'
parser.print_help()
sys.exit(1)
SDK_PATH = args[0]
TEST_PATH = "tests"
main(SDK_PATH, TEST_PATH) | Fix test runner to accept 1 arg | Fix test runner to accept 1 arg
| Python | mit | the-blue-alliance/the-blue-alliance,synth3tk/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,bvisness/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,josephbisch/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,synth3tk/the-blue-alliance,phil-lopreiato/the-blue-alliance,1fish2/the-blue-alliance,1fish2/the-blue-alliance,tsteward/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,josephbisch/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,jaredhasenklein/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,verycumbersome/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,tsteward/the-blue-alliance,bvisness/the-blue-alliance,jaredhasenklein/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,1fish2/the-blue-alliance,jaredhasenklein/the-blue-alliance,bvisness/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,1fish2/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,bvisness/the-blue-alliance,fangeugene/the-blue-alliance | ---
+++
@@ -8,8 +8,7 @@
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
-SDK_PATH Path to the SDK installation
-TEST_PATH Path to package containing test modules"""
+SDK_PATH Path to the SDK installation"""
def main(sdk_path, test_path):
@@ -23,8 +22,8 @@
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
- if len(args) != 2:
- print 'Error: Exactly 2 arguments required.'
+ if len(args) != 1:
+ print 'Error: Exactly 1 argument required.'
parser.print_help()
sys.exit(1)
SDK_PATH = args[0] |
def9d7037a3c629f63e1a0d8c1721501abc110cd | linguee_api/downloaders/httpx_downloader.py | linguee_api/downloaders/httpx_downloader.py | import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
| import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
ERROR_503 = (
"The Linguee server returned 503. The API proxy was temporarily blocked by "
"Linguee. For more details, see https://github.com/imankulov/linguee-api#"
"the-api-server-returns-the-linguee-server-returned-503"
)
class HTTPXDownloader(IDownloader):
"""
Real downloader.
Sends request to linguee.com to read the page.
"""
async def download(self, url: str) -> str:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
if response.status_code == 503:
raise DownloaderError(ERROR_503)
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}"
)
return response.text
| Update the 503 error message. | Update the 503 error message.
| Python | mit | imankulov/linguee-api | ---
+++
@@ -1,6 +1,12 @@
import httpx
from linguee_api.downloaders.interfaces import DownloaderError, IDownloader
+
+ERROR_503 = (
+ "The Linguee server returned 503. The API proxy was temporarily blocked by "
+ "Linguee. For more details, see https://github.com/imankulov/linguee-api#"
+ "the-api-server-returns-the-linguee-server-returned-503"
+)
class HTTPXDownloader(IDownloader):
@@ -16,6 +22,10 @@
response = await client.get(url)
except httpx.ConnectError as e:
raise DownloaderError(str(e)) from e
+
+ if response.status_code == 503:
+ raise DownloaderError(ERROR_503)
+
if response.status_code != 200:
raise DownloaderError(
f"The Linguee server returned {response.status_code}" |
ffa00eaea02cda8258bf42d4fa733fb8693e2f0c | chemtrails/apps.py | chemtrails/apps.py | # -*- coding: utf-8 -*-
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
def ready(self):
from .signals.handlers import (
m2m_changed_handler, post_migrate_handler,
post_save_handler, pre_delete_handler
)
m2m_changed.connect(receiver=m2m_changed_handler,
dispatch_uid='chemtrails.signals.handlers.m2m_changed_handler')
post_save.connect(receiver=post_save_handler,
dispatch_uid='chemtrails.signals.handlers.post_save_handler')
pre_delete.connect(receiver=pre_delete_handler,
dispatch_uid='chemtrails.signals.handlers.pre_delete_handler')
post_migrate.connect(receiver=post_migrate_handler,
dispatch_uid='neomodel.core.install_all_labels')
# Neo4j config
config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL)
config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE', False)
| # -*- coding: utf-8 -*-
import os
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
from neomodel import config
config.AUTO_INSTALL_LABELS = False
class ChemTrailsConfig(AppConfig):
name = 'chemtrails'
def ready(self):
from .signals.handlers import (
m2m_changed_handler, post_migrate_handler,
post_save_handler, pre_delete_handler
)
m2m_changed.connect(receiver=m2m_changed_handler,
dispatch_uid='chemtrails.signals.handlers.m2m_changed_handler')
post_save.connect(receiver=post_save_handler,
dispatch_uid='chemtrails.signals.handlers.post_save_handler')
pre_delete.connect(receiver=pre_delete_handler,
dispatch_uid='chemtrails.signals.handlers.pre_delete_handler')
post_migrate.connect(receiver=post_migrate_handler,
dispatch_uid='neomodel.core.install_all_labels')
# Neo4j config
config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL',
os.environ.get('NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL))
config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE',
os.environ.get('NEOMODEL_FORCE_TIMEZONE', False))
| Read Neo4j config from ENV if present | Read Neo4j config from ENV if present
| Python | mit | inonit/django-chemtrails,inonit/django-chemtrails,inonit/django-chemtrails | ---
+++
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+
+import os
from django.apps import AppConfig
from django.conf import settings
@@ -29,5 +31,7 @@
dispatch_uid='neomodel.core.install_all_labels')
# Neo4j config
- config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL)
- config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE', False)
+ config.DATABASE_URL = getattr(settings, 'NEOMODEL_NEO4J_BOLT_URL',
+ os.environ.get('NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL))
+ config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE',
+ os.environ.get('NEOMODEL_FORCE_TIMEZONE', False)) |
7a688f0712ff323668955a21ea335f3308fcc840 | wurstmineberg.45s.py | wurstmineberg.45s.py | #!/usr/local/bin/python3
import requests
people = requests.get('https://api.wurstmineberg.de/v2/people.json').json()
status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json()
print(len(status['list']))
print('---')
print('Version: {}|color=gray'.format(status['version']))
for wmb_id in status['list']:
display_name = people['people'].get(wmb_id, {}).get('name', wmb_id)
print('{}|href=https://wurstmineberg.de/people/{} color=#2889be'.format(display_name, wmb_id))
| #!/usr/local/bin/python3
import requests
people = requests.get('https://api.wurstmineberg.de/v2/people.json').json()
status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json()
print(len(status['list']))
print('---')
print('Version: {}|color=gray'.format(status['version']))
for wmb_id in status['list']:
display_name = people['people'].get(wmb_id, {}).get('name', wmb_id)
print('{}|href=https://wurstmineberg.de/people/{} color=#2889be'.format(display_name, wmb_id))
print('---')
print('Start Minecraft | bash=/usr/bin/open param1=-a param2=Minecraft terminal=false')
| Add “Start Minecraft” menu item | Add “Start Minecraft” menu item
From https://github.com/matryer/bitbar-plugins/blob/master/Games/minecraftplayers.1m.py
| Python | mit | wurstmineberg/bitbar-server-status | ---
+++
@@ -12,3 +12,6 @@
for wmb_id in status['list']:
display_name = people['people'].get(wmb_id, {}).get('name', wmb_id)
print('{}|href=https://wurstmineberg.de/people/{} color=#2889be'.format(display_name, wmb_id))
+
+print('---')
+print('Start Minecraft | bash=/usr/bin/open param1=-a param2=Minecraft terminal=false') |
6cc904a4ee48f8bdbc52cff6cda254e5e69b3c48 | framework/analytics/migrate.py | framework/analytics/migrate.py | from website.app import init_app
from website.models import Node, User
from framework import Q
from framework.analytics import piwik
app = init_app("website.settings", set_backends=True)
# NOTE: This is a naive implementation for migration, requiring a POST request
# for every user and every node. It is possible to bundle these together in a
# single request, but it would require duplication of logic and strict error
# checking of the result. Doing it this way is idempotent, and allows any
# exceptions raised to halt the process with a usable error message.
for user in User.find():
if user.piwik_token:
continue
piwik.create_user(user)
for node in Node.find(Q('is_public', 'eq', True), Q('is_deleted', 'eq', False)):
if node.piwik_site_id:
continue
piwik._provision_node(node) | from website.app import init_app
from website.models import Node, User
from framework import Q
from framework.analytics import piwik
app = init_app("website.settings", set_backends=True)
# NOTE: This is a naive implementation for migration, requiring a POST request
# for every user and every node. It is possible to bundle these together in a
# single request, but it would require duplication of logic and strict error
# checking of the result. Doing it this way is idempotent, and allows any
# exceptions raised to halt the process with a usable error message.
for user in User.find():
if user.piwik_token:
continue
piwik.create_user(user)
for node in Node.find(Q('is_public', 'eq', True) & Q('is_deleted', 'eq', False)):
if node.piwik_site_id:
continue
piwik._provision_node(node) | Update to latest version of ODM: Join queries with `&`, not `,` | Update to latest version of ODM: Join queries with `&`, not `,`
| Python | apache-2.0 | brandonPurvis/osf.io,GaryKriebel/osf.io,brianjgeiger/osf.io,kch8qx/osf.io,leb2dg/osf.io,zachjanicki/osf.io,cosenal/osf.io,jeffreyliu3230/osf.io,kushG/osf.io,mluo613/osf.io,GaryKriebel/osf.io,njantrania/osf.io,jinluyuan/osf.io,erinspace/osf.io,mfraezz/osf.io,barbour-em/osf.io,adlius/osf.io,HarryRybacki/osf.io,hmoco/osf.io,cwisecarver/osf.io,TomHeatwole/osf.io,jnayak1/osf.io,ticklemepierce/osf.io,sbt9uc/osf.io,baylee-d/osf.io,hmoco/osf.io,adlius/osf.io,monikagrabowska/osf.io,binoculars/osf.io,petermalcolm/osf.io,reinaH/osf.io,danielneis/osf.io,leb2dg/osf.io,billyhunt/osf.io,billyhunt/osf.io,brandonPurvis/osf.io,dplorimer/osf,caneruguz/osf.io,caseyrygt/osf.io,revanthkolli/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,acshi/osf.io,revanthkolli/osf.io,cslzchen/osf.io,chrisseto/osf.io,reinaH/osf.io,zamattiac/osf.io,brianjgeiger/osf.io,zkraime/osf.io,TomBaxter/osf.io,brianjgeiger/osf.io,ZobairAlijan/osf.io,kushG/osf.io,cosenal/osf.io,zachjanicki/osf.io,rdhyee/osf.io,cwisecarver/osf.io,kwierman/osf.io,doublebits/osf.io,GageGaskins/osf.io,revanthkolli/osf.io,lyndsysimon/osf.io,cslzchen/osf.io,wearpants/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,arpitar/osf.io,binoculars/osf.io,DanielSBrown/osf.io,doublebits/osf.io,laurenrevere/osf.io,cldershem/osf.io,bdyetton/prettychart,kwierman/osf.io,dplorimer/osf,lamdnhan/osf.io,amyshi188/osf.io,bdyetton/prettychart,HalcyonChimera/osf.io,laurenrevere/osf.io,GageGaskins/osf.io,Nesiehr/osf.io,mluke93/osf.io,acshi/osf.io,caseyrygt/osf.io,zkraime/osf.io,caneruguz/osf.io,erinspace/osf.io,ckc6cz/osf.io,petermalcolm/osf.io,asanfilippo7/osf.io,njantrania/osf.io,emetsger/osf.io,bdyetton/prettychart,wearpants/osf.io,aaxelb/osf.io,caseyrollins/osf.io,ZobairAlijan/osf.io,chennan47/osf.io,arpitar/osf.io,asanfilippo7/osf.io,amyshi188/osf.io,sloria/osf.io,MerlinZhang/osf.io,SSJohns/osf.io,cosenal/osf.io,mluke93/osf.io,mattclark/osf.io,mluo613/osf.io,lamdnhan/osf.io,binoculars/osf.io,amyshi188/osf.io,KAsante95/osf.io,wearpants/osf.io,saradbowman/osf.io,brandonPurvis/osf.io,Nesiehr/osf.io,Ghalko/osf.io,DanielSBrown/osf.io,samanehsan/osf.io,DanielSBrown/osf.io,jmcarp/osf.io,sbt9uc/osf.io,Nesiehr/osf.io,felliott/osf.io,ZobairAlijan/osf.io,jnayak1/osf.io,kushG/osf.io,zamattiac/osf.io,monikagrabowska/osf.io,AndrewSallans/osf.io,sbt9uc/osf.io,aaxelb/osf.io,KAsante95/osf.io,dplorimer/osf,alexschiller/osf.io,cwisecarver/osf.io,Ghalko/osf.io,brandonPurvis/osf.io,Johnetordoff/osf.io,jolene-esposito/osf.io,monikagrabowska/osf.io,cldershem/osf.io,alexschiller/osf.io,jmcarp/osf.io,njantrania/osf.io,zamattiac/osf.io,fabianvf/osf.io,lamdnhan/osf.io,alexschiller/osf.io,jolene-esposito/osf.io,adlius/osf.io,RomanZWang/osf.io,baylee-d/osf.io,fabianvf/osf.io,chrisseto/osf.io,erinspace/osf.io,jeffreyliu3230/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,jinluyuan/osf.io,ticklemepierce/osf.io,fabianvf/osf.io,HalcyonChimera/osf.io,GageGaskins/osf.io,zachjanicki/osf.io,caneruguz/osf.io,jeffreyliu3230/osf.io,adlius/osf.io,kch8qx/osf.io,cwisecarver/osf.io,chrisseto/osf.io,TomHeatwole/osf.io,zamattiac/osf.io,GageGaskins/osf.io,cslzchen/osf.io,TomBaxter/osf.io,felliott/osf.io,monikagrabowska/osf.io,caseyrygt/osf.io,chennan47/osf.io,zkraime/osf.io,ticklemepierce/osf.io,himanshuo/osf.io,leb2dg/osf.io,SSJohns/osf.io,kwierman/osf.io,jolene-esposito/osf.io,crcresearch/osf.io,laurenrevere/osf.io,jeffreyliu3230/osf.io,crcresearch/osf.io,samchrisinger/osf.io,acshi/osf.io,Johnetordoff/osf.io,himanshuo/osf.io,billyhunt/osf.io,samchrisinger/osf.io,AndrewSallans/osf.io,himanshuo/osf.io,sloria/osf.io,asanfilippo7/osf.io,zkraime/osf.io,samanehsan/osf.io,MerlinZhang/osf.io,fabianvf/osf.io,barbour-em/osf.io,samchrisinger/osf.io,aaxelb/osf.io,emetsger/osf.io,samanehsan/osf.io,acshi/osf.io,revanthkolli/osf.io,ZobairAlijan/osf.io,abought/osf.io,cosenal/osf.io,haoyuchen1992/osf.io,cldershem/osf.io,CenterForOpenScience/osf.io,jmcarp/osf.io,haoyuchen1992/osf.io,himanshuo/osf.io,SSJohns/osf.io,lyndsysimon/osf.io,baylee-d/osf.io,bdyetton/prettychart,CenterForOpenScience/osf.io,ckc6cz/osf.io,lyndsysimon/osf.io,pattisdr/osf.io,petermalcolm/osf.io,kch8qx/osf.io,caneruguz/osf.io,jnayak1/osf.io,mattclark/osf.io,mluke93/osf.io,Ghalko/osf.io,danielneis/osf.io,jinluyuan/osf.io,ckc6cz/osf.io,reinaH/osf.io,kushG/osf.io,barbour-em/osf.io,alexschiller/osf.io,hmoco/osf.io,KAsante95/osf.io,samanehsan/osf.io,caseyrygt/osf.io,samchrisinger/osf.io,zachjanicki/osf.io,jinluyuan/osf.io,GaryKriebel/osf.io,billyhunt/osf.io,lamdnhan/osf.io,jolene-esposito/osf.io,jnayak1/osf.io,HarryRybacki/osf.io,SSJohns/osf.io,haoyuchen1992/osf.io,MerlinZhang/osf.io,leb2dg/osf.io,RomanZWang/osf.io,Ghalko/osf.io,KAsante95/osf.io,kch8qx/osf.io,pattisdr/osf.io,mfraezz/osf.io,kch8qx/osf.io,icereval/osf.io,alexschiller/osf.io,caseyrollins/osf.io,lyndsysimon/osf.io,emetsger/osf.io,cslzchen/osf.io,KAsante95/osf.io,doublebits/osf.io,GageGaskins/osf.io,mluo613/osf.io,sloria/osf.io,Nesiehr/osf.io,CenterForOpenScience/osf.io,rdhyee/osf.io,hmoco/osf.io,danielneis/osf.io,Johnetordoff/osf.io,TomHeatwole/osf.io,danielneis/osf.io,saradbowman/osf.io,kwierman/osf.io,crcresearch/osf.io,reinaH/osf.io,DanielSBrown/osf.io,brandonPurvis/osf.io,felliott/osf.io,mattclark/osf.io,GaryKriebel/osf.io,mluo613/osf.io,arpitar/osf.io,pattisdr/osf.io,MerlinZhang/osf.io,mluo613/osf.io,brianjgeiger/osf.io,ticklemepierce/osf.io,barbour-em/osf.io,amyshi188/osf.io,icereval/osf.io,petermalcolm/osf.io,RomanZWang/osf.io,abought/osf.io,acshi/osf.io,icereval/osf.io,billyhunt/osf.io,doublebits/osf.io,mfraezz/osf.io,mluke93/osf.io,chrisseto/osf.io,jmcarp/osf.io,RomanZWang/osf.io,TomBaxter/osf.io,wearpants/osf.io,HarryRybacki/osf.io,felliott/osf.io,njantrania/osf.io,TomHeatwole/osf.io,haoyuchen1992/osf.io,doublebits/osf.io,cldershem/osf.io,chennan47/osf.io,ckc6cz/osf.io,arpitar/osf.io,abought/osf.io,caseyrollins/osf.io,RomanZWang/osf.io,HalcyonChimera/osf.io,abought/osf.io,emetsger/osf.io,monikagrabowska/osf.io,dplorimer/osf,HarryRybacki/osf.io,rdhyee/osf.io,sbt9uc/osf.io,asanfilippo7/osf.io | ---
+++
@@ -17,7 +17,7 @@
piwik.create_user(user)
-for node in Node.find(Q('is_public', 'eq', True), Q('is_deleted', 'eq', False)):
+for node in Node.find(Q('is_public', 'eq', True) & Q('is_deleted', 'eq', False)):
if node.piwik_site_id:
continue
|
75a4097006e6ea5f1693b9d746456b060974d8a0 | mtglib/__init__.py | mtglib/__init__.py | __version__ = '1.5.2'
__author__ = 'Cameron Higby-Naquin'
| __version__ = '1.6.0'
__author__ = 'Cameron Higby-Naquin'
| Increment minor version for new feature release. | Increment minor version for new feature release.
| Python | mit | chigby/mtg,chigby/mtg | ---
+++
@@ -1,2 +1,2 @@
-__version__ = '1.5.2'
+__version__ = '1.6.0'
__author__ = 'Cameron Higby-Naquin' |
d4db750d2ff2e18c9fced49fffe7a3073880078b | InvenTree/common/apps.py | InvenTree/common/apps.py | # -*- coding: utf-8 -*-
from django.apps import AppConfig
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
pass
| # -*- coding: utf-8 -*-
import logging
from django.apps import AppConfig
logger = logging.getLogger('inventree')
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
self.clear_restart_flag()
def clear_restart_flag(self):
"""
Clear the SERVER_RESTART_REQUIRED setting
"""
try:
import common.models
if common.models.InvenTreeSetting.get_setting('SERVER_RESTART_REQUIRED'):
logger.info("Clearing SERVER_RESTART_REQUIRED flag")
common.models.InvenTreeSetting.set_setting('SERVER_RESTART_REQUIRED', False, None)
except:
pass
| Clear the SERVER_RESTART_REQUIRED flag automatically when the server reloads | Clear the SERVER_RESTART_REQUIRED flag automatically when the server reloads
| Python | mit | SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree | ---
+++
@@ -1,10 +1,30 @@
# -*- coding: utf-8 -*-
+import logging
+
from django.apps import AppConfig
+
+
+logger = logging.getLogger('inventree')
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
- pass
+
+ self.clear_restart_flag()
+
+ def clear_restart_flag(self):
+ """
+ Clear the SERVER_RESTART_REQUIRED setting
+ """
+
+ try:
+ import common.models
+
+ if common.models.InvenTreeSetting.get_setting('SERVER_RESTART_REQUIRED'):
+ logger.info("Clearing SERVER_RESTART_REQUIRED flag")
+ common.models.InvenTreeSetting.set_setting('SERVER_RESTART_REQUIRED', False, None)
+ except:
+ pass |
ae918211a85654d7eaa848cbd09f717d0339f844 | database_email_backend/backend.py | database_email_backend/backend.py | #-*- coding: utf-8 -*-
from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
return
for message in email_messages:
email = Email.objects.create(
from_email = message.from_email,
to_emails = ', '.join(message.to),
cc_emails = ', '.join(message.cc),
bcc_emails = ', '.join(message.bcc),
all_recipients = ', '.join(message.recipients()),
subject = message.subject,
body = message.body,
raw = message.message().as_string()
)
for attachment in message.attachments:
if isinstance(attachment, tuple):
filename, content, mimetype = attachment
elif isinstance(attachment, MIMEBase):
filename = attachment.get_filename()
content = attachment.get_payload(decode=True)
mimetype = None
else:
continue
Attachment.objects.create(
email=email,
filename=filename,
content=content,
mimetype=mimetype
)
| #-*- coding: utf-8 -*-
from email.MIMEBase import MIMEBase
from django.core.mail.backends.base import BaseEmailBackend
from database_email_backend.models import Email, Attachment
class DatabaseEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
if not email_messages:
return
for message in email_messages:
email = Email.objects.create(
from_email = u'%s' % message.from_email,
to_emails = u', '.join(message.to),
cc_emails = u', '.join(message.cc),
bcc_emails = u', '.join(message.bcc),
all_recipients = u', '.join(message.recipients()),
subject = u'%s' % message.subject,
body = u'%s' % message.body,
raw = u'%s' % message.message().as_string()
)
for attachment in message.attachments:
if isinstance(attachment, tuple):
filename, content, mimetype = attachment
elif isinstance(attachment, MIMEBase):
filename = attachment.get_filename()
content = attachment.get_payload(decode=True)
mimetype = None
else:
continue
Attachment.objects.create(
email=email,
filename=filename,
content=content,
mimetype=mimetype
)
| Convert everything to unicode strings before inserting to DB | Convert everything to unicode strings before inserting to DB | Python | mit | machtfit/django-database-email-backend,machtfit/django-database-email-backend,jbinary/django-database-email-backend,stefanfoulis/django-database-email-backend,jbinary/django-database-email-backend | ---
+++
@@ -10,14 +10,14 @@
return
for message in email_messages:
email = Email.objects.create(
- from_email = message.from_email,
- to_emails = ', '.join(message.to),
- cc_emails = ', '.join(message.cc),
- bcc_emails = ', '.join(message.bcc),
- all_recipients = ', '.join(message.recipients()),
- subject = message.subject,
- body = message.body,
- raw = message.message().as_string()
+ from_email = u'%s' % message.from_email,
+ to_emails = u', '.join(message.to),
+ cc_emails = u', '.join(message.cc),
+ bcc_emails = u', '.join(message.bcc),
+ all_recipients = u', '.join(message.recipients()),
+ subject = u'%s' % message.subject,
+ body = u'%s' % message.body,
+ raw = u'%s' % message.message().as_string()
)
for attachment in message.attachments:
if isinstance(attachment, tuple): |
b4c97d3b7b914c193c018a1d808f0815778996b4 | keystone/common/sql/data_migration_repo/versions/002_password_created_at_not_nullable.py | keystone/common/sql/data_migration_repo/versions/002_password_created_at_not_nullable.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# A null initial migration to open this repo. Do not re-use replace this with
# a real migration, add additional ones in subsequent version scripts.
def upgrade(migrate_engine):
pass
| # 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.
def upgrade(migrate_engine):
pass
| Remove comment from previous migration | Remove comment from previous migration
The migration was using a comment from the first one.
Change-Id: I25dc9ca79f30f156bfc4296c44e141991119635e
| Python | apache-2.0 | ilay09/keystone,rajalokan/keystone,mahak/keystone,openstack/keystone,ilay09/keystone,openstack/keystone,mahak/keystone,mahak/keystone,openstack/keystone,rajalokan/keystone,rajalokan/keystone,ilay09/keystone | ---
+++
@@ -10,9 +10,6 @@
# License for the specific language governing permissions and limitations
# under the License.
-# A null initial migration to open this repo. Do not re-use replace this with
-# a real migration, add additional ones in subsequent version scripts.
-
def upgrade(migrate_engine):
pass |
cd0b6af73dd49b4da851a75232b5829b91b9030c | genome_designer/conf/demo_settings.py | genome_designer/conf/demo_settings.py | """
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.project_view',
'main.views.tab_root_analyze',
'main.views.reference_genome_list_view',
'main.views.reference_genome_view',
'main.views.sample_list_view',
'main.views.alignment_list_view',
'main.views.alignment_view',
'main.views.sample_alignment_error_view',
'main.views.variant_set_list_view',
'main.views.variant_set_view',
'main.views.single_variant_view',
'main.xhr_handlers.get_variant_list',
'main.xhr_handlers.get_variant_set_list',
'main.xhr_handlers.get_gene_list',
'main.xhr_handlers.get_alignment_groups',
'main.xhr_handlers.is_materialized_view_valid',
'main.xhr_handlers.get_ref_genomes',
'main.xhr_handlers.compile_jbrowse_and_redirect',
'main.template_xhrs.variant_filter_controls',
'main.demo_view_overrides.login_demo_account',
'django.contrib.auth.views.logout'
]
| """
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.project_view',
'main.views.tab_root_analyze',
'main.views.reference_genome_list_view',
'main.views.reference_genome_view',
'main.views.sample_list_view',
'main.views.alignment_list_view',
'main.views.alignment_view',
'main.views.sample_alignment_error_view',
'main.views.variant_set_list_view',
'main.views.variant_set_view',
'main.views.single_variant_view',
'main.xhr_handlers.get_variant_list',
'main.xhr_handlers.get_variant_set_list',
'main.xhr_handlers.get_gene_list',
'main.xhr_handlers.refresh_materialized_variant_table',
'main.xhr_handlers.get_alignment_groups',
'main.xhr_handlers.is_materialized_view_valid',
'main.xhr_handlers.get_ref_genomes',
'main.xhr_handlers.compile_jbrowse_and_redirect',
'main.template_xhrs.variant_filter_controls',
'main.demo_view_overrides.login_demo_account',
'django.contrib.auth.views.logout'
]
| Allow refresh materialized view in DEMO_MODE. | Allow refresh materialized view in DEMO_MODE.
| Python | mit | woodymit/millstone_accidental_source,woodymit/millstone_accidental_source,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source,woodymit/millstone,woodymit/millstone,churchlab/millstone,churchlab/millstone | ---
+++
@@ -22,6 +22,7 @@
'main.xhr_handlers.get_variant_list',
'main.xhr_handlers.get_variant_set_list',
'main.xhr_handlers.get_gene_list',
+ 'main.xhr_handlers.refresh_materialized_variant_table',
'main.xhr_handlers.get_alignment_groups',
'main.xhr_handlers.is_materialized_view_valid',
'main.xhr_handlers.get_ref_genomes', |
e073e020d46953e15f0fb30d2947028c42261fc1 | cropimg/widgets.py | cropimg/widgets.py | from django.forms.widgets import Input, ClearableFileInput
from django.template.loader import render_to_string
class CIImgWidget(ClearableFileInput):
def render(self, name, value, attrs=None):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueError: # attribute has no file associated with it.
attrs["data-value"] = ""
return super(CIImgWidget, self).render(name, value, attrs)
class CIThumbnailWidget(Input):
input_type = "text"
def render(self, name, value, attrs=None, renderer=None):
if attrs:
attrs.update(self.attrs)
attrs["type"] = "hidden"
input_field = super(CIThumbnailWidget, self).render(name, value, attrs)
return render_to_string("cropimg/cropimg_widget.html",
{
"name": name, "value": value, "attrs": attrs,
"input_field": input_field
})
class Media:
js = ("cropimg/js/jquery_init.js", "cropimg/js/cropimg.jquery.js",
"cropimg/js/cropimg_init.js")
css = {"all": ["cropimg/resource/cropimg.css"]}
| from django.forms.widgets import Input, ClearableFileInput
from django.template.loader import render_to_string
class CIImgWidget(ClearableFileInput):
def render(self, name, value, attrs=None, renderer=None, **kwargs):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueError: # attribute has no file associated with it.
attrs["data-value"] = ""
return super(CIImgWidget, self).render(name, value, attrs)
class CIThumbnailWidget(Input):
input_type = "text"
def render(self, name, value, attrs=None, renderer=None, **kwargs):
if attrs:
attrs.update(self.attrs)
attrs["type"] = "hidden"
input_field = super(CIThumbnailWidget, self).render(name, value, attrs)
return render_to_string("cropimg/cropimg_widget.html",
{
"name": name, "value": value, "attrs": attrs,
"input_field": input_field
})
class Media:
js = ("cropimg/js/jquery_init.js", "cropimg/js/cropimg.jquery.js",
"cropimg/js/cropimg_init.js")
css = {"all": ["cropimg/resource/cropimg.css"]}
| Make sure that the admin widget also supports Django 2 | Make sure that the admin widget also supports Django 2
| Python | mit | rewardz/cropimg-django,rewardz/cropimg-django,rewardz/cropimg-django | ---
+++
@@ -4,7 +4,7 @@
class CIImgWidget(ClearableFileInput):
- def render(self, name, value, attrs=None):
+ def render(self, name, value, attrs=None, renderer=None, **kwargs):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueError: # attribute has no file associated with it.
@@ -16,7 +16,7 @@
input_type = "text"
- def render(self, name, value, attrs=None, renderer=None):
+ def render(self, name, value, attrs=None, renderer=None, **kwargs):
if attrs:
attrs.update(self.attrs)
attrs["type"] = "hidden" |
413bebe630c29764dcbf17b114662427edfdac3c | pydot/errors.py | pydot/errors.py | class PardotAPIError(Exception):
"""
Basic exception class for errors encountered in API post and get requests. Takes the json response and parses out
the error code and message.
"""
def __init__(self, json_response):
self.response = json_response
try:
self.err_code = json_response['@attributes']['err_code']
self.message = str(json_response['err'])
except KeyError:
self.err_code = 0
self.message = 'Unknown API error occurred'
def __str__(self):
return 'Pardot API Error {err_code}: {message}'.format(err_code=self.err_code, message=self.message)
| class PardotAPIError(Exception):
"""
Basic exception class for errors encountered in API post and get requests. Takes the json response and parses out
the error code and message.
"""
def __init__(self, json_response):
self.response = json_response
self.err_code = json_response.get('@attributes').get('err_code')
self.message = str(json_response.get('err'))
if self.err_code is None:
self.err_code = 0
self.message = 'Unknown API error occurred'
def __str__(self):
return 'Pardot API Error {err_code}: {message}'.format(err_code=self.err_code, message=self.message)
| Refactor error data extraction from JSON | Refactor error data extraction from JSON
| Python | mit | joshgeller/PyPardot | ---
+++
@@ -6,10 +6,9 @@
def __init__(self, json_response):
self.response = json_response
- try:
- self.err_code = json_response['@attributes']['err_code']
- self.message = str(json_response['err'])
- except KeyError:
+ self.err_code = json_response.get('@attributes').get('err_code')
+ self.message = str(json_response.get('err'))
+ if self.err_code is None:
self.err_code = 0
self.message = 'Unknown API error occurred'
|
13e4a0ef064460ffa90bc150dc04b9a1fff26a1c | blanc_basic_news/news/templatetags/news_tags.py | blanc_basic_news/news/templatetags/news_tags.py | from django import template
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
| from django import template
from django.utils import timezone
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
@register.assignment_tag
def get_latest_news(count):
return Post.objects.select_related().filter(
published=True, date__lte=timezone.now())[:count]
| Add a template tag to get the latest news posts. | Add a template tag to get the latest news posts.
| Python | bsd-3-clause | blancltd/blanc-basic-news | ---
+++
@@ -1,4 +1,5 @@
from django import template
+from django.utils import timezone
from blanc_basic_news.news.models import Category, Post
register = template.Library()
@@ -12,3 +13,9 @@
@register.assignment_tag
def get_news_months():
return Post.objects.dates('date', 'month')
+
+
[email protected]_tag
+def get_latest_news(count):
+ return Post.objects.select_related().filter(
+ published=True, date__lte=timezone.now())[:count] |
649f2aa5a23541a4c57372eeb34a337d84dd0f86 | timed/tests/test_serializers.py | timed/tests/test_serializers.py | from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import DictObjectSerializer
class MyPkDictSerializer(DictObjectSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
pk_key = 'test_nr'
resource_name = 'my-resource'
@pytest.fixture
def data():
return {
'test_nr': 123,
'test_duration': timedelta(hours=1),
'invalid_field': '1234'
}
def test_pk_dict_serializer_single(data):
serializer = MyPkDictSerializer(data)
expected_data = {
'test_duration': '01:00:00',
'test_nr': 123,
}
assert expected_data == serializer.data
def test_pk_dict_serializer_many(data):
list_data = [
data,
data
]
serializer = MyPkDictSerializer(list_data, many=True)
expected_data = [
{
'test_duration': '01:00:00',
'test_nr': 123,
},
{
'test_duration': '01:00:00',
'test_nr': 123,
},
]
assert expected_data == serializer.data
| from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import DictObjectSerializer
class MyPkDictSerializer(DictObjectSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
resource_name = 'my-resource'
@pytest.fixture
def data():
return {
'test_nr': 123,
'test_duration': timedelta(hours=1),
'invalid_field': '1234'
}
def test_pk_dict_serializer_single(data):
serializer = MyPkDictSerializer(data)
expected_data = {
'test_duration': '01:00:00',
'test_nr': 123,
}
assert expected_data == serializer.data
def test_pk_dict_serializer_many(data):
list_data = [
data,
data
]
serializer = MyPkDictSerializer(list_data, many=True)
expected_data = [
{
'test_duration': '01:00:00',
'test_nr': 123,
},
{
'test_duration': '01:00:00',
'test_nr': 123,
},
]
assert expected_data == serializer.data
| Remove obsolete pk_key in test | Remove obsolete pk_key in test
| Python | agpl-3.0 | adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend | ---
+++
@@ -11,7 +11,6 @@
test_nr = IntegerField()
class Meta:
- pk_key = 'test_nr'
resource_name = 'my-resource'
|
2b2401fcbefc5c385f5e84057a76a4fcdbed0030 | serfnode/handler/handler.py | serfnode/handler/handler.py | #!/usr/bin/env python
import os
from serf_master import SerfHandlerProxy
from base_handler import BaseHandler
try:
from my_handler import MyHandler
except ImportError:
print "Could not import user's handler."
print "Defaulting to dummy handler."
MyHandler = BaseHandler
if __name__ == '__main__':
handler = SerfHandlerProxy()
handler.register(os.environ.get('ROLE', 'no_role'), MyHandler())
handler.run() | #!/usr/bin/env python
import os
from serf_master import SerfHandlerProxy
from base_handler import BaseHandler
try:
from my_handler import MyHandler
except ImportError:
print "Could not import user's handler."
print "Defaulting to dummy handler."
MyHandler = BaseHandler
if __name__ == '__main__':
handler = SerfHandlerProxy()
role = os.environ.get('ROLE') or 'no_role'
handler.register(role, MyHandler())
handler.run() | Set 'no_role' if role is not given | Set 'no_role' if role is not given
| Python | mit | waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode | ---
+++
@@ -13,5 +13,6 @@
if __name__ == '__main__':
handler = SerfHandlerProxy()
- handler.register(os.environ.get('ROLE', 'no_role'), MyHandler())
+ role = os.environ.get('ROLE') or 'no_role'
+ handler.register(role, MyHandler())
handler.run() |
62a3ab3409dbc1dd22896fb7c3b5376c1b6432e2 | AcmePlumbingSend.py | AcmePlumbingSend.py | import sublime, sublime_plugin
import os
from .Mouse import MouseCommand
class AcmePlumbingSend(MouseCommand):
""" Sends the current selected text to the plumbing """
def run(self, edit):
file_name = self.view.file_name()
message = {
"data": self.view.substr(self.selection_at_cursor()),
"cwd": os.path.dirname(file_name) if file_name else None,
"src": self.view.id(),
}
self.remove_selection("1") # in case it was expanded
self.view.sel().clear()
self.view.run_command("acme_plumbing", message)
| import sublime, sublime_plugin
import os
from .Mouse import MouseCommand
class AcmePlumbingSend(MouseCommand):
""" Sends the current selected text to the plumbing """
def run(self, edit):
file_name = self.view.file_name()
message = {
"data": self.view.substr(self.selection_at_cursor()),
"cwd": os.path.dirname(file_name) if file_name else None,
"src": self.view.id(),
}
self.view.sel().clear()
self.view.run_command("acme_plumbing", message)
| Remove artefact from earlier left mouse button selection | Remove artefact from earlier left mouse button selection
You used to be able to select with the left mouse button and then right click.
You can't now.
| Python | mit | lionicsheriff/SublimeAcmePlumbing | ---
+++
@@ -11,6 +11,5 @@
"cwd": os.path.dirname(file_name) if file_name else None,
"src": self.view.id(),
}
- self.remove_selection("1") # in case it was expanded
self.view.sel().clear()
self.view.run_command("acme_plumbing", message) |
ed2c56cd044f905c4325f42b4e9cf7a5df913bfd | books/models.py | books/models.py | from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = fields.CharField(max_length=255)
amount = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES)
created = fields.DateTimeField(auto_now=True)
modified = fields.DateTimeField(default=timezone.now)
user = models.ForeignKey(User)
def __str__(self):
return "{}".format(self.title)
| from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = fields.CharField(max_length=255)
amount = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES)
created = fields.DateTimeField(default=timezone.now, editable=False)
modified = fields.DateTimeField(default=timezone.now)
user = models.ForeignKey(User)
def __str__(self):
return "{}".format(self.title)
| Set created time with default callback | Set created time with default callback
auto_now is evil, as any editing and overriding is
almost completely impossible (e.g. unittesting)
| Python | mit | trimailov/finance,trimailov/finance,trimailov/finance | ---
+++
@@ -15,7 +15,7 @@
title = fields.CharField(max_length=255)
amount = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES)
- created = fields.DateTimeField(auto_now=True)
+ created = fields.DateTimeField(default=timezone.now, editable=False)
modified = fields.DateTimeField(default=timezone.now)
user = models.ForeignKey(User)
|
5bc51f525c702cd43d3d7bc3819d179815c41807 | foliant/backends/pre.py | foliant/backends/pre.py | from shutil import copytree, rmtree
from foliant.utils import spinner
from foliant.backends.base import BaseBackend
class Backend(BaseBackend):
'''Backend that just applies its preprocessors and returns a project
that doesn't need any further preprocessing.
'''
targets = 'pre',
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._preprocessed_dir_name = f'{self.get_slug()}.pre'
def make(self, target: str) -> str:
rmtree(self._preprocessed_dir_name, ignore_errors=True)
copytree(self.working_dir, self._preprocessed_dir_name)
return self._preprocessed_dir_name
| from shutil import copytree, rmtree
from foliant.utils import spinner
from foliant.backends.base import BaseBackend
class Backend(BaseBackend):
'''Backend that just applies its preprocessors and returns a project
that doesn't need any further preprocessing.
'''
targets = 'pre',
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._preprocessed_config = self.config.get('backend_config', {}).get('pre', {})
self._preprocessed_dir_name = f'{self._preprocessed_config.get("slug", self.get_slug())}.pre'
def make(self, target: str) -> str:
rmtree(self._preprocessed_dir_name, ignore_errors=True)
copytree(self.working_dir, self._preprocessed_dir_name)
return self._preprocessed_dir_name
| Allow to override the top-level slug. | Allow to override the top-level slug.
| Python | mit | foliant-docs/foliant | ---
+++
@@ -14,7 +14,9 @@
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self._preprocessed_dir_name = f'{self.get_slug()}.pre'
+ self._preprocessed_config = self.config.get('backend_config', {}).get('pre', {})
+
+ self._preprocessed_dir_name = f'{self._preprocessed_config.get("slug", self.get_slug())}.pre'
def make(self, target: str) -> str:
rmtree(self._preprocessed_dir_name, ignore_errors=True) |
4e3e1c3e70f5ba60ae9637febe4d95348561dd47 | db/editjsonfile.py | db/editjsonfile.py | #!/usr/bin/python
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aesjsonfile
def editfile(fn, password):
db = aesjsonfile.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
while True:
subprocess.call([os.getenv("EDITOR") or "editor", f.name])
try:
f.seek(0)
db = json.load(f)
aesjsonfile.dump(fn, db, password)
break
except Exception, e:
print "Error in json"
print e
print "Try again (y/n)? ",
input = sys.stdin.readline()
if not input.lower().startswith("y"):
break
f.seek(0,2)
len = f.tell()
print len
f.seek(0)
f.write(" " * len)
f.flush()
f.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(1)
fn = sys.argv[1]
password = getpass.getpass()
editfile(fn, password)
| #!/usr/bin/python
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aesjsonfile
def editfile(fn, password):
db = aesjsonfile.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
while True:
subprocess.call([os.getenv("EDITOR") or "editor", f.name])
try:
f.seek(0)
db = json.load(f)
aesjsonfile.dump(fn, db, password)
break
except Exception, e:
print "Error in json"
print e
print "Try again (y/n)? ",
input = raw_input()
if not input.lower().startswith("y"):
break
f.seek(0,2)
len = f.tell()
f.seek(0)
f.write(" " * len)
f.flush()
f.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(1)
fn = sys.argv[1]
password = getpass.getpass()
editfile(fn, password)
| Clean up input and output. | Clean up input and output. | Python | agpl-3.0 | vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash | ---
+++
@@ -23,12 +23,11 @@
print "Error in json"
print e
print "Try again (y/n)? ",
- input = sys.stdin.readline()
+ input = raw_input()
if not input.lower().startswith("y"):
break
f.seek(0,2)
len = f.tell()
- print len
f.seek(0)
f.write(" " * len)
f.flush() |
c37e3fe832ef3f584a60783a474b31f9f91e3735 | github_webhook/test_webhook.py | github_webhook/test_webhook.py | """Tests for github_webhook.webhook"""
from __future__ import print_function
import unittest
from mock import Mock
from github_webhook.webhook import Webhook
class TestWebhook(unittest.TestCase):
def test_constructor(self):
# GIVEN
app = Mock()
# WHEN
webhook = Webhook(app)
# THEN
app.add_url_rule.assert_called_once_with(
'/postreceive', view_func=webhook._postreceive, methods=['POST'])
# -----------------------------------------------------------------------------
# Copyright 2015 Bloomberg Finance L.P.
#
# 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.
# ----------------------------- END-OF-FILE -----------------------------------
| """Tests for github_webhook.webhook"""
from __future__ import print_function
import unittest
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
from github_webhook.webhook import Webhook
class TestWebhook(unittest.TestCase):
def test_constructor(self):
# GIVEN
app = Mock()
# WHEN
webhook = Webhook(app)
# THEN
app.add_url_rule.assert_called_once_with(
'/postreceive', view_func=webhook._postreceive, methods=['POST'])
# -----------------------------------------------------------------------------
# Copyright 2015 Bloomberg Finance L.P.
#
# 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.
# ----------------------------- END-OF-FILE -----------------------------------
| Fix mock import for Python 3 | Fix mock import for Python 3
| Python | apache-2.0 | fophillips/python-github-webhook | ---
+++
@@ -3,7 +3,10 @@
from __future__ import print_function
import unittest
-from mock import Mock
+try:
+ from unittest.mock import Mock
+except ImportError:
+ from mock import Mock
from github_webhook.webhook import Webhook
|
8adbb5c9cc089663bcdc62496415d666c9f818a3 | service/inchi.py | service/inchi.py | import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi))
if request.status_code == 200:
cjson = request.json();
else:
return None
print cjson
# Call convertion routine
p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(json.dumps(cjson['results'][0]))
fd, path = tempfile.mkstemp(suffix='.cml')
with open(path, 'w') as fp:
fp.write(str(stdout))
os.close(fd)
return path
| import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
import sys
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi))
if request.status_code == 200:
cjson = request.json();
else:
print >> sys.stderr, "Unable to access REST API: %s" % request.status_code
return None
# Call convertion routine
p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(json.dumps(cjson['results'][0]))
fd, path = tempfile.mkstemp(suffix='.cml')
with open(path, 'w') as fp:
fp.write(str(stdout))
os.close(fd)
return path
| Add log statement if REST API can't be accessed | Add log statement if REST API can't be accessed
| Python | bsd-3-clause | OpenChemistry/mongochemweb,OpenChemistry/mongochemweb | ---
+++
@@ -3,6 +3,7 @@
from subprocess import Popen, PIPE
import tempfile
import os
+import sys
config = {}
with open ('../config/conversion.json') as fp:
@@ -15,9 +16,8 @@
if request.status_code == 200:
cjson = request.json();
else:
+ print >> sys.stderr, "Unable to access REST API: %s" % request.status_code
return None
-
- print cjson
# Call convertion routine
p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE) |
94bcaa24f0dc1c0750023770574e26bb41183c6a | hangupsbot/plugins/namelock.py | hangupsbot/plugins/namelock.py | """Allows the user to configure the bot to watch for hangout renames
and change the name back to a default name accordingly"""
def setchatname(bot, event, *args):
"""Set a chat name. If no parameters given, remove chat name"""
truncatelength = 32 # What should the maximum length of the chatroom be?
chatname = ' '.join(args).strip()
chatname = chatname[0:truncatelength]
bot.initialise_memory(event.conv_id, "conv_data")
bot.memory.set_by_path(["conv_data", event.conv_id, "chatname"], chatname)
bot.memory.save()
if(chatname == ''):
bot.send_message_parsed(event.conv, "Removing chatname")
else:
bot.send_message_parsed(
event.conv,
"Setting chatname to '{}'".format(chatname))
| """Allows the user to configure the bot to watch for hangout renames
and change the name back to a default name accordingly"""
def setchatname(bot, event, *args):
"""Set a chat name. If no parameters given, remove chat name"""
truncatelength = 32 # What should the maximum length of the chatroom be?
chatname = ' '.join(args).strip()
chatname = chatname[0:truncatelength]
bot.initialise_memory(event.conv_id, "conv_data")
bot.memory.set_by_path(["conv_data", event.conv_id, "chatname"], chatname)
bot.memory.save()
if(chatname == ''):
bot.send_message_parsed(event.conv, "Removing chatname")
else:
bot.send_message_parsed(
event.conv,
"Setting chatname to '{}'".format(chatname))
"""Rename Hangout"""
yield from bot._client.setchatname(event.conv_id, ' '.join(args))
| Make hangout rename itself after setchatname is called | Make hangout rename itself after setchatname is called
| Python | agpl-3.0 | makiftasova/hangoutsbot,cd334/hangoutsbot,jhonnyam123/hangoutsbot | ---
+++
@@ -20,3 +20,6 @@
bot.send_message_parsed(
event.conv,
"Setting chatname to '{}'".format(chatname))
+
+ """Rename Hangout"""
+ yield from bot._client.setchatname(event.conv_id, ' '.join(args)) |
89b7b7f7fe1ec50f1d0bdfba7581f76326efe717 | dacapo_analyzer.py | dacapo_analyzer.py | import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'((?P<succed>FAILED|PASSED) in (?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
| import re
BENCHMARKS = set(( 'avrora'
, 'batik'
, 'eclipse'
, 'fop'
, 'h2'
, 'jython'
, 'luindex'
, 'lusearch'
, 'pmd'
, 'sunflow'
, 'tomcat'
, 'tradebeans'
, 'tradesoap'
, 'xalan'))
WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)')
def dacapo_wallclock(output):
"""
:param output: benchmark output
:returns: list of relevant parts for wallclock time
:rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec)
"""
return WALLCLOCK_RE.findall(output)
| Use only msecs of dacapo output. | [client] Use only msecs of dacapo output.
Signed-off-by: Michael Markert <[email protected]>
| Python | mit | fhirschmann/penchy,fhirschmann/penchy | ---
+++
@@ -15,7 +15,7 @@
, 'tradesoap'
, 'xalan'))
-WALLCLOCK_RE = re.compile(r'((?P<succed>FAILED|PASSED) in (?P<time>\d+) msec)')
+WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)')
def dacapo_wallclock(output):
""" |
f5cc0d9327f35d818b10e200404c849a5527aa50 | indra/databases/hgnc_client.py | indra/databases/hgnc_client.py | import urllib2
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None:
return None
hgnc_name_tag =\
xml_tree.find("result/doc/str[@name='symbol']")
if hgnc_name_tag is None:
return None
return hgnc_name_tag.text.strip()
def get_hgnc_entry(hgnc_id):
url = hgnc_url + 'hgnc_id/%s' % hgnc_id
headers = {'Accept': '*/*'}
req = urllib2.Request(url, headers=headers)
try:
res = urllib2.urlopen(req)
except urllib2.HTTPError:
return None
xml_tree = et.parse(res)
return xml_tree
| import urllib2
from functools32 import lru_cache
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
@lru_cache(maxsize=1000)
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None:
return None
hgnc_name_tag =\
xml_tree.find("result/doc/str[@name='symbol']")
if hgnc_name_tag is None:
return None
return hgnc_name_tag.text.strip()
def get_hgnc_entry(hgnc_id):
url = hgnc_url + 'hgnc_id/%s' % hgnc_id
headers = {'Accept': '*/*'}
req = urllib2.Request(url, headers=headers)
try:
res = urllib2.urlopen(req)
except urllib2.HTTPError:
return None
xml_tree = et.parse(res)
return xml_tree
| Add caching to HGNC client | Add caching to HGNC client
| Python | bsd-2-clause | johnbachman/belpy,sorgerlab/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,bgyori/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,jmuhlich/indra,jmuhlich/indra,sorgerlab/belpy,jmuhlich/indra | ---
+++
@@ -1,8 +1,10 @@
import urllib2
+from functools32 import lru_cache
import xml.etree.ElementTree as et
hgnc_url = 'http://rest.genenames.org/fetch/'
+@lru_cache(maxsize=1000)
def get_hgnc_name(hgnc_id):
xml_tree = get_hgnc_entry(hgnc_id)
if xml_tree is None: |
3b3da9ffc5f8247020d2c6c58f83d95e8dbf8dd6 | serrano/cors.py | serrano/cors.py | from warnings import warn
from django.conf import settings
def patch_response(request, response, methods):
if getattr(settings, 'SERRANO_CORS_ENABLED', False):
if hasattr(settings, 'SERRANO_CORS_ORIGIN'):
warn('SERRANO_CORS_ORIGIN has been deprecated in favor '
'of SERRANO_CORS_ORIGINS', DeprecationWarning)
allowed_origins = [s.strip() for s in
settings.SERRANO_CORS_ORIGIN.split(',')]
else:
allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ())
origin = request.META.get('HTTP_ORIGIN')
if not allowed_origins or origin in allowed_origins:
# The origin must be explicitly listed when used with the
# Access-Control-Allow-Credentials header
# See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa
response['Access-Control-Allow-Origin'] = origin
if request.method == 'OPTIONS':
response['Access-Control-Allow-Credentials'] = 'true'
response['Access-Control-Allow-Methods'] = ', '.join(methods)
headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa
if headers:
response['Access-Control-Allow-Headers'] = headers
return response
| from warnings import warn
from django.conf import settings
def patch_response(request, response, methods):
if getattr(settings, 'SERRANO_CORS_ENABLED', False):
if hasattr(settings, 'SERRANO_CORS_ORIGIN'):
warn('SERRANO_CORS_ORIGIN has been deprecated in favor '
'of SERRANO_CORS_ORIGINS', DeprecationWarning)
allowed_origins = [s.strip() for s in
settings.SERRANO_CORS_ORIGIN.split(',')]
else:
allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ())
origin = request.META.get('HTTP_ORIGIN')
if not allowed_origins or origin in allowed_origins:
# The origin must be explicitly listed when used with the
# Access-Control-Allow-Credentials header
# See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa
response['Access-Control-Allow-Origin'] = origin
response['Access-Control-Allow-Credentials'] = 'true'
if request.method == 'OPTIONS':
response['Access-Control-Allow-Methods'] = ', '.join(methods)
headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa
if headers:
response['Access-Control-Allow-Headers'] = headers
return response
| Set Access-Control-Allow-Credentials for all responses | Set Access-Control-Allow-Credentials for all responses
In order to inform the browser to set the Cookie header on requests, this
header must be set otherwise the session is reset on every request.
| Python | bsd-2-clause | chop-dbhi/serrano,chop-dbhi/serrano,rv816/serrano_night,rv816/serrano_night | ---
+++
@@ -19,8 +19,8 @@
# Access-Control-Allow-Credentials header
# See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa
response['Access-Control-Allow-Origin'] = origin
+ response['Access-Control-Allow-Credentials'] = 'true'
if request.method == 'OPTIONS':
- response['Access-Control-Allow-Credentials'] = 'true'
response['Access-Control-Allow-Methods'] = ', '.join(methods)
headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa
if headers: |
73219ea03b46599b4e2c84a301599c7f1f331751 | sal/urls.py | sal/urls.py | import django.contrib.auth.views as auth_views
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
admin.autodiscover()
urlpatterns = [
url(r'^login/*$', auth_views.LoginView, name='login'),
url(r'^logout/$', auth_views.logout_then_login, name='logout_then_login'),
url(r'^changepassword/$', auth_views.PasswordChangeView, name='password_change'),
url(r'^changepassword/done/$', auth_views.PasswordChangeDoneView, name='password_change_done'),
url(r'^', include('server.urls')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.v1.urls')),
url(r'^api/v1/', include('api.v1.urls')),
url(r'^api/v2/', include('api.v2.urls')),
url(r'^inventory/', include('inventory.urls')),
url(r'^search/', include('search.urls')),
url(r'^licenses/', include('licenses.urls')),
url(r'^catalog/', include('catalog.urls')),
url(r'^profiles/', include('profiles.urls')),
]
if settings.DEBUG:
urlpatterns += [url(r'^static/(?P<path>.*)$', views.serve),]
| import django.contrib.auth.views as auth_views
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
admin.autodiscover()
urlpatterns = [
url(r'^login/*$', auth_views.LoginView, name='login'),
url(r'^logout/$', auth_views.logout_then_login, name='logout_then_login'),
url(r'^changepassword/$', auth_views.PasswordChangeView, name='password_change'),
url(r'^changepassword/done/$', auth_views.PasswordChangeDoneView, name='password_change_done'),
url(r'^', include('server.urls')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.v1.urls')),
url(r'^api/v1/', include('api.v1.urls')),
url(r'^api/v2/', include('api.v2.urls')),
url(r'^inventory/', include('inventory.urls')),
url(r'^search/', include('search.urls')),
url(r'^licenses/', include('licenses.urls')),
url(r'^catalog/', include('catalog.urls')),
url(r'^profiles/', include('profiles.urls')),
]
if settings.DEBUG:
urlpatterns.append(url(r'^static/(?P<path>.*)$', views.serve))
| Fix linter complaint and append rather than cat lists. | Fix linter complaint and append rather than cat lists.
| Python | apache-2.0 | sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,salopensource/sal,salopensource/sal | ---
+++
@@ -26,4 +26,4 @@
]
if settings.DEBUG:
- urlpatterns += [url(r'^static/(?P<path>.*)$', views.serve),]
+ urlpatterns.append(url(r'^static/(?P<path>.*)$', views.serve)) |
77a965f27f75a8a5268ad95538d6625cecb44bfa | south/models.py | south/models.py | from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
class Meta:
unique_together = (('app_name', 'migration'),)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app_name=migration.app_label(),
migration=migration.name())
except cls.DoesNotExist:
return cls(app_name=migration.app_label(),
migration=migration.name())
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
| from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app_name=migration.app_label(),
migration=migration.name())
except cls.DoesNotExist:
return cls(app_name=migration.app_label(),
migration=migration.name())
def get_migrations(self):
from south.migration.base import Migrations
return Migrations(self.app_name)
def get_migration(self):
return self.get_migrations().migration(self.migration)
| Remove unique_together on the model; the key length was too long on wide-character MySQL installs. | Remove unique_together on the model; the key length was too long on wide-character MySQL installs.
| Python | apache-2.0 | matthiask/south,matthiask/south | ---
+++
@@ -4,9 +4,6 @@
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
-
- class Meta:
- unique_together = (('app_name', 'migration'),)
@classmethod
def for_migration(cls, migration): |
3ff91625fc99e279078547220fb4358d647c828a | deflect/widgets.py | deflect/widgets.py | from __future__ import unicode_literals
from itertools import chain
from django import forms
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class DataListInput(forms.TextInput):
"""
A form widget that displays a standard ``TextInput`` field, as well
as an HTML5 datalist element. This provides a set of options that
the user can select from, along with the ability to enter a custom
value. Suggested options are matched as the user begins typing.
"""
def __init__(self, attrs=None, choices=()):
super(DataListInput, self).__init__(attrs)
self.choices = list(chain.from_iterable(choices))
def render(self, name, value, attrs={}, choices=()):
attrs['list'] = 'id_%s_list' % name
output = [super(DataListInput, self).render(name, value, attrs)]
options = self.render_options(name, choices)
if options:
output.append(options)
return mark_safe('\n'.join(output))
def render_options(self, name, choices):
output = []
output.append('<datalist id="id_%s_list">' % name)
output.append('<select style="display:none">')
for option in chain(self.choices, choices):
output.append(format_html('<option value="{0}" />', force_text(option)))
output.append('</select>')
output.append('</datalist>')
return '\n'.join(output)
| from __future__ import unicode_literals
from itertools import chain
from django.contrib.admin.widgets import AdminTextInputWidget
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class DataListInput(AdminTextInputWidget):
"""
A form widget that displays a standard ``TextInput`` field, as well
as an HTML5 datalist element. This provides a set of options that
the user can select from, along with the ability to enter a custom
value. Suggested options are matched as the user begins typing.
"""
def __init__(self, attrs=None, choices=()):
super(DataListInput, self).__init__(attrs)
self.choices = list(chain.from_iterable(choices))
def render(self, name, value, attrs={}, choices=()):
attrs['list'] = 'id_%s_list' % name
output = [super(DataListInput, self).render(name, value, attrs)]
options = self.render_options(name, choices)
if options:
output.append(options)
return mark_safe('\n'.join(output))
def render_options(self, name, choices):
output = []
output.append('<datalist id="id_%s_list">' % name)
output.append('<select style="display:none">')
for option in chain(self.choices, choices):
output.append(format_html('<option value="{0}" />', force_text(option)))
output.append('</select>')
output.append('</datalist>')
return '\n'.join(output)
| Change the superclass for admin DataList widget | Change the superclass for admin DataList widget
This adds an additional class so it displays the same as other
text fields in the admin interface.
| Python | bsd-3-clause | jbittel/django-deflect | ---
+++
@@ -2,13 +2,13 @@
from itertools import chain
-from django import forms
+from django.contrib.admin.widgets import AdminTextInputWidget
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
-class DataListInput(forms.TextInput):
+class DataListInput(AdminTextInputWidget):
"""
A form widget that displays a standard ``TextInput`` field, as well
as an HTML5 datalist element. This provides a set of options that |
87929f67c0036bf9a0a2ad237c1a03b675484a74 | mcgill_app/main.py | mcgill_app/main.py | import graphs
import star
def main():
"""
Plots graph of black body emission wavelengths against amplitudes, then UBVR magnitudes of a star.
"""
graph = graphs.FunctionsGraph(x_label="wavelength / m", y_label="amplitude")
# Temperatures of black bodies (K) mapped to style of lines on graph.
temps_to_styles_map = {3000.0: "g-",
4000.0: "b-",
5000.0: "r-"}
for temp, style in temps_to_styles_map.items():
planck_function = graphs.PlottedPlanckFunction(temp)
graph.add_plotted_function(planck_function,
style=style,
label=str(int(temp)) + "K")
graph.plot(x_range=(0.1e-6, 6e-6), point_spacing=0.02e-6)
# TODO: input required parameters
st = star.Star(1, 10, 4000)
print st.get_ubvr_magnitudes()
if __name__ == "__main__":
main()
| import graphs
import star
def main():
"""
Plots graph of black body emission wavelengths against amplitudes, then UBVR magnitudes of a star.
"""
graph = graphs.FunctionsGraph(x_label="wavelength / m", y_label="amplitude / W * sr^-1 * m^-3")
# Temperatures of black bodies (K) mapped to style of lines on graph.
temps_to_styles_map = {3000.0: "g-",
4000.0: "b-",
5000.0: "r-"}
for temp, style in temps_to_styles_map.items():
planck_function = graphs.PlottedPlanckFunction(temp)
graph.add_plotted_function(planck_function,
style=style,
label=str(int(temp)) + "K")
graph.plot(x_range=(0.1e-6, 6e-6), point_spacing=0.02e-6)
# TODO: input required parameters
st = star.Star(1, 10, 4000)
print st.get_ubvr_magnitudes()
if __name__ == "__main__":
main()
| Change units on graph y-axis | Change units on graph y-axis
| Python | mit | jackromo/GSOCMcgillApplication | ---
+++
@@ -6,7 +6,7 @@
"""
Plots graph of black body emission wavelengths against amplitudes, then UBVR magnitudes of a star.
"""
- graph = graphs.FunctionsGraph(x_label="wavelength / m", y_label="amplitude")
+ graph = graphs.FunctionsGraph(x_label="wavelength / m", y_label="amplitude / W * sr^-1 * m^-3")
# Temperatures of black bodies (K) mapped to style of lines on graph.
temps_to_styles_map = {3000.0: "g-",
4000.0: "b-", |
87cfac55b14083fdb8e346b9db1a95bb0f63881a | connect/config/factories.py | connect/config/factories.py | import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
email = factory.Sequence(lambda n: "site.email%[email protected]" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png')
| import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
logo = factory.django.ImageField(filename='my_log.png', format='PNG')
email = factory.Sequence(lambda n: "site.email%[email protected]" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
| Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency | Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency
| Python | bsd-3-clause | nlhkabu/connect,f3r3nc/connect,f3r3nc/connect,f3r3nc/connect,nlhkabu/connect,f3r3nc/connect,nlhkabu/connect,nlhkabu/connect | ---
+++
@@ -18,6 +18,7 @@
model = SiteConfig
site = factory.SubFactory(Site)
+ logo = factory.django.ImageField(filename='my_log.png', format='PNG')
email = factory.Sequence(lambda n: "site.email%[email protected]" % n)
tagline = 'A tagline'
- email_header = factory.django.ImageField(filename='my_image.png')
+ email_header = factory.django.ImageField(filename='my_image.png', format='PNG') |
78ba73998168d8e723d1c62942b19dabfd9ab229 | src/constants.py | src/constants.py | #!/usr/bin/env python
SIMULATION_TIME_IN_SECONDS = 40
DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)
K_V = 0.90
K_W = 0.90
TRAJECTORY_TYPE = 'linear'
| #!/usr/bin/env python
TRAJECTORY_TYPE = 'circular'
if TRAJECTORY_TYPE == 'linear':
SIMULATION_TIME_IN_SECONDS = 40
elif TRAJECTORY_TYPE == 'circular':
SIMULATION_TIME_IN_SECONDS = 120
DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)
K_V = 0.90
K_W = 0.90
| Define simulation time for linear and circular trajectories | Define simulation time for linear and circular trajectories
| Python | mit | bit0001/trajectory_tracking,bit0001/trajectory_tracking | ---
+++
@@ -1,7 +1,12 @@
#!/usr/bin/env python
-SIMULATION_TIME_IN_SECONDS = 40
+TRAJECTORY_TYPE = 'circular'
+
+if TRAJECTORY_TYPE == 'linear':
+ SIMULATION_TIME_IN_SECONDS = 40
+elif TRAJECTORY_TYPE == 'circular':
+ SIMULATION_TIME_IN_SECONDS = 120
+
DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)
K_V = 0.90
K_W = 0.90
-TRAJECTORY_TYPE = 'linear' |
9150618ca2a1c4b8917596547f73d9c1cc207fda | monkeys/release.py | monkeys/release.py | from invoke import task, run
@task
def makerelease(version, local_only=False):
if not version:
raise Exception("You must specify a version!")
# FoodTruck assets.
print("Update node modules")
run("npm install")
print("Generating Wikked assets")
run("grunt")
if not local_only:
# Tag in Mercurial, which will then be used for PyPi version.
run("hg tag %s" % version)
# PyPi upload.
run("python setup.py sdist upload")
else:
print("Would tag repo with %s..." % version)
print("Would upload to PyPi...")
| from invoke import task, run
@task
def makerelease(ctx, version, local_only=False):
if not version:
raise Exception("You must specify a version!")
# FoodTruck assets.
print("Update node modules")
run("npm install")
print("Generating Wikked assets")
run("grunt")
if not local_only:
# Tag in Mercurial, which will then be used for PyPi version.
run("hg tag %s" % version)
# PyPi upload.
run("python setup.py sdist upload")
else:
print("Would tag repo with %s..." % version)
print("Would upload to PyPi...")
| Make invoke tasks work with the new version of invoke. | cm: Make invoke tasks work with the new version of invoke.
| Python | apache-2.0 | ludovicchabant/Wikked,ludovicchabant/Wikked,ludovicchabant/Wikked | ---
+++
@@ -2,7 +2,7 @@
@task
-def makerelease(version, local_only=False):
+def makerelease(ctx, version, local_only=False):
if not version:
raise Exception("You must specify a version!")
|
b3413818bf651c13cef047132813fb26a185cd33 | indra/tests/test_reading_files.py | indra/tests/test_reading_files.py | from os import path
from indra.tools.reading.read_files import read_files, get_readers
from nose.plugins.attrib import attr
@attr('slow', 'nonpublic')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
readers = get_readers()
outputs = read_files(example_files, readers)
N_out = len(outputs)
N_exp = 2*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
| from os import path
from indra.tools.reading.read_files import read_files, get_reader_classes
from nose.plugins.attrib import attr
from indra.tools.reading.readers import EmptyReader
@attr('slow', 'nonpublic', 'notravis')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
reader_classes = get_reader_classes()
readers = []
for rc in reader_classes:
readers.append(rc())
outputs = read_files(example_files, readers)
N_out = len(outputs)
proper_readers = [r for r in readers if not isinstance(r, EmptyReader)]
N_exp = len(proper_readers)*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
| Fix the reading files test. | Fix the reading files test.
| Python | bsd-2-clause | johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy | ---
+++
@@ -1,10 +1,12 @@
from os import path
-from indra.tools.reading.read_files import read_files, get_readers
+from indra.tools.reading.read_files import read_files, get_reader_classes
from nose.plugins.attrib import attr
+from indra.tools.reading.readers import EmptyReader
-@attr('slow', 'nonpublic')
+
+@attr('slow', 'nonpublic', 'notravis')
def test_read_files():
"Test that the system can read files."
# Create the test files.
@@ -26,8 +28,12 @@
assert len(example_files), "No content available to test."
# Now read them.
- readers = get_readers()
+ reader_classes = get_reader_classes()
+ readers = []
+ for rc in reader_classes:
+ readers.append(rc())
outputs = read_files(example_files, readers)
N_out = len(outputs)
- N_exp = 2*len(example_files)
+ proper_readers = [r for r in readers if not isinstance(r, EmptyReader)]
+ N_exp = len(proper_readers)*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out) |
fd951edbef26dcab2a4b89036811520b22e77fcf | marry-fuck-kill/main.py | marry-fuck-kill/main.py | #!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import html_handlers
import models
def main():
# TODO(mjkelly): Clean up these handlers.
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler),
("/make", html_handlers.MakeHandler),
("/make.do", html_handlers.MakeSubmitHandler),
("/mymfks", html_handlers.MyMfksHandler),
("/vote/(.*)", html_handlers.VoteHandler),
("/vote.do", html_handlers.VoteSubmitHandler),
("/i/(.*)", html_handlers.EntityImageHandler),
("/.*", html_handlers.CatchAllHandler),
])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import html_handlers
import models
def main():
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler),
("/make", html_handlers.MakeHandler),
("/make.do", html_handlers.MakeSubmitHandler),
("/mymfks", html_handlers.MyMfksHandler),
("/vote/(.*)", html_handlers.VoteHandler),
("/vote.do", html_handlers.VoteSubmitHandler),
("/i/(.*)", html_handlers.EntityImageHandler),
("/.*", html_handlers.CatchAllHandler),
])
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| Remove TODO -- handlers have been cleaned up. | Remove TODO -- handlers have been cleaned up.
| Python | apache-2.0 | hjfreyer/marry-fuck-kill,hjfreyer/marry-fuck-kill | ---
+++
@@ -21,7 +21,6 @@
import models
def main():
- # TODO(mjkelly): Clean up these handlers.
application = webapp.WSGIApplication([
("/", html_handlers.MainPageHandler),
("/about", html_handlers.AboutHandler), |
366937921cfb13fd83fb5964d0373be48e3c8564 | cmsplugin_plain_text/models.py | cmsplugin_plain_text/models.py | # -*- coding: utf-8 -*-
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
| # -*- coding: utf-8 -*-
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Plaintext(CMSPlugin):
body = models.TextField(_('Plaintext'))
def __unicode__(self):
return self.body
def __str__(self):
return self.body
| Add `__str__` method to support Python 3 | Add `__str__` method to support Python 3
| Python | bsd-3-clause | chschuermann/cmsplugin-plain-text,chschuermann/cmsplugin-plain-text | ---
+++
@@ -9,3 +9,6 @@
def __unicode__(self):
return self.body
+
+ def __str__(self):
+ return self.body |
d15bfddd59f0009852ff5f69a665c8858a5cdd40 | __init__.py | __init__.py | r"""
============================================
msm - Markov state models (:mod:`pyemma.msm`)
============================================
.. currentmodule:: pyemma.msm
User-API
--------
.. autosummary::
:toctree: generated/
"""
from . import analysis
from . import estimation
from . import generation
from . import io
from . import flux
from .api import *
| r"""
=============================================
msm - Markov state models (:mod:`pyemma.msm`)
=============================================
.. currentmodule:: pyemma.msm
User-API
--------
.. autosummary::
:toctree: generated/
its
msm
tpt
cktest
hmsm
"""
from . import analysis
from . import estimation
from . import generation
from . import io
from . import flux
from .api import *
| Add autodoc for msm user-API | [doc] Add autodoc for msm user-API
| Python | bsd-3-clause | clonker/ci-tests | ---
+++
@@ -1,8 +1,8 @@
r"""
-============================================
+=============================================
msm - Markov state models (:mod:`pyemma.msm`)
-============================================
+=============================================
.. currentmodule:: pyemma.msm
@@ -11,6 +11,12 @@
.. autosummary::
:toctree: generated/
+
+ its
+ msm
+ tpt
+ cktest
+ hmsm
"""
|
08c2f9fe24b6ce7697bf725e70855e8d6861c370 | pandas/__init__.py | pandas/__init__.py | """This package contains interface adapters for pandas.
On import, this package detects if pandas is installed. If it is installed,
then the contained modules are imported to register the pandas classes with
Gaia. If pandas is not found, this package will contain no modules.
"""
try:
import pandas
except ImportError:
pandas = None
__all__ = ()
if pandas is not None:
from pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
try:
import geopandas
except ImportError:
geopandas = None
if geopandas is not None:
from geopandas_data import GeopandasDataFrame
from geopandas_reader import GeopandasReader
from geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
'GeopandasReader',
'GeopandasPlot'
)
try:
import xray
except ImportError:
xray = None
if xray is not None:
from xray_data import XrayDataset
__all__ += ('XrayDataset',)
| """This package contains interface adapters for pandas.
On import, this package detects if pandas is installed. If it is installed,
then the contained modules are imported to register the pandas classes with
Gaia. If pandas is not found, this package will contain no modules.
"""
try:
import pandas
except ImportError:
pandas = None
__all__ = ()
if pandas is not None:
from gaia.pandas.pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
try:
import geopandas
except ImportError:
geopandas = None
if geopandas is not None:
from gaia.pandas.geopandas_data import GeopandasDataFrame
from gaia.pandas.geopandas_reader import GeopandasReader
from gaia.pandas.geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
'GeopandasReader',
'GeopandasPlot'
)
try:
import xray
except ImportError:
xray = None
if xray is not None:
from gaia.pandas.xray_data import XrayDataset
__all__ += ('XrayDataset',)
| Use only absolute imports for python 3 | Use only absolute imports for python 3
| Python | apache-2.0 | Kitware/romanesco,Kitware/romanesco,girder/girder_worker,girder/girder_worker,girder/girder_worker,Kitware/romanesco,Kitware/romanesco | ---
+++
@@ -14,7 +14,7 @@
__all__ = ()
if pandas is not None:
- from pandas_data import PandasDataFrame
+ from gaia.pandas.pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
@@ -24,9 +24,9 @@
geopandas = None
if geopandas is not None:
- from geopandas_data import GeopandasDataFrame
- from geopandas_reader import GeopandasReader
- from geopandas_plot import GeopandasPlot
+ from gaia.pandas.geopandas_data import GeopandasDataFrame
+ from gaia.pandas.geopandas_reader import GeopandasReader
+ from gaia.pandas.geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
@@ -40,6 +40,6 @@
xray = None
if xray is not None:
- from xray_data import XrayDataset
+ from gaia.pandas.xray_data import XrayDataset
__all__ += ('XrayDataset',) |
8e900343312fa644a21e5b209b83431ced3c3020 | inet/constants.py | inet/constants.py | import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
OPS_KEY = os.environ.get("OPS_KEY")
OPS_SECRET = os.environ.get("OPS_SECRET")
TWITTER_CONSUMER_ACCESS = os.environ['TWITTER_CONSUMER_ACCESS']
TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS = os.environ['TWITTER_ACCESS']
TWITTER_SECRET = os.environ['TWITTER_SECRET']
| import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
OPS_KEY = os.environ["OPS_KEY"]
OPS_SECRET = os.environ["OPS_SECRET"]
TWITTER_CONSUMER_ACCESS = os.environ['TWITTER_CONSUMER_ACCESS']
TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS = os.environ['TWITTER_ACCESS']
TWITTER_SECRET = os.environ['TWITTER_SECRET']
| Access envvars using standard dictionary access isntead of get method to ensure missing vars cause an exception to be raised | Access envvars using standard dictionary access isntead of get method to ensure missing vars cause an exception to be raised
| Python | mit | nestauk/inet | ---
+++
@@ -4,8 +4,8 @@
load_dotenv(find_dotenv())
-OPS_KEY = os.environ.get("OPS_KEY")
-OPS_SECRET = os.environ.get("OPS_SECRET")
+OPS_KEY = os.environ["OPS_KEY"]
+OPS_SECRET = os.environ["OPS_SECRET"]
TWITTER_CONSUMER_ACCESS = os.environ['TWITTER_CONSUMER_ACCESS']
TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS = os.environ['TWITTER_ACCESS'] |
08247c2d4cb3cf1879b568697d7888728ebb1c3b | parse_rest/role.py | parse_rest/role.py | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from parse_rest.connection import API_ROOT
from parse_rest.datatypes import ParseResource
from parse_rest.query import QueryManager
class Role(ParseResource):
'''
A Role is like a regular Parse object (can be modified and saved) but
it requires additional methods and functionality
'''
ENDPOINT_ROOT = '/'.join([API_ROOT, 'roles'])
@property
def className(self):
return '_Role'
def __repr__(self):
return '<Role:%s (Id %s)>' % (getattr(self, 'name', None), self.objectId)
Role.Query = QueryManager(Role)
| # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from parse_rest.connection import API_ROOT
from parse_rest.datatypes import ParseResource
from parse_rest.query import QueryManager
class Role(ParseResource):
'''
A Role is like a regular Parse object (can be modified and saved) but
it requires additional methods and functionality
'''
ENDPOINT_ROOT = '/'.join([API_ROOT, 'roles'])
@property
def className(self):
return '_Role'
def __repr__(self):
return '<Role:%s (Id %s)>' % (getattr(self, 'name', None), self.objectId)
def removeRelation(self, key, className, objectsId):
self.manageRelation('RemoveRelation', key, className, objectsId)
def addRelation(self, key, className, objectsId):
self.manageRelation('AddRelation', key, className, objectsId)
def manageRelation(self, action, key, className, objectsId):
objects = [{
"__type": "Pointer",
"className": className,
"objectId": objectId
} for objectId in objectsId]
payload = {
key: {
"__op": action,
"objects": objects
}
}
self.__class__.PUT(self._absolute_url, **payload)
self.__dict__[key] = ''
Role.Query = QueryManager(Role)
| Handle adding and removing relations from Roles. | Handle adding and removing relations from Roles.
This adds addRelation and removeRelation capabilities to Role, making it possible to add users to the users column and roles to the roles column in a Role object, for example. This prevents the error of Role not having the attribute addRelation or removeRelation when trying to add users or roles to a Role, which is critical for Role functionality. | Python | mit | alacroix/ParsePy,milesrichardson/ParsePy,milesrichardson/ParsePy,alacroix/ParsePy | ---
+++
@@ -30,6 +30,28 @@
def __repr__(self):
return '<Role:%s (Id %s)>' % (getattr(self, 'name', None), self.objectId)
+
+ def removeRelation(self, key, className, objectsId):
+ self.manageRelation('RemoveRelation', key, className, objectsId)
+
+ def addRelation(self, key, className, objectsId):
+ self.manageRelation('AddRelation', key, className, objectsId)
+
+ def manageRelation(self, action, key, className, objectsId):
+ objects = [{
+ "__type": "Pointer",
+ "className": className,
+ "objectId": objectId
+ } for objectId in objectsId]
+
+ payload = {
+ key: {
+ "__op": action,
+ "objects": objects
+ }
+ }
+ self.__class__.PUT(self._absolute_url, **payload)
+ self.__dict__[key] = ''
Role.Query = QueryManager(Role) |
d0f4209f373d91a82339ddfc15445e84f4cf0ac8 | oscar_sagepay/config.py | oscar_sagepay/config.py | from django.conf import settings
VPS_PROTOCOL = getattr(settings, 'OSCAR_SAGEPAY_VPS_PROTOCOL', '3.0')
VENDOR = settings.OSCAR_SAGEPAY_VENDOR
TEST_MODE = getattr(settings, 'OSCAR_SAGEPAY_TEST_MODE', True)
if TEST_MODE:
VPS_REGISTER_URL = 'https://test.sagepay.com/Simulator/VSPDirectGateway.asp'
VPS_AUTHORISE_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorAuthoriseTx'
VPS_REFUND_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorRefundTx'
VPS_VOID_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorVoidTx'
else:
VPS_REGISTER_URL = 'https://live.sagepay.com/gateway/service/vspdirect-register.vsp'
VPS_AUTHORISE_URL = VPS_REFUND_URL = VPS_REGISTER_URL = VPS_VOID_URL
VENDOR_TX_CODE_PREFIX = getattr(settings, "OSCAR_SAGEOAY_TX_CODE_PREFIX",
"oscar")
| from django.conf import settings
VPS_PROTOCOL = getattr(settings, 'OSCAR_SAGEPAY_VPS_PROTOCOL', '3.0')
VENDOR = settings.OSCAR_SAGEPAY_VENDOR
TEST_MODE = getattr(settings, 'OSCAR_SAGEPAY_TEST_MODE', True)
if TEST_MODE:
VPS_REGISTER_URL = 'https://test.sagepay.com/Simulator/VSPDirectGateway.asp'
VPS_AUTHORISE_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorAuthoriseTx'
VPS_REFUND_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorRefundTx'
VPS_VOID_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorVoidTx'
else:
VPS_REGISTER_URL = 'https://live.sagepay.com/gateway/service/vspdirect-register.vsp'
VPS_AUTHORISE_URL = VPS_REFUND_URL = VPS_REGISTER_URL = VPS_VOID_URL
VENDOR_TX_CODE_PREFIX = getattr(settings, "OSCAR_SAGEPAY_TX_CODE_PREFIX",
"oscar")
| Fix typo retrieving vendor prefix | Fix typo retrieving vendor prefix
Properly get the OSCAR_SAGEPAY_TX_CODE_PREFIX from the project settings
| Python | bsd-3-clause | django-oscar/django-oscar-sagepay-direct | ---
+++
@@ -14,5 +14,5 @@
VPS_REGISTER_URL = 'https://live.sagepay.com/gateway/service/vspdirect-register.vsp'
VPS_AUTHORISE_URL = VPS_REFUND_URL = VPS_REGISTER_URL = VPS_VOID_URL
-VENDOR_TX_CODE_PREFIX = getattr(settings, "OSCAR_SAGEOAY_TX_CODE_PREFIX",
+VENDOR_TX_CODE_PREFIX = getattr(settings, "OSCAR_SAGEPAY_TX_CODE_PREFIX",
"oscar") |
fe34b3be69c119729febefd23f80a24203383f8a | pidman/__init__.py | pidman/__init__.py | # Project Version and Author Information
__author__ = "EUL Systems"
__copyright__ = "Copyright 2010, Emory University General Library"
__credits__ = ["Rebecca Koeser", "Ben Ranker", "Alex Thomas", "Scott Turnbull"]
__email__ = "[email protected]"
# Version Info, parsed below for actual version number.
__version_info__ = (0, 9, 0)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([ str(i) for i in __version_info__[:-1] ])
if __version_info__[-1] is not None: # Adds dash
__version__ += ('-%s' % (__version_info__[-1],))
| Update project version and other metadata from previous | Update project version and other metadata from previous
| Python | apache-2.0 | emory-libraries/pidman,emory-libraries/pidman | ---
+++
@@ -0,0 +1,13 @@
+# Project Version and Author Information
+__author__ = "EUL Systems"
+__copyright__ = "Copyright 2010, Emory University General Library"
+__credits__ = ["Rebecca Koeser", "Ben Ranker", "Alex Thomas", "Scott Turnbull"]
+__email__ = "[email protected]"
+
+# Version Info, parsed below for actual version number.
+__version_info__ = (0, 9, 0)
+
+# Dot-connect all but the last. Last is dash-connected if not None.
+__version__ = '.'.join([ str(i) for i in __version_info__[:-1] ])
+if __version_info__[-1] is not None: # Adds dash
+ __version__ += ('-%s' % (__version_info__[-1],)) |
|
02d67008d0f0bdc205ca9168384c4a951c106a28 | nintendo/common/transport.py | nintendo/common/transport.py |
import socket
class Socket:
TCP = 0
UDP = 1
def __init__(self, type):
if type == self.TCP:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.s.setblocking(False)
def connect(self, host, port): self.s.connect((host, port))
def close(self): self.s.close()
def send(self, data): self.s.sendall(data)
def recv(self, num):
try:
return self.s.recv(num)
except BlockingIOError:
pass
def get_address(self): return self.s.getsockname()[0]
def get_port(self): return self.s.getsockname()[1]
|
import socket
class Socket:
TCP = 0
UDP = 1
def __init__(self, type):
if type == self.TCP:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.s.setblocking(False)
def connect(self, host, port): self.s.connect((host, port))
def close(self): self.s.close()
def send(self, data): self.s.sendall(data)
def recv(self, num):
try:
return self.s.recv(num)
except BlockingIOError:
pass
def bind(self, addr=("", 0)): self.s.bind(addr)
def sendto(self, data, addr): self.s.sendto(data, addr)
def recvfrom(self, num):
try:
return self.s.recvfrom(num)
except BlockingIOError:
return None, None
def get_address(self): return self.s.getsockname()[0]
def get_port(self): return self.s.getsockname()[1]
| Add a few functions to Socket class | Add a few functions to Socket class
| Python | mit | Kinnay/NintendoClients | ---
+++
@@ -23,5 +23,13 @@
except BlockingIOError:
pass
+ def bind(self, addr=("", 0)): self.s.bind(addr)
+ def sendto(self, data, addr): self.s.sendto(data, addr)
+ def recvfrom(self, num):
+ try:
+ return self.s.recvfrom(num)
+ except BlockingIOError:
+ return None, None
+
def get_address(self): return self.s.getsockname()[0]
def get_port(self): return self.s.getsockname()[1] |
60d8b38eac3c36bd754f5ed01aae6d3af1918adc | notifications/match_score.py | notifications/match_score.py | from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self._event_feed = match.event.id
# TODO Add notion of District to Match model?
@property
def _type(self):
return NotificationType.MATCH_SCORE
def _build_dict(self):
data = {}
data['message_type'] = NotificationType.type_names[self._type]
data['message_data'] = {}
data['message_data']['event_name'] = self.match.event.get().name
data['message_data']['match'] = ModelToDict.matchConverter(self.match)
return data
| from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self.event = match.event.get()
self._event_feed = self.event.key_name
self._district_feed = self.event.event_district_enum
@property
def _type(self):
return NotificationType.MATCH_SCORE
def _build_dict(self):
data = {}
data['message_type'] = NotificationType.type_names[self._type]
data['message_data'] = {}
data['message_data']['event_name'] = self.event.name
data['message_data']['match'] = ModelToDict.matchConverter(self.match)
return data
| Add district feed to match score notification | Add district feed to match score notification
| Python | mit | phil-lopreiato/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,bdaroz/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,verycumbersome/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,phil-lopreiato/the-blue-alliance | ---
+++
@@ -7,8 +7,9 @@
def __init__(self, match):
self.match = match
- self._event_feed = match.event.id
- # TODO Add notion of District to Match model?
+ self.event = match.event.get()
+ self._event_feed = self.event.key_name
+ self._district_feed = self.event.event_district_enum
@property
def _type(self):
@@ -18,6 +19,6 @@
data = {}
data['message_type'] = NotificationType.type_names[self._type]
data['message_data'] = {}
- data['message_data']['event_name'] = self.match.event.get().name
+ data['message_data']['event_name'] = self.event.name
data['message_data']['match'] = ModelToDict.matchConverter(self.match)
return data |
79c12316cf132acdb5e375ea30f1cc67d7fd11ed | thehonestgenepipeline/celeryconfig.py | thehonestgenepipeline/celeryconfig.py | from kombu import Exchange, Queue
import os
BROKER_URL = os.environ['CELERY_BROKER']
CELERY_RESULT_BACKEND='rpc://'
CELERY_RESULT_PERSISTENT = True
CELERY_DISABLE_RATE_LIMITS = True
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
imputation_exchange = Exchange('imputation', type='direct')
ancestry_exchange = Exchange('ancestry',type='direct')
riskprediction_exchange = Exchange('riskprediction',type='direct')
CELERY_QUEUES = (
Queue('imputation', imputation_exchange, routing_key='imputation'),
Queue('ancestry', ancestry_exchange, routing_key='ancestry'),
Queue('riskprediction',riskprediction_exchange,routing_key='riskprediction')
)
CELERY_ROUTES = {
'thehonestgenepipeline.imputation.test':{'queue':'imputation'},
'thehonestgenepipeline.imputation.imputation':{'queue':'imputation'},
'thehonestgenepipeline.imputation.convert':{'queue':'imputation'},
'thehonestgenepipeline.imputation.impute':{'queue':'imputation'},
'thehonestgenepipeline.ancestry.analysis':{'queue':'ancestry'},
'thehonestgenepipeline.riskprediction.run':{'queue':'riskprediction'}
}
| from kombu import Exchange, Queue
import os
BROKER_URL = os.environ['CELERY_BROKER']
CELERY_RESULT_BACKEND='amqp://'
CELERY_RESULT_PERSISTENT = True
CELERY_DISABLE_RATE_LIMITS = True
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
imputation_exchange = Exchange('imputation', type='direct')
ancestry_exchange = Exchange('ancestry',type='direct')
riskprediction_exchange = Exchange('riskprediction',type='direct')
CELERY_QUEUES = (
Queue('imputation', imputation_exchange, routing_key='imputation'),
Queue('ancestry', ancestry_exchange, routing_key='ancestry'),
Queue('riskprediction',riskprediction_exchange,routing_key='riskprediction')
)
CELERY_ROUTES = {
'thehonestgenepipeline.imputation.test':{'queue':'imputation'},
'thehonestgenepipeline.imputation.imputation':{'queue':'imputation'},
'thehonestgenepipeline.imputation.convert':{'queue':'imputation'},
'thehonestgenepipeline.imputation.impute':{'queue':'imputation'},
'thehonestgenepipeline.ancestry.analysis':{'queue':'ancestry'},
'thehonestgenepipeline.riskprediction.run':{'queue':'riskprediction'}
}
| Change from rpc to amqp backend | Change from rpc to amqp backend
Otherwise retrieving result are problematic
| Python | mit | TheHonestGene/thehonestgene-pipeline | ---
+++
@@ -1,7 +1,7 @@
from kombu import Exchange, Queue
import os
BROKER_URL = os.environ['CELERY_BROKER']
-CELERY_RESULT_BACKEND='rpc://'
+CELERY_RESULT_BACKEND='amqp://'
CELERY_RESULT_PERSISTENT = True
CELERY_DISABLE_RATE_LIMITS = True
CELERY_TASK_SERIALIZER = 'json' |
f4c56937caacb4709847d67752f4ff3cba4568f6 | tests/test_it.py | tests/test_it.py | import os
import shutil
import deck2pdf
from pytest import raises
from . import (
current_dir,
test_dir,
skip_in_ci,
)
class TestForMain(object):
def setUp(self):
shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True)
def test_help(self):
raises(SystemExit, deck2pdf.main, [])
raises(SystemExit, deck2pdf.main, ['-h'])
@skip_in_ci
def test_files(self):
test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html')
deck2pdf.main([test_slide_path, ])
assert os.path.exists(os.path.join(current_dir, '.deck2pdf'))
| import os
import shutil
import deck2pdf
from pytest import raises
from . import (
current_dir,
test_dir,
)
class TestForMain(object):
def setUp(self):
shutil.rmtree(os.path.join(current_dir, '.deck2pdf'), ignore_errors=True)
def test_help(self):
raises(SystemExit, deck2pdf.main, [])
raises(SystemExit, deck2pdf.main, ['-h'])
def test_files(self):
test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html')
deck2pdf.main([test_slide_path, '-c', 'stub'])
assert os.path.exists(os.path.join(current_dir, '.deck2pdf'))
| Remove decorator 'skip_in_ci' from test_files | Remove decorator 'skip_in_ci' from test_files
Because implement stub of capture engine, 'Output slides pdf' test can run in CircleCI
| Python | mit | attakei/deck2pdf-python,attakei/deck2pdf-python,attakei/slide2pdf,attakei/deck2pdf,attakei/slide2pdf,attakei/deck2pdf | ---
+++
@@ -5,7 +5,6 @@
from . import (
current_dir,
test_dir,
- skip_in_ci,
)
@@ -17,8 +16,7 @@
raises(SystemExit, deck2pdf.main, [])
raises(SystemExit, deck2pdf.main, ['-h'])
- @skip_in_ci
def test_files(self):
test_slide_path = os.path.join(test_dir, 'testslide/_build/slides/index.html')
- deck2pdf.main([test_slide_path, ])
+ deck2pdf.main([test_slide_path, '-c', 'stub'])
assert os.path.exists(os.path.join(current_dir, '.deck2pdf')) |
cabf0004d6e7e3687cdd2ebe9aebeede01877e69 | tests/run_tests.py | tests/run_tests.py | """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = 'bsd'
DIRECTORIES = ['functional'] # Unit tests to be added here
def platform_test(filename):
for key in PLATFORMS:
if filename.find(key) > -1:
return True
return False
def this_platform(filename):
if filename.find(platform) > -1:
return True
return False
def run_test(file):
print "Running test: %s" % file
print
proc = subprocess.Popen("python %s" % file,
shell=True,
stdout=subprocess.PIPE)
output = proc.communicate()[0]
print output
# We don't do anything with this yet but I'll probably try and group all
# these calls up and keep track of the data at the top level
if output.find('OK'):
return True
return False
for directory in DIRECTORIES:
files = os.listdir(directory)
for file in files:
file_path = os.path.join(directory, file)
if os.path.isfile('%s' % file_path) and file[-3:] == '.py':
if platform_test(file):
if this_platform(file):
run_test(file_path)
else:
run_test(file_path)
| """
Simple test runner to separate out the functional tests and the unit tests.
"""
import os
import subprocess
PLATFORMS = ['bsd', 'linux', 'nt']
# Detect what platform we are on
try:
platform = os.uname()[0].lower()
except AttributeError:
platform = os.name.lower()
if platform == 'darwin':
platform = 'bsd'
DIRECTORIES = ['functional', 'unit'] # Unit tests to be added here
def platform_test(filename):
for key in PLATFORMS:
if filename.find(key) > -1:
return True
return False
def this_platform(filename):
if filename.find(platform) > -1:
return True
return False
def run_test(file):
print "Running test: %s" % file
print
proc = subprocess.Popen("python %s" % file,
shell=True,
stdout=subprocess.PIPE)
output = proc.communicate()[0]
print output
# We don't do anything with this yet but I'll probably try and group all
# these calls up and keep track of the data at the top level
if output.find('OK'):
return True
return False
for directory in DIRECTORIES:
files = os.listdir(directory)
for file in files:
file_path = os.path.join(directory, file)
if os.path.isfile('%s' % file_path) and file[-3:] == '.py':
if platform_test(file):
if this_platform(file):
run_test(file_path)
else:
run_test(file_path)
| Add unit to the test directories | Add unit to the test directories
| Python | bsd-3-clause | jstnlef/pika,reddec/pika,pika/pika,Tarsbot/pika,Zephor5/pika,knowsis/pika,shinji-s/pika,fkarb/pika-python3,vitaly-krugl/pika,vrtsystems/pika,benjamin9999/pika,skftn/pika,renshawbay/pika-python3,hugoxia/pika,zixiliuyue/pika | ---
+++
@@ -15,7 +15,7 @@
if platform == 'darwin':
platform = 'bsd'
-DIRECTORIES = ['functional'] # Unit tests to be added here
+DIRECTORIES = ['functional', 'unit'] # Unit tests to be added here
def platform_test(filename):
for key in PLATFORMS: |
d5b231fbc5dd32ded78e4499a49872487533cda4 | tests/test_main.py | tests/test_main.py | from cookiecutter.main import is_repo_url
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('[email protected]:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
assert is_repo_url('gh:audreyr/cookiecutter-pypackage') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
assert is_repo_url('/home/audreyr/cookiecutter') is False
appveyor_temp_dir = (
'c:\\users\\appveyor\\appdata\\local\\temp\\1\\pytest-0\\'
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
| from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('[email protected]:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
assert is_repo_url('/home/audreyr/cookiecutter') is False
appveyor_temp_dir = (
'c:\\users\\appveyor\\appdata\\local\\temp\\1\\pytest-0\\'
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
def test_expand_abbreviations():
template = 'gh:audreyr/cookiecutter-pypackage'
# This is not a valid repo url just yet!
# First `main.expand_abbreviations` needs to translate it
assert is_repo_url(template) is False
expanded_template = expand_abbreviations(template, {})
assert is_repo_url(expanded_template) is True
| Implement a test specifically for abbreviations | Implement a test specifically for abbreviations
| Python | bsd-3-clause | willingc/cookiecutter,michaeljoseph/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,pjbull/cookiecutter,ramiroluz/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,michaeljoseph/cookiecutter,pjbull/cookiecutter,cguardia/cookiecutter,terryjbates/cookiecutter,Springerle/cookiecutter,hackebrot/cookiecutter,dajose/cookiecutter,Springerle/cookiecutter,terryjbates/cookiecutter,cguardia/cookiecutter,willingc/cookiecutter,ramiroluz/cookiecutter,audreyr/cookiecutter,audreyr/cookiecutter,hackebrot/cookiecutter,dajose/cookiecutter | ---
+++
@@ -1,4 +1,4 @@
-from cookiecutter.main import is_repo_url
+from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
@@ -6,7 +6,6 @@
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('[email protected]:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
- assert is_repo_url('gh:audreyr/cookiecutter-pypackage') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
@@ -17,3 +16,14 @@
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
+
+
+def test_expand_abbreviations():
+ template = 'gh:audreyr/cookiecutter-pypackage'
+
+ # This is not a valid repo url just yet!
+ # First `main.expand_abbreviations` needs to translate it
+ assert is_repo_url(template) is False
+
+ expanded_template = expand_abbreviations(template, {})
+ assert is_repo_url(expanded_template) is True |
1028afcdc1e8e1027b10fe5254f5fe5b9499eddd | tests/test_void.py | tests/test_void.py | """test_void.py
Test the parsing of VoID dump files.
"""
import RDF
from glharvest import util
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
model = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': {
'dataDump': 'http://lod.dataone.org/test.ttl',
'features': [
'http://lod.dataone.org/fulldump'
]
}
}
| """test_void.py
Test the parsing of VoID dump files.
"""
import RDF
from glharvest import util, void
def test_returns_none_if_the_registry_file_is_not_found():
m = util.load_file_into_model("nonexistantvoidfile.ttl")
assert m is None
def test_can_load_a_simple_void_file():
m = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': {
'dataDump': 'http://lod.dataone.org/test.ttl',
'features': [
'http://lod.dataone.org/fulldump'
]
}
}
| Fix imports for void tests | Fix imports for void tests
| Python | apache-2.0 | ec-geolink/glharvest,ec-geolink/glharvest,ec-geolink/glharvest | ---
+++
@@ -6,7 +6,7 @@
import RDF
-from glharvest import util
+from glharvest import util, void
def test_returns_none_if_the_registry_file_is_not_found():
@@ -16,7 +16,7 @@
def test_can_load_a_simple_void_file():
- model = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
+ m = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle')
p = void.parse_void_model(m)
assert p == { 'http://lod.dataone.org/test': { |
43fd422599972f9385c9f3f9bc5a9a2e5947e0ea | web/webhooks.py | web/webhooks.py | from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
def handle_ping(request, repo):
return HttpResponse()
def handle_issues(request, repo):
return HttpResponse()
def handle_issue_comment(request, repo):
return HttpResponse()
def dispatch(request, repo, hook):
github_event = request.META.get('HTTP_X_GITHUB_EVENT')
if not github_event:
return HttpResponseNotFound('No X-GitHub-Event!')
if github_event == 'ping':
return handle_ping(request, repo)
elif github_event == 'issue_comment':
return handle_issue_comment(request, repo)
elif github_event == 'issues':
return handle_issues(request, repo)
else:
return HttpResponseNotFound('Unknown event!')
@csrf_exempt
def all_issues(request, full_repo_name):
return dispatch(request, repo=full_repo_name, hook='all_issues')
| import hashlib
import hmac
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
from web import jucybot
def handle_ping(request, repo):
return HttpResponse()
def handle_issues(request, repo):
return HttpResponse()
def handle_issue_comment(request, repo):
return HttpResponse()
def verify_signature(request, repo):
signature = request.META.get('HTTP_X_HUB_SIGNATURE')
if not signature:
return False
repo_secret = jucybot.getSecretForRepo(repo)
h = hmac.new(repo_secret, request.body, digestmod=hashlib.sha1)
reference = 'sha1=%s' % h.hexdigest()
return reference == signature
def dispatch(request, repo, hook):
github_event = request.META.get('HTTP_X_GITHUB_EVENT')
if not github_event:
return HttpResponseNotFound('No X-GitHub-Event!')
if not verify_signature(request, repo):
return HttpResponseNotFound('X-Hub-Signature did not verify')
if github_event == 'ping':
return handle_ping(request, repo)
elif github_event == 'issue_comment':
return handle_issue_comment(request, repo)
elif github_event == 'issues':
return handle_issues(request, repo)
else:
return HttpResponseNotFound('Unknown event!')
@csrf_exempt
def all_issues(request, full_repo_name):
return dispatch(request, repo=full_repo_name, hook='all_issues')
| Check HMAC digests in webhook notifications before handling them. | Check HMAC digests in webhook notifications before handling them.
Bump #1
| Python | apache-2.0 | Jucyio/Jucy,Jucyio/Jucy,Jucyio/Jucy | ---
+++
@@ -1,6 +1,8 @@
+import hashlib
+import hmac
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound
-
+from web import jucybot
def handle_ping(request, repo):
return HttpResponse()
@@ -14,10 +16,21 @@
return HttpResponse()
+def verify_signature(request, repo):
+ signature = request.META.get('HTTP_X_HUB_SIGNATURE')
+ if not signature:
+ return False
+ repo_secret = jucybot.getSecretForRepo(repo)
+ h = hmac.new(repo_secret, request.body, digestmod=hashlib.sha1)
+ reference = 'sha1=%s' % h.hexdigest()
+ return reference == signature
+
def dispatch(request, repo, hook):
github_event = request.META.get('HTTP_X_GITHUB_EVENT')
if not github_event:
return HttpResponseNotFound('No X-GitHub-Event!')
+ if not verify_signature(request, repo):
+ return HttpResponseNotFound('X-Hub-Signature did not verify')
if github_event == 'ping':
return handle_ping(request, repo)
elif github_event == 'issue_comment': |
f9884fc274d2068051edb41f9ad13ad25a7f1c72 | isogram/isogram.py | isogram/isogram.py | from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
| from string import ascii_lowercase
LOWERCASE = set(ascii_lowercase)
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
# You could also achieve this using "c.isalpha()" instead of LOWERCASE
# You would then not need to import from `string`, but it's marginally slower
| Add note about str.isalpha() method as an alternative | Add note about str.isalpha() method as an alternative
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -7,3 +7,7 @@
def is_isogram(s):
chars = [c for c in s.lower() if c in LOWERCASE]
return len(chars) == len(set(chars))
+
+
+# You could also achieve this using "c.isalpha()" instead of LOWERCASE
+# You would then not need to import from `string`, but it's marginally slower |
16630b23238ee66c8e4ca6017db934befc6ab71e | py/garage/garage/sql/sqlite.py | py/garage/garage/sql/sqlite.py | __all__ = [
'create_engine',
]
import sqlalchemy
def create_engine(
db_uri, *,
check_same_thread=False,
echo=False,
pragmas=()):
engine = sqlalchemy.create_engine(
db_uri,
echo=echo,
connect_args={
'check_same_thread': check_same_thread,
},
)
@sqlalchemy.event.listens_for(engine, 'connect')
def do_connect(dbapi_connection, _):
# Stop pysqlite issue commit automatically.
dbapi_connection.isolation_level = None
# Enable foreign key.
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys = ON")
for name, value in pragmas:
cursor.execute("PRAGMA %s = %s" % (name, value))
cursor.close()
@sqlalchemy.event.listens_for(engine, 'begin')
def do_begin(connection):
connection.execute('BEGIN EXCLUSIVE')
return engine
| __all__ = [
'create_engine',
]
import sqlalchemy
def create_engine(
db_uri, *,
check_same_thread=False,
echo=False,
pragmas=()):
engine = sqlalchemy.create_engine(
db_uri,
echo=echo,
connect_args={
'check_same_thread': check_same_thread,
},
)
@sqlalchemy.event.listens_for(engine, 'connect')
def do_connect(dbapi_connection, _):
# Stop pysqlite issue commit automatically.
dbapi_connection.isolation_level = None
# Enable foreign key.
cursor = dbapi_connection.cursor()
cursor.execute('PRAGMA foreign_keys = ON')
for name, value in pragmas:
cursor.execute('PRAGMA %s = %s' % (name, value))
cursor.close()
@sqlalchemy.event.listens_for(engine, 'begin')
def do_begin(connection):
connection.execute('BEGIN EXCLUSIVE')
return engine
| Replace double quotes with single quotes | Replace double quotes with single quotes
| Python | mit | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage | ---
+++
@@ -25,9 +25,9 @@
dbapi_connection.isolation_level = None
# Enable foreign key.
cursor = dbapi_connection.cursor()
- cursor.execute("PRAGMA foreign_keys = ON")
+ cursor.execute('PRAGMA foreign_keys = ON')
for name, value in pragmas:
- cursor.execute("PRAGMA %s = %s" % (name, value))
+ cursor.execute('PRAGMA %s = %s' % (name, value))
cursor.close()
@sqlalchemy.event.listens_for(engine, 'begin') |
d2c368995e33b375404e3c01f79fdc5a14a48282 | polyaxon/libs/repos/utils.py | polyaxon/libs/repos/utils.py | from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_project_code_reference(project, commit=None):
if not project.has_code:
return None
repo = project.repo
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=commit)
except ObjectDoesNotExist:
return None
# If no commit is provided we get the last commit, and save new ref if not found
last_commit = repo.last_commit
if not last_commit:
return None
code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
return code_reference
def get_code_reference(instance, commit):
return get_project_code_reference(instance.project, commit=commit)
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None:
return
if not commit and instance.specification and instance.specification.build:
commit = instance.specification.build.commit
code_reference = get_code_reference(instance=instance, commit=commit)
if code_reference:
instance.code_reference = code_reference
return instance
| from django.core.exceptions import ObjectDoesNotExist
from db.models.repos import CodeReference
def get_code_reference(instance, commit=None, external_repo=None):
project = instance.project
repo = project.repo if project.has_code else external_repo
if not repo:
return None
if commit:
try:
return CodeReference.objects.get(repo=repo, commit=commit)
except ObjectDoesNotExist:
return None
# If no commit is provided we get the last commit, and save new ref if not found
last_commit = repo.last_commit
if not last_commit:
return None
code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
return code_reference
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None:
return
build = instance.specification.build if instance.specification else None
if not commit and build:
commit = build.commit
external_repo = build.git if build and build.git else None
code_reference = get_code_reference(instance=instance,
commit=commit,
external_repo=external_repo)
if code_reference:
instance.code_reference = code_reference
return instance
| Extend code references with external repos | Extend code references with external repos
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -3,11 +3,13 @@
from db.models.repos import CodeReference
-def get_project_code_reference(project, commit=None):
- if not project.has_code:
+def get_code_reference(instance, commit=None, external_repo=None):
+ project = instance.project
+
+ repo = project.repo if project.has_code else external_repo
+
+ if not repo:
return None
-
- repo = project.repo
if commit:
try:
@@ -24,16 +26,16 @@
return code_reference
-def get_code_reference(instance, commit):
- return get_project_code_reference(instance.project, commit=commit)
-
-
def assign_code_reference(instance, commit=None):
if instance.code_reference is not None:
return
- if not commit and instance.specification and instance.specification.build:
- commit = instance.specification.build.commit
- code_reference = get_code_reference(instance=instance, commit=commit)
+ build = instance.specification.build if instance.specification else None
+ if not commit and build:
+ commit = build.commit
+ external_repo = build.git if build and build.git else None
+ code_reference = get_code_reference(instance=instance,
+ commit=commit,
+ external_repo=external_repo)
if code_reference:
instance.code_reference = code_reference
|
db93242b97eb8733192d38c4b0af0377759fd647 | pysal/model/access/__init__.py | pysal/model/access/__init__.py | from access import fca
from access import raam
from access import weights
from access import helpers
from access.datasets import datasets
from access import access_log_stream
from access import access
| from access import fca
from access import raam
from access import weights
from access import helpers
from access.datasets import datasets
from access import access
| Update import for access changes | [BUG] Update import for access changes
| Python | bsd-3-clause | pysal/pysal,weikang9009/pysal,lanselin/pysal,sjsrey/pysal | ---
+++
@@ -3,5 +3,4 @@
from access import weights
from access import helpers
from access.datasets import datasets
-from access import access_log_stream
from access import access |
724335a9719174d3aeb745ed2d4c161507a08bd3 | pysparkling/fileio/textfile.py | pysparkling/fileio/textfile.py | from __future__ import absolute_import, unicode_literals
import logging
from io import StringIO
from . import codec
from .file import File
log = logging.getLogger(__name__)
class TextFile(File):
"""
Derived from :class:`pysparkling.fileio.File`.
:param file_name:
Any text file name. Supports the schemes ``http://``, ``s3://`` and
``file://``.
"""
def __init__(self, file_name):
File.__init__(self, file_name)
def load(self, encoding='utf8'):
"""
Load the data from a file.
:param encoding: (optional)
The character encoding of the file.
:returns:
An ``io.StringIO`` instance. Use ``getvalue()`` to get a string.
"""
if type(self.codec) == codec.Codec and \
getattr(self.fs, 'load_text'):
print(self.codec)
stream = self.fs.load_text()
else:
stream = self.fs.load()
stream = StringIO(
self.codec.decompress(stream).read().decode(encoding)
)
return stream
def dump(self, stream=None, encoding='utf8'):
"""
Writes a stream to a file.
:param stream:
An ``io.StringIO`` instance.
:param encoding: (optional)
The character encoding of the file.
:returns:
self
"""
if stream is None:
stream = StringIO()
stream = self.codec.compress(stream.read().encode(encoding))
self.fs.dump(stream)
return self
| from __future__ import absolute_import, unicode_literals
import logging
from io import BytesIO, StringIO
from . import codec
from .file import File
log = logging.getLogger(__name__)
class TextFile(File):
"""
Derived from :class:`pysparkling.fileio.File`.
:param file_name:
Any text file name. Supports the schemes ``http://``, ``s3://`` and
``file://``.
"""
def __init__(self, file_name):
File.__init__(self, file_name)
def load(self, encoding='utf8'):
"""
Load the data from a file.
:param encoding: (optional)
The character encoding of the file.
:returns:
An ``io.StringIO`` instance. Use ``getvalue()`` to get a string.
"""
if type(self.codec) == codec.Codec and \
getattr(self.fs, 'load_text'):
print(self.codec)
stream = self.fs.load_text()
else:
stream = self.fs.load()
stream = StringIO(
self.codec.decompress(stream).read().decode(encoding)
)
return stream
def dump(self, stream=None, encoding='utf8'):
"""
Writes a stream to a file.
:param stream:
An ``io.StringIO`` instance.
:param encoding: (optional)
The character encoding of the file.
:returns:
self
"""
if stream is None:
stream = StringIO()
stream = self.codec.compress(
BytesIO(stream.read().encode(encoding))
)
self.fs.dump(stream)
return self
| Add fileio.TextFile and use it when reading and writing text files in RDD and Context. | Add fileio.TextFile and use it when reading and writing text files in RDD and Context.
| Python | mit | giserh/pysparkling | ---
+++
@@ -1,7 +1,7 @@
from __future__ import absolute_import, unicode_literals
import logging
-from io import StringIO
+from io import BytesIO, StringIO
from . import codec
from .file import File
@@ -61,7 +61,9 @@
if stream is None:
stream = StringIO()
- stream = self.codec.compress(stream.read().encode(encoding))
+ stream = self.codec.compress(
+ BytesIO(stream.read().encode(encoding))
+ )
self.fs.dump(stream)
return self |
1b33866dd7f140efa035dfd32e0a912dfcf60f35 | utils/kvtable.py | utils/kvtable.py | '''
Abstraction of TinyDB table for storing config
'''
from tinydb import Query
class KeyValueTable:
"""Wrapper around a TinyDB table.
"""
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
self.setting = Query()
def get(self, key):
"""Get the value of named setting or None if it doesn't exist.
"""
result = self.table.get(self.setting.key == key)
if result:
return result['value']
return None
def set(self, key, value):
"""Insert or update named setting with given value.
"""
if self.table.contains(self.setting.key == key):
self.table.update({'value': value}, self.setting.key == key)
else:
self.table.insert({'key': key, 'value': value})
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
| '''
Abstraction of TinyDB table for storing config
'''
from tinydb import Query
class KeyValueTable:
"""Wrapper around a TinyDB table.
"""
setting = Query()
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
def get(self, key):
"""Get the value of named setting or None if it doesn't exist.
"""
result = self.table.get(self.setting.key == key)
if result:
return result['value']
return None
def set(self, key, value):
"""Insert or update named setting with given value.
"""
self.table.upsert({
'key': key,
'value': value
}, self.setting.key == key)
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
| Use upsert to reduce chance of duplicates | Use upsert to reduce chance of duplicates
| Python | mit | randomic/antinub-gregbot | ---
+++
@@ -8,10 +8,10 @@
"""Wrapper around a TinyDB table.
"""
+ setting = Query()
def __init__(self, tdb, name='_default'):
self.table = tdb.table(name)
- self.setting = Query()
def get(self, key):
"""Get the value of named setting or None if it doesn't exist.
@@ -26,10 +26,10 @@
"""Insert or update named setting with given value.
"""
- if self.table.contains(self.setting.key == key):
- self.table.update({'value': value}, self.setting.key == key)
- else:
- self.table.insert({'key': key, 'value': value})
+ self.table.upsert({
+ 'key': key,
+ 'value': value
+ }, self.setting.key == key)
def __getitem__(self, key):
return self.get(key) |
d7db5b38bd90502575c68d7fd5548cb64cd7447a | services/disqus.py | services/disqus.py | from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'http://disqus.com/'
docs_url = 'http://disqus.com/api/docs/'
category = 'Social'
# URLs to interact with the API
authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'
access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'
api_domain = 'disqus.com'
available_permissions = [
(None, 'read data on your behalf'),
('write', 'read and write data on your behalf'),
('admin', 'read and write data on your behalf and moderate your forums'),
]
permissions_widget = 'radio'
bearer_type = token_uri
def get_scope_string(self, scopes):
# Disqus doesn't follow the spec on this point
return ','.join(scopes)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')
return r.json[u'response'][u'id']
| from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'http://disqus.com/'
docs_url = 'http://disqus.com/api/docs/'
category = 'Social'
# URLs to interact with the API
authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'
access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'
api_domain = 'disqus.com'
available_permissions = [
(None, 'access your contact info'),
('write', 'access your contact info and add comments'),
('admin', 'access your contact info, and comments and moderate your forums'),
]
permissions_widget = 'radio'
bearer_type = token_uri
def get_scope_string(self, scopes):
# Disqus doesn't follow the spec on this point
return ','.join(scopes)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')
return r.json[u'response'][u'id']
| Reword the permissions for Disqus | Reword the permissions for Disqus
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org | ---
+++
@@ -20,9 +20,9 @@
api_domain = 'disqus.com'
available_permissions = [
- (None, 'read data on your behalf'),
- ('write', 'read and write data on your behalf'),
- ('admin', 'read and write data on your behalf and moderate your forums'),
+ (None, 'access your contact info'),
+ ('write', 'access your contact info and add comments'),
+ ('admin', 'access your contact info, and comments and moderate your forums'),
]
permissions_widget = 'radio'
|
43a2f2f27110f45e8a0d19004dac097ae67949c9 | gunicorn_config.py | gunicorn_config.py | import os
import sys
import traceback
import gunicorn
from gds_metrics.gunicorn import child_exit # noqa
workers = 5
worker_class = "eventlet"
errorlog = "/home/vcap/logs/gunicorn_error.log"
bind = "0.0.0.0:{}".format(os.getenv("PORT"))
disable_redirect_access_to_syslog = True
gunicorn.SERVER_SOFTWARE = 'None'
def worker_abort(worker):
worker.log.info("worker received ABORT")
for stack in sys._current_frames().values():
worker.log.error(''.join(traceback.format_stack(stack)))
| import os
import sys
import traceback
import eventlet
import socket
import gunicorn
from gds_metrics.gunicorn import child_exit # noqa
workers = 5
worker_class = "eventlet"
errorlog = "/home/vcap/logs/gunicorn_error.log"
bind = "0.0.0.0:{}".format(os.getenv("PORT"))
disable_redirect_access_to_syslog = True
gunicorn.SERVER_SOFTWARE = 'None'
def worker_abort(worker):
worker.log.info("worker received ABORT")
for stack in sys._current_frames().values():
worker.log.error(''.join(traceback.format_stack(stack)))
def fix_ssl_monkeypatching():
"""
eventlet works by monkey-patching core IO libraries (such as ssl) to be non-blocking. However, there's currently
a bug: In the normal socket library it may throw a timeout error as a `socket.timeout` exception. However
eventlet.green.ssl's patch raises an ssl.SSLError('timed out',) instead. redispy handles socket.timeout but not
ssl.SSLError, so we solve this by monkey patching the monkey patching code to raise the correct exception type
:scream:
https://github.com/eventlet/eventlet/issues/692
"""
# this has probably already been called somewhere in gunicorn internals, however, to be sure, we invoke it again.
# eventlet.monkey_patch can be called multiple times without issue
eventlet.monkey_patch()
eventlet.green.ssl.timeout_exc = socket.timeout
fix_ssl_monkeypatching()
| Fix rediss ssl eventlet sslerror bug | Fix rediss ssl eventlet sslerror bug
This is the same as [^1].
I did a test deploy to double check that Redis on PaaS doesn't work
without this.
[^1]: https://github.com/alphagov/notifications-api/pull/3508/commits/a2cbe2032565c61b971659aed28ebd4b096ea87d
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin | ---
+++
@@ -1,6 +1,8 @@
import os
import sys
import traceback
+import eventlet
+import socket
import gunicorn
from gds_metrics.gunicorn import child_exit # noqa
@@ -17,3 +19,21 @@
worker.log.info("worker received ABORT")
for stack in sys._current_frames().values():
worker.log.error(''.join(traceback.format_stack(stack)))
+
+
+def fix_ssl_monkeypatching():
+ """
+ eventlet works by monkey-patching core IO libraries (such as ssl) to be non-blocking. However, there's currently
+ a bug: In the normal socket library it may throw a timeout error as a `socket.timeout` exception. However
+ eventlet.green.ssl's patch raises an ssl.SSLError('timed out',) instead. redispy handles socket.timeout but not
+ ssl.SSLError, so we solve this by monkey patching the monkey patching code to raise the correct exception type
+ :scream:
+ https://github.com/eventlet/eventlet/issues/692
+ """
+ # this has probably already been called somewhere in gunicorn internals, however, to be sure, we invoke it again.
+ # eventlet.monkey_patch can be called multiple times without issue
+ eventlet.monkey_patch()
+ eventlet.green.ssl.timeout_exc = socket.timeout
+
+
+fix_ssl_monkeypatching() |
9691ff0a1fa5fee4895cc5cff33ca169498dbbc6 | encrypt.py | encrypt.py | from PIL import Image
import stepic
import sys
import os
from moviepy.editor import *
import moviepy.editor as mpy
from moviepy.editor import VideoFileClip
os.chdir("videos")
def encrypt_video(filename, userinfo):
# Orignal Video
original = VideoFileClip(filename+".mp4")
t0 = 56
first_half = VideoFileClip(filename+".mp4").subclip(0, t0)
second_half = VideoFileClip(filename+".mp4").subclip(t0+1, original.duration)
original.save_frame("frame.png", t=t0)
img = Image.open("frame.png").convert(mode='RGB')
stepic.encode_inplace(img, userinfo)
msg = stepic.decode(img)
print(msg)
"""os.system("cp frame.png fame2.png")
encoded_clip = ImageClip('frame2.png', duration=1)
new_mov = CompositeVideoClip([first_half.set_start(0),
encoded_clip.set_start(t0),
second_half.set_start(t0+1)])
# Write the result to a file (many options available !)
new_mov.write_videofile("modified_"+filename+".mp4")
"""
img = Image.open("frame.png").convert(mode='RGB')
msg = stepic.decode(img)
print(msg)
encrypt_video("gangnam_style", "ayylmaoo") | from PIL import Image
import stepic
import sys
import os
from moviepy.editor import *
import moviepy.editor as mpy
from moviepy.editor import VideoFileClip
os.chdir("videos")
def encrypt_video(filename, userinfo):
# Orignal Video
original = VideoFileClip(filename+".mp4")
t0 = 56
first_half = VideoFileClip(filename+".mp4").subclip(0, t0)
second_half = VideoFileClip(filename+".mp4").subclip(t0+1, original.duration)
original.save_frame("frame.png", t=t0)
img = Image.open("frame.png").convert(mode='RGB')
stepic.encode_inplace(img, userinfo)
msg = stepic.decode(img)
print(msg)
"""os.system("cp frame.png fame2.png")
encoded_clip = ImageClip('frame2.png', duration=1)
new_mov = CompositeVideoClip([first_half.set_start(0),
encoded_clip.set_start(t0),
second_half.set_start(t0+1)])
# Write the result to a file (many options available !)
new_mov.write_videofile("modified_"+filename+".mp4")
"""
img = Image.open("frame.png").convert(mode='RGB')
msg = stepic.decode(img)
print(msg)
encrypt_video("gangnam_style", "ayylmaoo")
| Add newline to a file | Add newline to a file
| Python | apache-2.0 | AntiPiracy/webapp,tcyrus-hackathon/scurvy-webapp,AntiPiracy/webapp,tcyrus-hackathon/scurvy-webapp,tcyrus-hackathon/scurvy-webapp,AntiPiracy/webapp | ---
+++
@@ -4,7 +4,7 @@
import os
from moviepy.editor import *
-import moviepy.editor as mpy
+import moviepy.editor as mpy
from moviepy.editor import VideoFileClip
os.chdir("videos") |
02ef2f1cb4e1e0bf3696ea68b73d0d9c3b9c8657 | events/views.py | events/views.py | from datetime import date
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
return render_to_response('events/event_archive_month.html', {'month': month})
| from datetime import date, timedelta
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
previous = month - timedelta(days=15)
next = month + timedelta(days=45)
return render_to_response('events/event_archive_month.html', {
'month': month,
'previous_month': previous,
'next_month': next,
})
| Add links to previous and next month | Add links to previous and next month
| Python | agpl-3.0 | vcorreze/agendaEteAccoord,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,mlhamel/agendadulibre | ---
+++
@@ -1,7 +1,13 @@
-from datetime import date
+from datetime import date, timedelta
from django.shortcuts import render_to_response
def month (request, year, month):
month = date(int(year), int(month), 1)
+ previous = month - timedelta(days=15)
+ next = month + timedelta(days=45)
- return render_to_response('events/event_archive_month.html', {'month': month})
+ return render_to_response('events/event_archive_month.html', {
+ 'month': month,
+ 'previous_month': previous,
+ 'next_month': next,
+ }) |
bf1f62cb7d91458e768ac31c26deb9ff67ff3a1e | rcamp/rcamp/settings/auth.py | rcamp/rcamp/settings/auth.py | AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'curc-twofactor-duo',
'csu': 'csu'
}
| AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'login',
'csu': 'csu'
}
| Change PAM stack back to login | Change PAM stack back to login
| Python | mit | ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP | ---
+++
@@ -8,6 +8,6 @@
LOGIN_URL = '/login'
PAM_SERVICES = {
- 'default': 'curc-twofactor-duo',
+ 'default': 'login',
'csu': 'csu'
} |
a18f948a6b11522425aace5a591b5f622a5534d3 | payments/forms.py | payments/forms.py | from django import forms
from payments.settings import PLAN_CHOICES
class PlanForm(forms.Form):
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")])
| from django import forms
from payments.settings import PLAN_CHOICES
class PlanForm(forms.Form):
# pylint: disable=R0924
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")])
| Disable R0924 check on PlanForm | Disable R0924 check on PlanForm
This check fails on Django 1.4 but not Django 1.5
| Python | mit | crehana/django-stripe-payments,aibon/django-stripe-payments,jawed123/django-stripe-payments,aibon/django-stripe-payments,alexhayes/django-stripe-payments,adi-li/django-stripe-payments,alexhayes/django-stripe-payments,adi-li/django-stripe-payments,ZeevG/django-stripe-payments,jawed123/django-stripe-payments,grue/django-stripe-payments,boxysean/django-stripe-payments,ZeevG/django-stripe-payments,grue/django-stripe-payments,jamespacileo/django-stripe-payments,wahuneke/django-stripe-payments,jamespacileo/django-stripe-payments,wahuneke/django-stripe-payments,crehana/django-stripe-payments,pinax/django-stripe-payments,boxysean/django-stripe-payments,wahuneke/django-stripe-payments | ---
+++
@@ -4,5 +4,5 @@
class PlanForm(forms.Form):
-
+ # pylint: disable=R0924
plan = forms.ChoiceField(choices=PLAN_CHOICES + [("", "-------")]) |
b19330abc312c8bdfa66d46b8ed9f8541a371b6b | fbmsgbot/bot.py | fbmsgbot/bot.py | from http_client import HttpClient
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient()
def send_message(self, message, completion):
def _completion(response, error):
print error
if error is None:
# TODO: Is there anything the bot needs to do?
# maybe retry if it fails...?
pass
else:
print response
completion(response)
self.client.submit_request(
'/me/messages',
'POST',
message.to_json(),
_completion)
def set_welcome(self, message, completion):
url = "/me/thread_settings?access_token=%s" % (self.access_token)
def _completion(response, error):
print error
if error is None:
# TODO: Is there anything the bot needs to do?
# maybe retry if it fails...?
pass
else:
print response
completion(response)
self.client.submit_request(
url,
'POST'
message.to_json(),
_completion)
| from http_client import HttpClient
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient(token)
def send_message(self, message, completion):
def _completion(response, error):
print error
if error is None:
# TODO: Is there anything the bot needs to do?
# maybe retry if it fails...?
pass
else:
print response
completion(response)
self.client.submit_request(
'/me/messages',
'POST',
message.to_json(),
_completion)
def set_welcome(self, message, completion):
def _completion(response, error):
print error
if error is None:
# TODO: Is there anything the bot needs to do?
# maybe retry if it fails...?
pass
else:
print response
completion(response)
self.client.submit_request(
'/me/thread_settings',
'POST',
message.to_json(),
_completion)
| Fix errors in set_welcome and update for http_client | Fix errors in set_welcome and update for http_client
| Python | mit | ben-cunningham/pybot,ben-cunningham/python-messenger-bot | ---
+++
@@ -7,7 +7,7 @@
def __init__(self, token):
self.api_token = token
- self.client = HttpClient()
+ self.client = HttpClient(token)
def send_message(self, message, completion):
@@ -28,7 +28,6 @@
_completion)
def set_welcome(self, message, completion):
- url = "/me/thread_settings?access_token=%s" % (self.access_token)
def _completion(response, error):
print error
@@ -41,8 +40,8 @@
completion(response)
self.client.submit_request(
- url,
- 'POST'
+ '/me/thread_settings',
+ 'POST',
message.to_json(),
_completion)
|
3ede075c812b116629c5f514596669b16c4784df | fulltext/backends/__json.py | fulltext/backends/__json.py | import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
_to_text(text, item)
elif isinstance(obj, string_types):
text.write(obj)
text.write(u' ')
elif isinstance(obj, integer_types):
text.write(str(obj))
text.write(u' ')
def _get_file(f, **kwargs):
text, obj = StringIO(), json.loads(f.read().decode('utf8'))
_to_text(text, obj)
return text.getvalue()
| import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
_to_text(text, item)
elif isinstance(obj, string_types + integer_types):
text.write(u'%s ' % obj)
else:
raise ValueError('Unrecognized type: %s' % obj.__class__)
def _get_file(f, **kwargs):
text, data = StringIO(), f.read()
obj = json.loads(data.decode('utf8'))
_to_text(text, obj)
return text.getvalue()
| Use format string. Readability. ValueError. | Use format string. Readability. ValueError.
| Python | mit | btimby/fulltext,btimby/fulltext | ---
+++
@@ -15,17 +15,16 @@
for item in obj:
_to_text(text, item)
- elif isinstance(obj, string_types):
- text.write(obj)
- text.write(u' ')
+ elif isinstance(obj, string_types + integer_types):
+ text.write(u'%s ' % obj)
- elif isinstance(obj, integer_types):
- text.write(str(obj))
- text.write(u' ')
+ else:
+ raise ValueError('Unrecognized type: %s' % obj.__class__)
def _get_file(f, **kwargs):
- text, obj = StringIO(), json.loads(f.read().decode('utf8'))
+ text, data = StringIO(), f.read()
+ obj = json.loads(data.decode('utf8'))
_to_text(text, obj)
|
8ba775d863e269e30ad60e0f449650575e3ff855 | dthm4kaiako/config/__init__.py | dthm4kaiako/config/__init__.py | """Configuration for Django system."""
__version__ = "0.16.0"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| """Configuration for Django system."""
__version__ = "0.16.1"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| Increment version number to 0.16.1 | Increment version number to 0.16.1
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -1,6 +1,6 @@
"""Configuration for Django system."""
-__version__ = "0.16.0"
+__version__ = "0.16.1"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num |
b6c8921b7281f24f5e8353cd0542d7ca1d18cf37 | pymemcache/test/test_serde.py | pymemcache/test/test_serde.py | from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer)
class TestSerde(TestCase):
def check(self, value):
serialized, flags = python_memcache_serializer(b'key', value)
deserialized = python_memcache_deserializer(b'key', serialized, flags)
assert deserialized == value
def test_str(self):
self.check('value')
def test_int(self):
self.check(1)
def test_long(self):
self.check(123123123123123123123)
def test_pickleable(self):
self.check({'a': 'dict'})
| from unittest import TestCase
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer)
import pytest
import six
@pytest.mark.unit()
class TestSerde(TestCase):
def check(self, value):
serialized, flags = python_memcache_serializer(b'key', value)
# pymemcache stores values as byte strings, so we immediately the value
# if needed so deserialized works as it would with a real server
if not isinstance(serialized, six.binary_type):
serialized = six.text_type(serialized).encode('ascii')
deserialized = python_memcache_deserializer(b'key', serialized, flags)
assert deserialized == value
def test_bytes(self):
self.check(b'value')
def test_unicode(self):
self.check(u'value')
def test_int(self):
self.check(1)
def test_long(self):
self.check(123123123123123123123)
def test_pickleable(self):
self.check({'a': 'dict'})
| Use byte strings after serializing with serde | Use byte strings after serializing with serde
The pymemcache client will return a byte string, so we'll do the same to test that the deserializer works as expected.
This currently fails with Python 3.
| Python | apache-2.0 | sontek/pymemcache,ewdurbin/pymemcache,sontek/pymemcache,bwalks/pymemcache,pinterest/pymemcache,pinterest/pymemcache | ---
+++
@@ -2,17 +2,29 @@
from pymemcache.serde import (python_memcache_serializer,
python_memcache_deserializer)
+import pytest
+import six
[email protected]()
class TestSerde(TestCase):
def check(self, value):
serialized, flags = python_memcache_serializer(b'key', value)
+
+ # pymemcache stores values as byte strings, so we immediately the value
+ # if needed so deserialized works as it would with a real server
+ if not isinstance(serialized, six.binary_type):
+ serialized = six.text_type(serialized).encode('ascii')
+
deserialized = python_memcache_deserializer(b'key', serialized, flags)
assert deserialized == value
- def test_str(self):
- self.check('value')
+ def test_bytes(self):
+ self.check(b'value')
+
+ def test_unicode(self):
+ self.check(u'value')
def test_int(self):
self.check(1) |
6e583085ac056b7df2b29a94cd6743493c151684 | subjectivity_clues/clues.py | subjectivity_clues/clues.py | import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmethod
def read_all(filename):
with open(filename, 'r') as f:
clues = f.readlines()
return clues
@staticmethod
def parse_clues(lines):
clues = dict()
for l in lines:
clue = dict(token.split('=') for token in shlex.split(l))
word = clue['word1']
clues[word] = clue
return clues
if __name__ == '__main__':
c = Clues()
| import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
PRIORPOLARITY = {
'positive': 1,
'negative': -1,
'both': 0,
'neutral': 0
}
TYPE = {
'strongsubj': 2,
'weaksubj': 1
}
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmethod
def read_all(filename):
with open(filename, 'r') as f:
clues = f.readlines()
return clues
@staticmethod
def parse_clues(lines):
clues = dict()
for l in lines:
clue = dict(token.split('=') for token in shlex.split(l))
word = clue['word1']
clues[word] = clue
return clues
def calculate(self, sentence):
related_words = 0
total_subjectivity = 0
total_priorpolarity = 0
for w in sentence.split(' '):
if w not in self.lexicons.keys():
continue
related_words += 1
total_subjectivity += self.TYPE[self.lexicons[w]['type']]
total_priorpolarity += self.PRIORPOLARITY[self.lexicons[w]['priorpolarity']]
return {
'sentence': sentence,
'related_words': related_words,
'total_subjectivity': total_subjectivity,
'total_priorpolarity': total_priorpolarity
}
if __name__ == '__main__':
c = Clues()
| Add calculation to the lexicon | Add calculation to the lexicon
| Python | apache-2.0 | chuajiesheng/twitter-sentiment-analysis | ---
+++
@@ -4,6 +4,18 @@
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
+
+ PRIORPOLARITY = {
+ 'positive': 1,
+ 'negative': -1,
+ 'both': 0,
+ 'neutral': 0
+ }
+
+ TYPE = {
+ 'strongsubj': 2,
+ 'weaksubj': 1
+ }
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
@@ -24,5 +36,25 @@
clues[word] = clue
return clues
+ def calculate(self, sentence):
+ related_words = 0
+ total_subjectivity = 0
+ total_priorpolarity = 0
+
+ for w in sentence.split(' '):
+ if w not in self.lexicons.keys():
+ continue
+
+ related_words += 1
+ total_subjectivity += self.TYPE[self.lexicons[w]['type']]
+ total_priorpolarity += self.PRIORPOLARITY[self.lexicons[w]['priorpolarity']]
+
+ return {
+ 'sentence': sentence,
+ 'related_words': related_words,
+ 'total_subjectivity': total_subjectivity,
+ 'total_priorpolarity': total_priorpolarity
+ }
+
if __name__ == '__main__':
c = Clues() |
13d0dfd957c1159c7fe6377637b10996ef91afcd | imhotep/shas.py | imhotep/shas.py | from collections import namedtuple
Remote = namedtuple('Remote', ('name', 'url'))
CommitInfo = namedtuple("CommitInfo",
('commit', 'origin', 'remote_repo', 'ref'))
class PRInfo(object):
def __init__(self, json):
self.json = json
@property
def base_sha(self):
return self.json['base']['sha']
@property
def head_sha(self):
return self.json['head']['sha']
@property
def base_ref(self):
return self.json['base']['ref']
@property
def head_ref(self):
return self.json['head']['ref']
@property
def has_remote_repo(self):
return self.json['base']['repo']['owner']['login'] != \
self.json['head']['repo']['owner']['login']
@property
def remote_repo(self):
remote = None
if self.has_remote_repo:
remote = Remote(name=self.json['head']['repo']['owner']['login'],
url=self.json['head']['repo']['ssh_url'])
return remote
def to_commit_info(self):
return CommitInfo(self.base_sha, self.head_sha, self.remote_repo,
self.head_ref)
def get_pr_info(requester, reponame, number):
"Returns the PullRequest as a PRInfo object"
resp = requester.get(
'https://api.github.com/repos/%s/pulls/%s' % (reponame, number))
return PRInfo(resp.json())
| from collections import namedtuple
Remote = namedtuple('Remote', ('name', 'url'))
CommitInfo = namedtuple("CommitInfo",
('commit', 'origin', 'remote_repo', 'ref'))
class PRInfo(object):
def __init__(self, json):
self.json = json
@property
def base_sha(self):
return self.json['base']['sha']
@property
def head_sha(self):
return self.json['head']['sha']
@property
def base_ref(self):
return self.json['base']['ref']
@property
def head_ref(self):
return self.json['head']['ref']
@property
def has_remote_repo(self):
return self.json['base']['repo']['owner']['login'] != \
self.json['head']['repo']['owner']['login']
@property
def remote_repo(self):
remote = None
if self.has_remote_repo:
remote = Remote(name=self.json['head']['repo']['owner']['login'],
url=self.json['head']['repo']['clone_url'])
return remote
def to_commit_info(self):
return CommitInfo(self.base_sha, self.head_sha, self.remote_repo,
self.head_ref)
def get_pr_info(requester, reponame, number):
"Returns the PullRequest as a PRInfo object"
resp = requester.get(
'https://api.github.com/repos/%s/pulls/%s' % (reponame, number))
return PRInfo(resp.json())
| Use github's `clone_url` instead of mandating ssh. | Use github's `clone_url` instead of mandating ssh.
| Python | mit | richtier/imhotep,justinabrahms/imhotep,justinabrahms/imhotep | ---
+++
@@ -35,7 +35,7 @@
remote = None
if self.has_remote_repo:
remote = Remote(name=self.json['head']['repo']['owner']['login'],
- url=self.json['head']['repo']['ssh_url'])
+ url=self.json['head']['repo']['clone_url'])
return remote
def to_commit_info(self): |
0db4d0f3df3b9541aaf6301c11f83376debb41ff | lib/get_version.py | lib/get_version.py | #!/usr/bin/env python
""" Extracts the version of the khmer project. """
import sys
import pkg_resources
try:
print pkg_resources.get_distribution( # pylint: disable=E1103
'khmer').version
except pkg_resources.DistributionNotFound:
print 'To build the khmer library, the distribution information'
print 'has to be available. Either install the package into your'
print 'development environment or run "setup.py develop" to setup the'
print 'metadata. A virtualenv is recommended!'
sys.exit(1)
del pkg_resources
| import sys
sys.path.insert(0, '../')
import versioneer
versioneer.VCS = 'git'
versioneer.versionfile_source = '../khmer/_version.py'
versioneer.versionfile_build = '../khmer/_version.py'
versioneer.tag_prefix = 'v' # tags are like v1.2.0
versioneer.parentdir_prefix = '..'
print versioneer.get_version()
| Use versioneer for ./lib version | Use versioneer for ./lib version
- Allows the version to be obtained without khmer being installed.
| Python | bsd-3-clause | Winterflower/khmer,kdmurray91/khmer,souravsingh/khmer,souravsingh/khmer,Winterflower/khmer,jas14/khmer,ged-lab/khmer,ged-lab/khmer,Winterflower/khmer,F1000Research/khmer,F1000Research/khmer,jas14/khmer,kdmurray91/khmer,souravsingh/khmer,ged-lab/khmer,kdmurray91/khmer,F1000Research/khmer,jas14/khmer | ---
+++
@@ -1,16 +1,10 @@
-#!/usr/bin/env python
-""" Extracts the version of the khmer project. """
+import sys
+sys.path.insert(0, '../')
+import versioneer
+versioneer.VCS = 'git'
+versioneer.versionfile_source = '../khmer/_version.py'
+versioneer.versionfile_build = '../khmer/_version.py'
+versioneer.tag_prefix = 'v' # tags are like v1.2.0
+versioneer.parentdir_prefix = '..'
-import sys
-import pkg_resources
-
-try:
- print pkg_resources.get_distribution( # pylint: disable=E1103
- 'khmer').version
-except pkg_resources.DistributionNotFound:
- print 'To build the khmer library, the distribution information'
- print 'has to be available. Either install the package into your'
- print 'development environment or run "setup.py develop" to setup the'
- print 'metadata. A virtualenv is recommended!'
- sys.exit(1)
-del pkg_resources
+print versioneer.get_version() |
c07f9d2b455ec312d22a5aa07f9d724ee4cd1e42 | grab/tools/logs.py | grab/tools/logs.py | import logging
def default_logging(grab_log='/tmp/grab.log'):
"""
Customize logging output to display all log messages
except grab network logs.
Redirect grab network logs into file.
"""
logging.basicConfig(level=logging.DEBUG)
glog = logging.getLogger('grab')
glog.propagate = False
if grab_log:
hdl = logging.FileHandler(grab_log, 'w')
glog.addHandler(hdl)
| import logging
def default_logging(grab_log='/tmp/grab.log', level=logging.DEBUG, mode='a'):
"""
Customize logging output to display all log messages
except grab network logs.
Redirect grab network logs into file.
"""
logging.basicConfig(level=level)
glog = logging.getLogger('grab')
glog.propagate = False
if grab_log:
hdl = logging.FileHandler(grab_log, mode)
glog.addHandler(hdl)
| Create additional options for default_logging function | Create additional options for default_logging function
| Python | mit | SpaceAppsXploration/grab,maurobaraldi/grab,giserh/grab,lorien/grab,SpaceAppsXploration/grab,subeax/grab,huiyi1990/grab,raybuhr/grab,DDShadoww/grab,codevlabs/grab,pombredanne/grab-1,liorvh/grab,lorien/grab,DDShadoww/grab,huiyi1990/grab,codevlabs/grab,alihalabyah/grab,liorvh/grab,maurobaraldi/grab,subeax/grab,istinspring/grab,shaunstanislaus/grab,istinspring/grab,alihalabyah/grab,kevinlondon/grab,giserh/grab,subeax/grab,kevinlondon/grab,pombredanne/grab-1,raybuhr/grab,shaunstanislaus/grab | ---
+++
@@ -1,6 +1,6 @@
import logging
-def default_logging(grab_log='/tmp/grab.log'):
+def default_logging(grab_log='/tmp/grab.log', level=logging.DEBUG, mode='a'):
"""
Customize logging output to display all log messages
except grab network logs.
@@ -8,9 +8,9 @@
Redirect grab network logs into file.
"""
- logging.basicConfig(level=logging.DEBUG)
+ logging.basicConfig(level=level)
glog = logging.getLogger('grab')
glog.propagate = False
if grab_log:
- hdl = logging.FileHandler(grab_log, 'w')
+ hdl = logging.FileHandler(grab_log, mode)
glog.addHandler(hdl) |
e046bbd4027275a94888bd70138000cdb2da67f3 | pages/search_indexes.py | pages/search_indexes.py | """Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex) | """Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
title = CharField(model_attr='title')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex) | Add a title attribute to the SearchIndex for pages. | Add a title attribute to the SearchIndex for pages.
This is useful when displaying a list of search results because we
can display the title of the result without hitting the database to
actually pull the page.
| Python | bsd-3-clause | batiste/django-page-cms,remik/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,batiste/django-page-cms,batiste/django-page-cms,pombredanne/django-page-cms-1 | ---
+++
@@ -9,6 +9,7 @@
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
+ title = CharField(model_attr='title')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self): |
227244ae21c98b52a460beb942a8200ab66c0633 | grappa/__init__.py | grappa/__init__.py | # -*- coding: utf-8 -*
"""
`grappa` provides two different testing styles: `should` and `expect`.
should
------
Example using ``should`` style::
from grappa import should
should('foo').be.equal.to('foo')
'foo' | should.be.equal.to('foo')
expect
------
Example using ``expect`` style::
from grappa import expect
expect([1, 2, 3]).to.contain([2, 3])
[1, 2, 3] | expect.to.contain([2, 3])
For assertion operators and aliases, see `operators documentation`_.
.. _`operators documentation`: operators.html
Reference
---------
"""
# Export public API module members
from .api import * # noqa
from .api import __all__ # noqa
# Package metadata
__author__ = 'Tomas Aparicio'
__license__ = 'MIT'
# Current package version
__version__ = '0.1.8'
| # -*- coding: utf-8 -*
"""
`grappa` provides two different testing styles: `should` and `expect`.
should
------
Example using ``should`` style::
from grappa import should
should('foo').be.equal.to('foo')
'foo' | should.be.equal.to('foo')
expect
------
Example using ``expect`` style::
from grappa import expect
expect([1, 2, 3]).to.contain([2, 3])
[1, 2, 3] | expect.to.contain([2, 3])
For assertion operators and aliases, see `operators documentation`_.
.. _`operators documentation`: operators.html
Reference
---------
"""
# Export public API module members
from .api import * # noqa
from .api import __all__ # noqa
# Package metadata
__author__ = 'Tomas Aparicio'
__license__ = 'MIT'
# Current package version
__version__ = '0.1.9'
| Bump version: 0.1.8 → 0.1.9 | Bump version: 0.1.8 → 0.1.9
| Python | mit | grappa-py/grappa | ---
+++
@@ -40,4 +40,4 @@
__license__ = 'MIT'
# Current package version
-__version__ = '0.1.8'
+__version__ = '0.1.9' |
4ca82986828514f26d06270477a2d243ebd91294 | tests/hummus/test_document.py | tests/hummus/test_document.py | # -*- coding: utf-8 -*-
import hummus
from tempfile import NamedTemporaryFile
import os
def assert_pdf(filename):
with open(filename, 'rb') as stream:
assert stream.read(4) == b'%PDF'
def test_document_file():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
document = hummus.Document(filename=stream.name)
document.begin()
document.end()
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
def test_document_stream():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
document = hummus.Document(stream)
document.begin()
document.end()
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
def test_page_size():
page = hummus.Page()
assert page.media_box.left == 0
page.media_box = hummus.Rectangle(0, 0, 800, 1000)
assert page.media_box.bottom == 1000
def test_basic_text():
with NamedTemporaryFile(delete=False) as stream:
with hummus.Document(stream) as document:
with document.Page() as page:
pass
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
| # -*- coding: utf-8 -*-
import hummus
from tempfile import NamedTemporaryFile
import os
def assert_pdf(filename):
with open(filename, 'rb') as stream:
assert stream.read(4) == b'%PDF'
def test_document_file():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
document = hummus.Document(stream.name)
document.begin()
document.end()
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
def test_document_stream():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
document = hummus.Document(stream)
document.begin()
document.end()
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
def test_page_size():
page = hummus.Page()
assert page.media_box.left == 0
page.media_box = hummus.Rectangle(0, 0, 800, 1000)
assert page.media_box.bottom == 1000
def test_basic_text():
with NamedTemporaryFile(delete=False) as stream:
with hummus.Document(stream) as document:
with document.Page() as page:
pass
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
| Update tests for new API. | Update tests for new API.
| Python | mit | concordusapps/python-hummus,concordusapps/python-hummus | ---
+++
@@ -12,7 +12,7 @@
def test_document_file():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
- document = hummus.Document(filename=stream.name)
+ document = hummus.Document(stream.name)
document.begin()
document.end()
|
58eede75663fda02a7323fa6579a6ca8ac83f2fd | belogging/defaults.py | belogging/defaults.py |
DEFAULT_LOGGING_CONF = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {'format': '%(asctime)s %(module)s %(message)s'},
},
'filters': {
'logger_filter': {
'()': 'belogging.filters.LoggerFilter',
},
},
'handlers': {
'default': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'default',
'filters': ['logger_filter'],
},
'null': {
'class': 'logging.NullHandler',
},
},
'root': {
'handlers': ['default'],
'level': 'DEBUG',
},
'loggers': {},
}
DEFAULT_KVP_FORMAT = 'asctime=%(asctime)s level=%(levelname)s module=%(module)s line=%(lineno)s message=%(message)s'
LEVEL_MAP = {'DISABLED': 60,
'CRITICAL': 50,
'FATAL': 50,
'ERROR': 40,
'WARNING': 30,
'WARN': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0}
|
DEFAULT_LOGGING_CONF = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {'format': '%(asctime)s %(module)s %(message)s'},
},
'filters': {
'logger_filter': {
'()': 'belogging.filters.LoggerFilter',
},
},
'handlers': {
'default': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'default',
'filters': ['logger_filter'],
},
'null': {
'class': 'logging.NullHandler',
},
},
'root': {
'handlers': ['default'],
'level': 'DEBUG',
},
'loggers': {},
}
DEFAULT_KVP_FORMAT = 'asctime=%(asctime)s level=%(levelname)s pathname=%(pathname)s line=%(lineno)s message=%(message)s'
LEVEL_MAP = {'DISABLED': 60,
'CRITICAL': 50,
'FATAL': 50,
'ERROR': 40,
'WARNING': 30,
'WARN': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0}
| Replace %(module)s with %(pathname)s in DEFAULT_KVP_FORMAT | Replace %(module)s with %(pathname)s in DEFAULT_KVP_FORMAT
The pathname gives more context in large projects that contains repeated module
names (eg models, base, etc).
| Python | mit | georgeyk/belogging | ---
+++
@@ -29,7 +29,7 @@
}
-DEFAULT_KVP_FORMAT = 'asctime=%(asctime)s level=%(levelname)s module=%(module)s line=%(lineno)s message=%(message)s'
+DEFAULT_KVP_FORMAT = 'asctime=%(asctime)s level=%(levelname)s pathname=%(pathname)s line=%(lineno)s message=%(message)s'
LEVEL_MAP = {'DISABLED': 60, |
273dd930836345fccc42e8f1a6720f04b29a46f1 | pytui/settings.py | pytui/settings.py | from __future__ import unicode_literals
DEBUG_MODULES = [
# 'pytui',
]
VERSION = '0.3.1b'
| from __future__ import unicode_literals
DEBUG_MODULES = [
# 'pytui',
]
VERSION = '0.3.1b0'
| Repair version, beta needs a number. | Repair version, beta needs a number.
| Python | mit | martinsmid/pytest-ui | ---
+++
@@ -3,4 +3,4 @@
# 'pytui',
]
-VERSION = '0.3.1b'
+VERSION = '0.3.1b0' |
dcc5c7be6f8463f41e1d1697bdba7fd576382259 | master/rc_force.py | master/rc_force.py | # Add a manual scheduler for building release candidates
rc_scheduler = ForceScheduler(
name="rc build",
builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm"],
reason=FixedParameter(name="reason", default=""),
branch=FixedParameter(name="branch", default=""),
repository=FixedParameter(name="repository", default=""),
project=FixedParameter(name="project", default="Packaging"),
properties=[
]
)
c['schedulers'].append(rc_scheduler)
| # Add a manual scheduler for building release candidates
rc_scheduler = ForceScheduler(
name="rc build",
builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm", "package_tarballppc64le"],
reason=FixedParameter(name="reason", default=""),
branch=FixedParameter(name="branch", default=""),
repository=FixedParameter(name="repository", default=""),
project=FixedParameter(name="project", default="Packaging"),
properties=[
]
)
c['schedulers'].append(rc_scheduler)
| Add ppc64le tarball rc force builder | Add ppc64le tarball rc force builder
| Python | mit | staticfloat/julia-buildbot,staticfloat/julia-buildbot | ---
+++
@@ -1,7 +1,7 @@
# Add a manual scheduler for building release candidates
rc_scheduler = ForceScheduler(
name="rc build",
- builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm"],
+ builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm", "package_tarballppc64le"],
reason=FixedParameter(name="reason", default=""),
branch=FixedParameter(name="branch", default=""),
repository=FixedParameter(name="repository", default=""), |
f4be8fd80b1aad9babdfbc56dec331af635f5554 | migrations/versions/0165_another_letter_org.py | migrations/versions/0165_another_letter_org.py | """empty message
Revision ID: 0165_another_letter_org
Revises: 0164_add_organisation_to_service
Create Date: 2017-06-29 12:44:16.815039
"""
# revision identifiers, used by Alembic.
revision = '0165_another_letter_org'
down_revision = '0164_add_organisation_to_service'
from alembic import op
NEW_ORGANISATIONS = [
('502', 'Welsh Revenue Authority'),
]
def upgrade():
for numeric_id, name in NEW_ORGANISATIONS:
op.execute("""
INSERT
INTO dvla_organisation
VALUES ('{}', '{}')
""".format(numeric_id, name))
def downgrade():
for numeric_id, _ in NEW_ORGANISATIONS:
op.execute("""
DELETE
FROM dvla_organisation
WHERE id = '{}'
""".format(numeric_id))
| """empty message
Revision ID: 0165_another_letter_org
Revises: 0164_add_organisation_to_service
Create Date: 2017-06-29 12:44:16.815039
"""
# revision identifiers, used by Alembic.
revision = '0165_another_letter_org'
down_revision = '0164_add_organisation_to_service'
from alembic import op
NEW_ORGANISATIONS = [
('502', 'Welsh Revenue Authority'),
('503', 'East Riding of Yorkshire Council'),
]
def upgrade():
for numeric_id, name in NEW_ORGANISATIONS:
op.execute("""
INSERT
INTO dvla_organisation
VALUES ('{}', '{}')
""".format(numeric_id, name))
def downgrade():
for numeric_id, _ in NEW_ORGANISATIONS:
op.execute("""
DELETE
FROM dvla_organisation
WHERE id = '{}'
""".format(numeric_id))
| Add East Riding of Yorkshire Council to migration | Add East Riding of Yorkshire Council to migration
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | ---
+++
@@ -15,6 +15,7 @@
NEW_ORGANISATIONS = [
('502', 'Welsh Revenue Authority'),
+ ('503', 'East Riding of Yorkshire Council'),
]
|
73dd57a0d27b08089f91f303d3d36e428b108618 | CI/syntaxCheck.py | CI/syntaxCheck.py | import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
#"AKD":"/ApplicationExamples/AKD/package.mo",
#"N44":"/ApplicationExamples/N44/package.mo",
#"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
#"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}
# Instance of CITests
ci = CITests("/OpenIPSL")
# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo")
if not passLib:
# Error in OpenIPSL
sys.exit(1)
else:
# Run Check on App Examples
passAppEx = 1
for package in appExamples.keys():
passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])
# The tests are failing if the number of failed check > 0
if passAppEx:
# Everything is fine
sys.exit(0)
else:
# Exit with error
sys.exit(1)
| import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
#"AKD":"/ApplicationExamples/AKD/package.mo",
#"N44":"/ApplicationExamples/N44/package.mo",
#"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
#"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}
# Instance of CITests
ci = CITests("/OpenIPSL")
# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo")
if not passLib:
# Error in OpenIPSL
sys.exit(1)
else:
# Run Check on App Examples
passAppEx = 1
for package in appExamples.keys():
passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])
# The tests are failing if the number of failed check > 0
if passAppEx:
# Everything is fine
sys.exit(0)
else:
# Exit with error
sys.exit(1)
| Revert "Fix the location path of OpenIPSL" | Revert "Fix the location path of OpenIPSL"
This reverts commit 5b3af4a6c1c77c651867ee2b5f5cef5100944ba6.
| Python | bsd-3-clause | SmarTS-Lab/OpenIPSL,OpenIPSL/OpenIPSL,SmarTS-Lab/OpenIPSL,tinrabuzin/OpenIPSL | ---
+++
@@ -18,7 +18,7 @@
ci = CITests("/OpenIPSL")
# Run Check on OpenIPSL
-passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo")
+passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo")
if not passLib:
# Error in OpenIPSL |
dc0dfd4a763dceef655d62e8364b92a8073b7751 | chrome/chromehost.py | chrome/chromehost.py | #!/usr/bin/env python
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
socket_name = '/tmp/cachebrowser.sock'
sock.connect(socket_name)
message = read_from_chrome()
sock.send(message)
sock.send('\n')
response = ''
while True:
read = sock.recv(1024)
if len(read) == 0:
break
response += read
# response = sock.recv(1024)
send_to_chrome(response)
| #!/usr/bin/env python
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# socket_name = '/tmp/cachebrowser.sock'
# sock.connect(socket_name)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4242))
message = read_from_chrome()
sock.send(message)
sock.send('\n')
# response = ''
# while True:
# read = sock.recv(1024)
# if len(read) == 0:
# break
# response += read
response = sock.recv(1024)
send_to_chrome(response)
# send_to_chrome("{}")
| Change chromhost to use normal sockets | Change chromhost to use normal sockets
| Python | mit | CacheBrowser/cachebrowser,NewBie1993/cachebrowser | ---
+++
@@ -24,21 +24,24 @@
return text
-sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-socket_name = '/tmp/cachebrowser.sock'
-sock.connect(socket_name)
+# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+# socket_name = '/tmp/cachebrowser.sock'
+# sock.connect(socket_name)
+sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+sock.connect(('127.0.0.1', 4242))
message = read_from_chrome()
sock.send(message)
sock.send('\n')
-response = ''
-while True:
- read = sock.recv(1024)
- if len(read) == 0:
- break
- response += read
-# response = sock.recv(1024)
+# response = ''
+# while True:
+# read = sock.recv(1024)
+# if len(read) == 0:
+# break
+# response += read
+response = sock.recv(1024)
send_to_chrome(response)
+# send_to_chrome("{}") |
78ca616d611a6c9b8364cf25a21affd80e261ff8 | cutplanner/planner.py | cutplanner/planner.py | import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = needed.reverse
self.cut_loss = loss
self.cur_stock = None
@property
def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
self.cur_stock.cut(piece, self.cut_loss)
def finalize_stock(self):
""" Takes current stock out of use, attempts to shrink """
# shrink as much as possible
for smaller in self.stock_sizes[-2::-1]:
if self.cur_stock.shrink(smaller) is None:
break
self.stock.append(self.cur_stock)
def apply_next_fit(self, piece):
""" Cut from current stock until unable, then move to new stock """
if self.cur_stock.remaining_length < piece.length + self.cut_loss:
# finalize current stock and get fresh stock
self.finalize_stock()
cur_stock = Stock(self.largest_stock)
self.cur_stock.cut(piece, self.cut_loss)
| import collections
from stock import Stock
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = [Piece(i, s) for i, s in enumerate(needed)]
self.pieces_needed.reverse()
self.cut_loss = loss
self.cur_stock = None
@property
def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
self.cur_stock.cut(piece, self.cut_loss)
def finalize_stock(self):
""" Takes current stock out of use, attempts to shrink """
# shrink as much as possible
for smaller in self.stock_sizes[-2::-1]:
if self.cur_stock.shrink(smaller) is None:
break
self.stock.append(self.cur_stock)
def apply_next_fit(self, piece):
""" Cut from current stock until unable, then move to new stock """
if self.cur_stock.remaining_length < piece.length + self.cut_loss:
# finalize current stock and get fresh stock
self.finalize_stock()
cur_stock = Stock(self.largest_stock)
self.cur_stock.cut(piece, self.cut_loss)
| Set up list of needed pieces on init | Set up list of needed pieces on init
| Python | mit | alanc10n/py-cutplanner | ---
+++
@@ -9,7 +9,8 @@
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
- self.pieces_needed = needed.reverse
+ self.pieces_needed = [Piece(i, s) for i, s in enumerate(needed)]
+ self.pieces_needed.reverse()
self.cut_loss = loss
self.cur_stock = None
|
131f0d3a67bc6ba995d1f45dd8c85594d8d8e79c | tests/run_tests.py | tests/run_tests.py | """Python script to run all tests"""
import pytest
if __name__ == '__main__':
pytest.main()
| """Python script to run all tests"""
import sys
import pytest
if __name__ == '__main__':
sys.exit(pytest.main())
| Allow Jenkins to actually report build failures | Allow Jenkins to actually report build failures
| Python | mit | gatkin/declxml | ---
+++
@@ -1,5 +1,8 @@
"""Python script to run all tests"""
+import sys
+
import pytest
+
if __name__ == '__main__':
- pytest.main()
+ sys.exit(pytest.main()) |
2d8ddb4ab59bc7198b637bcc9e51914379ff408b | tests/test_i18n.py | tests/test_i18n.py | import datetime as dt
import humanize
def test_i18n():
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
humanize.i18n.activate("ru_RU")
assert humanize.naturaltime(three_seconds) == "3 секунды назад"
humanize.i18n.deactivate()
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
| import datetime as dt
import humanize
def test_i18n():
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
assert humanize.ordinal(5) == "5th"
try:
humanize.i18n.activate("ru_RU")
assert humanize.naturaltime(three_seconds) == "3 секунды назад"
assert humanize.ordinal(5) == "5ый"
finally:
humanize.i18n.deactivate()
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
assert humanize.ordinal(5) == "5th"
| Add i18n test for humanize.ordinal | Add i18n test for humanize.ordinal
| Python | mit | jmoiron/humanize,jmoiron/humanize | ---
+++
@@ -7,9 +7,13 @@
three_seconds = dt.timedelta(seconds=3)
assert humanize.naturaltime(three_seconds) == "3 seconds ago"
+ assert humanize.ordinal(5) == "5th"
- humanize.i18n.activate("ru_RU")
- assert humanize.naturaltime(three_seconds) == "3 секунды назад"
-
- humanize.i18n.deactivate()
- assert humanize.naturaltime(three_seconds) == "3 seconds ago"
+ try:
+ humanize.i18n.activate("ru_RU")
+ assert humanize.naturaltime(three_seconds) == "3 секунды назад"
+ assert humanize.ordinal(5) == "5ый"
+ finally:
+ humanize.i18n.deactivate()
+ assert humanize.naturaltime(three_seconds) == "3 seconds ago"
+ assert humanize.ordinal(5) == "5th" |
7cde727c5a1a5de652e6b1c3d207c5b51fe719cf | mission.py | mission.py | # coding: utf-8
"""
Mission simulation.
"""
from rover import Plateau, Rover, Heading, Command
if __name__ == '__main__':
instructions = open('instructions.txt', 'r')
# Prepare the plateau to landings.
data = instructions.readline().split()
x, y = map(int, data)
plateau = Plateau(x, y)
# Deploy Rovers on the plateau.
for data in instructions:
x, y, heading = data.split()
rover = Rover(int(x), int(y), getattr(Heading, heading), plateau)
# Parse and run instructions.
commands = instructions.readline().strip()
for cmd in commands:
command = getattr(Command, cmd)
rover.execute(command)
print(rover)
instructions.close()
| # coding: utf-8
"""
Mission simulation.
"""
from rover import Plateau, Rover, Heading, Command
if __name__ == '__main__':
instructions = open('instructions.txt', 'r')
# Prepare the plateau to landings.
data = instructions.readline().split()
x, y = map(int, data)
plateau = Plateau(x, y)
# Deploy Rovers on the plateau.
for data in instructions:
x, y, heading = data.split()
rover = Rover(int(x), int(y), getattr(Heading, heading), plateau)
# Parse and run instructions.
commands = instructions.readline().strip()
for cmd in commands:
command = getattr(Command, cmd, None)
rover.execute(command)
print(rover)
instructions.close()
| Fix to deal with invalid commands. | Fix to deal with invalid commands.
| Python | mit | rodrigobraga/Mars-Rover-Challenge | ---
+++
@@ -23,7 +23,7 @@
# Parse and run instructions.
commands = instructions.readline().strip()
for cmd in commands:
- command = getattr(Command, cmd)
+ command = getattr(Command, cmd, None)
rover.execute(command)
print(rover) |
8e26fa46ffdb9442254712b4083a973ab9ce6577 | Python/tangshi.py | Python/tangshi.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import re
import codecs
ping = re.compile(u'.平')
shang = re.compile(u'上聲')
ru = re.compile(u'入')
qu = re.compile(u'去')
mydict = { }
# f = open("../Data/TangRhymesMap.csv")
f = codecs.open("../Data/TangRhymesMap.csv", "r", "utf-8")
for line in f:
line = line.rstrip()
value, key = line.split(",")
#key = char.decode("utf-8")
#value = rhyme.decode("utf-8")
mydict[key] = value
f = codecs.open("../Data/SamplePoem.txt", "r", "utf-8")
for line in f:
line = line.rstrip()
for key in line:
if ping.match(mydict[key]):
print key + " = " + " Ping"
elif shang.match(mydict[key]):
print key + " = " + " Shang"
elif qu.match(mydict[key]):
print key + " = " + " Qu"
elif ru.match(mydict[key]):
print key + " = " + " Ru"
else:
print key + " = " + " *"
| #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import re
import codecs
ping = re.compile(u'.平')
shang = re.compile(u'上聲')
ru = re.compile(u'入')
qu = re.compile(u'去')
mydict = { }
# f = open("../Data/TangRhymesMap.csv")
f = codecs.open("../Data/TangRhymesMap.csv", "r", "utf-8")
for line in f:
line = line.rstrip()
value, key = line.split(",")
#key = char.decode("utf-8")
#value = rhyme.decode("utf-8")
mydict[key] = value
f = codecs.open("../Data/SamplePoem.txt", "r", "utf-8")
for line in f:
line = line.rstrip()
for key in line:
if key not in mydict:
print key
elif ping.match(mydict[key]):
print key + " = " + " Ping"
elif shang.match(mydict[key]):
print key + " = " + " Shang"
elif qu.match(mydict[key]):
print key + " = " + " Qu"
elif ru.match(mydict[key]):
print key + " = " + " Ru"
else:
print key + " = " + " *"
| Print the character without Rhyme if it is not on the Rhyme Dictionary | Print the character without Rhyme if it is not on the Rhyme Dictionary
| Python | apache-2.0 | jmworsley/TangShi | ---
+++
@@ -26,7 +26,9 @@
for line in f:
line = line.rstrip()
for key in line:
- if ping.match(mydict[key]):
+ if key not in mydict:
+ print key
+ elif ping.match(mydict[key]):
print key + " = " + " Ping"
elif shang.match(mydict[key]):
print key + " = " + " Shang" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.