commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 0
2.94k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
444
| message
stringlengths 16
3.45k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43.2k
| prompt
stringlengths 17
4.58k
| response
stringlengths 1
4.43k
| prompt_tagged
stringlengths 58
4.62k
| response_tagged
stringlengths 1
4.43k
| text
stringlengths 132
7.29k
| text_tagged
stringlengths 173
7.33k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2775c7f39c0e26b728fe6fb31168328ba4caeab2
|
opps/api/models.py
|
opps/api/models.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
key = models.CharField(u"Key", max_length=255)
date_insert = models.DateTimeField(u"Date insert", auto_now_add=True)
def __unicode__(self):
return u"{} for {}".format(self.key, self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(ApiKey, self).save(*args, **kwargs)
def generate_key(self):
new_uuid = uuid.uuid4()
return hmac.new(new_uuid.bytes, digestmod=sha1).hexdigest()
def create_api_key(sender, **kwargs):
if kwargs.get('created') is True:
ApiKey.objects.create(user=kwargs.get('instance'))
models.signals.post_save.connect(create_api_key, settings.AUTH_USER_MODEL)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
key = models.CharField(u"Key", max_length=255)
date_insert = models.DateTimeField(u"Date insert", auto_now_add=True)
def __unicode__(self):
return u"{} for {}".format(self.key, self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(ApiKey, self).save(*args, **kwargs)
def generate_key(self):
new_uuid = uuid.uuid4()
return hmac.new(new_uuid.bytes, digestmod=sha1).hexdigest()
def create_api_key(sender, **kwargs):
if kwargs.get('created') is True:
ApiKey.objects.create(user=kwargs.get('instance'))
models.signals.post_save.connect(create_api_key, User)
|
Fix signal create api key on post save User
|
Fix signal create api key on post save User
|
Python
|
mit
|
williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,YACOWS/opps
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
key = models.CharField(u"Key", max_length=255)
date_insert = models.DateTimeField(u"Date insert", auto_now_add=True)
def __unicode__(self):
return u"{} for {}".format(self.key, self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(ApiKey, self).save(*args, **kwargs)
def generate_key(self):
new_uuid = uuid.uuid4()
return hmac.new(new_uuid.bytes, digestmod=sha1).hexdigest()
def create_api_key(sender, **kwargs):
if kwargs.get('created') is True:
ApiKey.objects.create(user=kwargs.get('instance'))
models.signals.post_save.connect(create_api_key, settings.AUTH_USER_MODEL)
Fix signal create api key on post save User
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
key = models.CharField(u"Key", max_length=255)
date_insert = models.DateTimeField(u"Date insert", auto_now_add=True)
def __unicode__(self):
return u"{} for {}".format(self.key, self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(ApiKey, self).save(*args, **kwargs)
def generate_key(self):
new_uuid = uuid.uuid4()
return hmac.new(new_uuid.bytes, digestmod=sha1).hexdigest()
def create_api_key(sender, **kwargs):
if kwargs.get('created') is True:
ApiKey.objects.create(user=kwargs.get('instance'))
models.signals.post_save.connect(create_api_key, User)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
key = models.CharField(u"Key", max_length=255)
date_insert = models.DateTimeField(u"Date insert", auto_now_add=True)
def __unicode__(self):
return u"{} for {}".format(self.key, self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(ApiKey, self).save(*args, **kwargs)
def generate_key(self):
new_uuid = uuid.uuid4()
return hmac.new(new_uuid.bytes, digestmod=sha1).hexdigest()
def create_api_key(sender, **kwargs):
if kwargs.get('created') is True:
ApiKey.objects.create(user=kwargs.get('instance'))
models.signals.post_save.connect(create_api_key, settings.AUTH_USER_MODEL)
<commit_msg>Fix signal create api key on post save User<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
key = models.CharField(u"Key", max_length=255)
date_insert = models.DateTimeField(u"Date insert", auto_now_add=True)
def __unicode__(self):
return u"{} for {}".format(self.key, self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(ApiKey, self).save(*args, **kwargs)
def generate_key(self):
new_uuid = uuid.uuid4()
return hmac.new(new_uuid.bytes, digestmod=sha1).hexdigest()
def create_api_key(sender, **kwargs):
if kwargs.get('created') is True:
ApiKey.objects.create(user=kwargs.get('instance'))
models.signals.post_save.connect(create_api_key, User)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
key = models.CharField(u"Key", max_length=255)
date_insert = models.DateTimeField(u"Date insert", auto_now_add=True)
def __unicode__(self):
return u"{} for {}".format(self.key, self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(ApiKey, self).save(*args, **kwargs)
def generate_key(self):
new_uuid = uuid.uuid4()
return hmac.new(new_uuid.bytes, digestmod=sha1).hexdigest()
def create_api_key(sender, **kwargs):
if kwargs.get('created') is True:
ApiKey.objects.create(user=kwargs.get('instance'))
models.signals.post_save.connect(create_api_key, settings.AUTH_USER_MODEL)
Fix signal create api key on post save User#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
key = models.CharField(u"Key", max_length=255)
date_insert = models.DateTimeField(u"Date insert", auto_now_add=True)
def __unicode__(self):
return u"{} for {}".format(self.key, self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(ApiKey, self).save(*args, **kwargs)
def generate_key(self):
new_uuid = uuid.uuid4()
return hmac.new(new_uuid.bytes, digestmod=sha1).hexdigest()
def create_api_key(sender, **kwargs):
if kwargs.get('created') is True:
ApiKey.objects.create(user=kwargs.get('instance'))
models.signals.post_save.connect(create_api_key, User)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
key = models.CharField(u"Key", max_length=255)
date_insert = models.DateTimeField(u"Date insert", auto_now_add=True)
def __unicode__(self):
return u"{} for {}".format(self.key, self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(ApiKey, self).save(*args, **kwargs)
def generate_key(self):
new_uuid = uuid.uuid4()
return hmac.new(new_uuid.bytes, digestmod=sha1).hexdigest()
def create_api_key(sender, **kwargs):
if kwargs.get('created') is True:
ApiKey.objects.create(user=kwargs.get('instance'))
models.signals.post_save.connect(create_api_key, settings.AUTH_USER_MODEL)
<commit_msg>Fix signal create api key on post save User<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
import hmac
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
try:
from hashlib import sha1
except ImportError:
import sha
sha1 = sha.sha
User = get_user_model()
class ApiKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
key = models.CharField(u"Key", max_length=255)
date_insert = models.DateTimeField(u"Date insert", auto_now_add=True)
def __unicode__(self):
return u"{} for {}".format(self.key, self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(ApiKey, self).save(*args, **kwargs)
def generate_key(self):
new_uuid = uuid.uuid4()
return hmac.new(new_uuid.bytes, digestmod=sha1).hexdigest()
def create_api_key(sender, **kwargs):
if kwargs.get('created') is True:
ApiKey.objects.create(user=kwargs.get('instance'))
models.signals.post_save.connect(create_api_key, User)
|
9e77d9a40ae13cff09051c9975361dca9259b426
|
gala/__init__.py
|
gala/__init__.py
|
"""
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <jni@janelia.hhmi.org>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.3dev'
|
"""
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <juan.n@unimelb.edu.au>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.3dev'
|
Update email in module init
|
Update email in module init
|
Python
|
bsd-3-clause
|
jni/gala,janelia-flyem/gala
|
"""
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <jni@janelia.hhmi.org>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.3dev'
Update email in module init
|
"""
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <juan.n@unimelb.edu.au>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.3dev'
|
<commit_before>"""
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <jni@janelia.hhmi.org>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.3dev'
<commit_msg>Update email in module init<commit_after>
|
"""
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <juan.n@unimelb.edu.au>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.3dev'
|
"""
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <jni@janelia.hhmi.org>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.3dev'
Update email in module init"""
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <juan.n@unimelb.edu.au>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.3dev'
|
<commit_before>"""
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <jni@janelia.hhmi.org>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.3dev'
<commit_msg>Update email in module init<commit_after>"""
Gala
===
Gala is a Python package for nD image segmentation.
"""
from __future__ import absolute_import
import sys, logging
if sys.version_info[:2] < (2,6):
logging.warning('Gala has not been tested on Python versions prior to 2.6'+
' (%d.%d detected).'%sys.version_info[:2])
__author__ = 'Juan Nunez-Iglesias <juan.n@unimelb.edu.au>, '+\
'Ryan Kennedy <kenry@cis.upenn.edu>'
del sys, logging
__all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify',
'stack_np', 'app_logger', 'option_manager', 'features', 'filter']
__version__ = '0.3dev'
|
b4d43bfbcc03b93826c194fb98a52b411dc6304b
|
turbustat/tests/test_wrapper.py
|
turbustat/tests/test_wrapper.py
|
# Licensed under an MIT open source license - see LICENSE
from ..statistics import stats_wrapper
from ._testing_data import \
dataset1, dataset2
def test_wrapper():
run_wrapper = stats_wrapper(dataset1, dataset2)
|
# Licensed under an MIT open source license - see LICENSE
import pytest
import numpy as np
from ..statistics import stats_wrapper, statistics_list
from ._testing_data import \
dataset1, dataset2
spacers = np.arange(2, len(statistics_list) + 1, 2)
# Split these into smaller tests to avoid timeout errors on Travis
@pytest.mark.parametrize(('stats'),
[statistics_list[i - 2:i] for i in
spacers])
def test_wrapper(stats):
stats_wrapper(dataset1, dataset2,
statistics=stats)
|
Split wrapper tests into smaller chunks
|
Split wrapper tests into smaller chunks
|
Python
|
mit
|
Astroua/TurbuStat,e-koch/TurbuStat
|
# Licensed under an MIT open source license - see LICENSE
from ..statistics import stats_wrapper
from ._testing_data import \
dataset1, dataset2
def test_wrapper():
run_wrapper = stats_wrapper(dataset1, dataset2)
Split wrapper tests into smaller chunks
|
# Licensed under an MIT open source license - see LICENSE
import pytest
import numpy as np
from ..statistics import stats_wrapper, statistics_list
from ._testing_data import \
dataset1, dataset2
spacers = np.arange(2, len(statistics_list) + 1, 2)
# Split these into smaller tests to avoid timeout errors on Travis
@pytest.mark.parametrize(('stats'),
[statistics_list[i - 2:i] for i in
spacers])
def test_wrapper(stats):
stats_wrapper(dataset1, dataset2,
statistics=stats)
|
<commit_before># Licensed under an MIT open source license - see LICENSE
from ..statistics import stats_wrapper
from ._testing_data import \
dataset1, dataset2
def test_wrapper():
run_wrapper = stats_wrapper(dataset1, dataset2)
<commit_msg>Split wrapper tests into smaller chunks<commit_after>
|
# Licensed under an MIT open source license - see LICENSE
import pytest
import numpy as np
from ..statistics import stats_wrapper, statistics_list
from ._testing_data import \
dataset1, dataset2
spacers = np.arange(2, len(statistics_list) + 1, 2)
# Split these into smaller tests to avoid timeout errors on Travis
@pytest.mark.parametrize(('stats'),
[statistics_list[i - 2:i] for i in
spacers])
def test_wrapper(stats):
stats_wrapper(dataset1, dataset2,
statistics=stats)
|
# Licensed under an MIT open source license - see LICENSE
from ..statistics import stats_wrapper
from ._testing_data import \
dataset1, dataset2
def test_wrapper():
run_wrapper = stats_wrapper(dataset1, dataset2)
Split wrapper tests into smaller chunks# Licensed under an MIT open source license - see LICENSE
import pytest
import numpy as np
from ..statistics import stats_wrapper, statistics_list
from ._testing_data import \
dataset1, dataset2
spacers = np.arange(2, len(statistics_list) + 1, 2)
# Split these into smaller tests to avoid timeout errors on Travis
@pytest.mark.parametrize(('stats'),
[statistics_list[i - 2:i] for i in
spacers])
def test_wrapper(stats):
stats_wrapper(dataset1, dataset2,
statistics=stats)
|
<commit_before># Licensed under an MIT open source license - see LICENSE
from ..statistics import stats_wrapper
from ._testing_data import \
dataset1, dataset2
def test_wrapper():
run_wrapper = stats_wrapper(dataset1, dataset2)
<commit_msg>Split wrapper tests into smaller chunks<commit_after># Licensed under an MIT open source license - see LICENSE
import pytest
import numpy as np
from ..statistics import stats_wrapper, statistics_list
from ._testing_data import \
dataset1, dataset2
spacers = np.arange(2, len(statistics_list) + 1, 2)
# Split these into smaller tests to avoid timeout errors on Travis
@pytest.mark.parametrize(('stats'),
[statistics_list[i - 2:i] for i in
spacers])
def test_wrapper(stats):
stats_wrapper(dataset1, dataset2,
statistics=stats)
|
f798066d20116d2cfd35cae0bf0771799677f6c2
|
py509/bin/verify.py
|
py509/bin/verify.py
|
#!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
trust_store = []
with open(certifi.where()) as fh:
#with open('/Users/sholsapp/workspace/py509/test.pem') as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
|
#!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--ca', required=False, default=certifi.where())
args = parser.parse_args()
trust_store = []
with open(args.ca) as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
|
Allow --ca parameter to specify trust store
|
Allow --ca parameter to specify trust store
|
Python
|
apache-2.0
|
sholsapp/py509
|
#!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
trust_store = []
with open(certifi.where()) as fh:
#with open('/Users/sholsapp/workspace/py509/test.pem') as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
Allow --ca parameter to specify trust store
|
#!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--ca', required=False, default=certifi.where())
args = parser.parse_args()
trust_store = []
with open(args.ca) as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
|
<commit_before>#!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
trust_store = []
with open(certifi.where()) as fh:
#with open('/Users/sholsapp/workspace/py509/test.pem') as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
<commit_msg>Allow --ca parameter to specify trust store<commit_after>
|
#!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--ca', required=False, default=certifi.where())
args = parser.parse_args()
trust_store = []
with open(args.ca) as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
|
#!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
trust_store = []
with open(certifi.where()) as fh:
#with open('/Users/sholsapp/workspace/py509/test.pem') as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
Allow --ca parameter to specify trust store#!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--ca', required=False, default=certifi.where())
args = parser.parse_args()
trust_store = []
with open(args.ca) as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
|
<commit_before>#!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
trust_store = []
with open(certifi.where()) as fh:
#with open('/Users/sholsapp/workspace/py509/test.pem') as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
<commit_msg>Allow --ca parameter to specify trust store<commit_after>#!/usr/bin/env python
"""Verify a certificate."""
import argparse
import logging
import sys
import certifi
from OpenSSL import crypto
from py509.x509 import load_x509_certificates
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--ca', required=False, default=certifi.where())
args = parser.parse_args()
trust_store = []
with open(args.ca) as fh:
trust_store = list(load_x509_certificates(fh.read()))
x509store = crypto.X509Store()
for ca in trust_store:
print ca.get_subject()
x509store.add_cert(ca)
x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, sys.stdin.read())
try:
crypto.X509StoreContext(x509store, x509cert).verify_certificate()
print 'Success'
except crypto.X509StoreContextError as e:
print 'Failed on {0}'.format(e.certificate.get_subject())
print 'Issuer {0}'.format(e.certificate.get_issuer())
print 'Message: {0}'.format(e)
|
3131f282d6ad1a703939c91c0d7dc0b3e4e54046
|
iati/versions.py
|
iati/versions.py
|
"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number."""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
|
"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number.
Args:
version_string (str): A string representation of an IATI version number.
Raises:
TypeError: If an attempt to pass something that is not a string is made.
ValueError: If a provided string is not a version number.
"""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
|
Document the current state of the Version class.
|
Document the current state of the Version class.
|
Python
|
mit
|
IATI/iati.core,IATI/iati.core
|
"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number."""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
Document the current state of the Version class.
|
"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number.
Args:
version_string (str): A string representation of an IATI version number.
Raises:
TypeError: If an attempt to pass something that is not a string is made.
ValueError: If a provided string is not a version number.
"""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
|
<commit_before>"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number."""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
<commit_msg>Document the current state of the Version class.<commit_after>
|
"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number.
Args:
version_string (str): A string representation of an IATI version number.
Raises:
TypeError: If an attempt to pass something that is not a string is made.
ValueError: If a provided string is not a version number.
"""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
|
"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number."""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
Document the current state of the Version class."""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number.
Args:
version_string (str): A string representation of an IATI version number.
Raises:
TypeError: If an attempt to pass something that is not a string is made.
ValueError: If a provided string is not a version number.
"""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
|
<commit_before>"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number."""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
<commit_msg>Document the current state of the Version class.<commit_after>"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants
class Version(object):
"""Representation of an IATI Standard Version Number."""
def __init__(self, version_string):
"""Initialise a Version Number.
Args:
version_string (str): A string representation of an IATI version number.
Raises:
TypeError: If an attempt to pass something that is not a string is made.
ValueError: If a provided string is not a version number.
"""
if not isinstance(version_string, str):
raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))
if not version_string in iati.constants.STANDARD_VERSIONS:
raise ValueError('A valid version number must be specified.')
|
ff336e34ab2996c0e01378945b10e4f3bc870a2e
|
simplekv/_compat.py
|
simplekv/_compat.py
|
# -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY3 = sys.version_info[0] == 3
if PY3:
import configparser as ConfigParser
else:
import ConfigParser
if PY3:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if PY3:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if PY3:
imap = map
else:
from itertools import imap
xrange = range if PY3 else xrange
|
# -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
import configparser as ConfigParser
else:
import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
else:
from itertools import imap
xrange = range if not PY2 else xrange
|
Use PY2 check instead of PY3 check.
|
Use PY2 check instead of PY3 check.
See http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ for
details.
|
Python
|
mit
|
fmarczin/simplekv,fmarczin/simplekv,karteek/simplekv,mbr/simplekv,karteek/simplekv,mbr/simplekv
|
# -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY3 = sys.version_info[0] == 3
if PY3:
import configparser as ConfigParser
else:
import ConfigParser
if PY3:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if PY3:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if PY3:
imap = map
else:
from itertools import imap
xrange = range if PY3 else xrange
Use PY2 check instead of PY3 check.
See http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ for
details.
|
# -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
import configparser as ConfigParser
else:
import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
else:
from itertools import imap
xrange = range if not PY2 else xrange
|
<commit_before># -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY3 = sys.version_info[0] == 3
if PY3:
import configparser as ConfigParser
else:
import ConfigParser
if PY3:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if PY3:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if PY3:
imap = map
else:
from itertools import imap
xrange = range if PY3 else xrange
<commit_msg>Use PY2 check instead of PY3 check.
See http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ for
details.<commit_after>
|
# -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
import configparser as ConfigParser
else:
import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
else:
from itertools import imap
xrange = range if not PY2 else xrange
|
# -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY3 = sys.version_info[0] == 3
if PY3:
import configparser as ConfigParser
else:
import ConfigParser
if PY3:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if PY3:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if PY3:
imap = map
else:
from itertools import imap
xrange = range if PY3 else xrange
Use PY2 check instead of PY3 check.
See http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ for
details.# -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
import configparser as ConfigParser
else:
import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
else:
from itertools import imap
xrange = range if not PY2 else xrange
|
<commit_before># -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY3 = sys.version_info[0] == 3
if PY3:
import configparser as ConfigParser
else:
import ConfigParser
if PY3:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if PY3:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if PY3:
imap = map
else:
from itertools import imap
xrange = range if PY3 else xrange
<commit_msg>Use PY2 check instead of PY3 check.
See http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ for
details.<commit_after># -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
import configparser as ConfigParser
else:
import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
else:
from itertools import imap
xrange = range if not PY2 else xrange
|
eeb284b86e4f6bf535afe0bb7bb009344ff7ec0f
|
simplekv/_compat.py
|
simplekv/_compat.py
|
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unquote_plus
else:
from urllib import quote as url_quote
from urllib import unquote as url_unquote
from urllib import quote_plus, unquote_plus
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
ifilter = filter
else:
from itertools import imap
from itertools import ifilter
if not PY2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
if not PY2:
import pickle
import copyreg
else:
try:
import cPickle as pickle
import copy_reg as copyreg
except ImportError:
import pickle
xrange = range if not PY2 else xrange
if not PY2:
text_type = str
unichr = chr
binary_type = bytes
else:
text_type = unicode
unichr = unichr
binary_type = str
|
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unquote_plus
else:
from urllib import quote as url_quote
from urllib import unquote as url_unquote
from urllib import quote_plus, unquote_plus
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
ifilter = filter
else:
from itertools import imap
from itertools import ifilter
if not PY2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
if not PY2:
import pickle
import copyreg
else:
try:
import cPickle as pickle
import copy_reg as copyreg
except ImportError:
import pickle
xrange = range if not PY2 else xrange
if not PY2:
text_type = str
unichr = chr
binary_type = bytes
else:
text_type = basestring
unichr = unichr
binary_type = str
|
Use basestring to check for key validity in Python 2
|
Use basestring to check for key validity in Python 2
|
Python
|
mit
|
karteek/simplekv,karteek/simplekv
|
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unquote_plus
else:
from urllib import quote as url_quote
from urllib import unquote as url_unquote
from urllib import quote_plus, unquote_plus
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
ifilter = filter
else:
from itertools import imap
from itertools import ifilter
if not PY2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
if not PY2:
import pickle
import copyreg
else:
try:
import cPickle as pickle
import copy_reg as copyreg
except ImportError:
import pickle
xrange = range if not PY2 else xrange
if not PY2:
text_type = str
unichr = chr
binary_type = bytes
else:
text_type = unicode
unichr = unichr
binary_type = str
Use basestring to check for key validity in Python 2
|
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unquote_plus
else:
from urllib import quote as url_quote
from urllib import unquote as url_unquote
from urllib import quote_plus, unquote_plus
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
ifilter = filter
else:
from itertools import imap
from itertools import ifilter
if not PY2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
if not PY2:
import pickle
import copyreg
else:
try:
import cPickle as pickle
import copy_reg as copyreg
except ImportError:
import pickle
xrange = range if not PY2 else xrange
if not PY2:
text_type = str
unichr = chr
binary_type = bytes
else:
text_type = basestring
unichr = unichr
binary_type = str
|
<commit_before>"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unquote_plus
else:
from urllib import quote as url_quote
from urllib import unquote as url_unquote
from urllib import quote_plus, unquote_plus
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
ifilter = filter
else:
from itertools import imap
from itertools import ifilter
if not PY2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
if not PY2:
import pickle
import copyreg
else:
try:
import cPickle as pickle
import copy_reg as copyreg
except ImportError:
import pickle
xrange = range if not PY2 else xrange
if not PY2:
text_type = str
unichr = chr
binary_type = bytes
else:
text_type = unicode
unichr = unichr
binary_type = str
<commit_msg>Use basestring to check for key validity in Python 2<commit_after>
|
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unquote_plus
else:
from urllib import quote as url_quote
from urllib import unquote as url_unquote
from urllib import quote_plus, unquote_plus
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
ifilter = filter
else:
from itertools import imap
from itertools import ifilter
if not PY2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
if not PY2:
import pickle
import copyreg
else:
try:
import cPickle as pickle
import copy_reg as copyreg
except ImportError:
import pickle
xrange = range if not PY2 else xrange
if not PY2:
text_type = str
unichr = chr
binary_type = bytes
else:
text_type = basestring
unichr = unichr
binary_type = str
|
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unquote_plus
else:
from urllib import quote as url_quote
from urllib import unquote as url_unquote
from urllib import quote_plus, unquote_plus
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
ifilter = filter
else:
from itertools import imap
from itertools import ifilter
if not PY2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
if not PY2:
import pickle
import copyreg
else:
try:
import cPickle as pickle
import copy_reg as copyreg
except ImportError:
import pickle
xrange = range if not PY2 else xrange
if not PY2:
text_type = str
unichr = chr
binary_type = bytes
else:
text_type = unicode
unichr = unichr
binary_type = str
Use basestring to check for key validity in Python 2"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unquote_plus
else:
from urllib import quote as url_quote
from urllib import unquote as url_unquote
from urllib import quote_plus, unquote_plus
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
ifilter = filter
else:
from itertools import imap
from itertools import ifilter
if not PY2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
if not PY2:
import pickle
import copyreg
else:
try:
import cPickle as pickle
import copy_reg as copyreg
except ImportError:
import pickle
xrange = range if not PY2 else xrange
if not PY2:
text_type = str
unichr = chr
binary_type = bytes
else:
text_type = basestring
unichr = unichr
binary_type = str
|
<commit_before>"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unquote_plus
else:
from urllib import quote as url_quote
from urllib import unquote as url_unquote
from urllib import quote_plus, unquote_plus
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
ifilter = filter
else:
from itertools import imap
from itertools import ifilter
if not PY2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
if not PY2:
import pickle
import copyreg
else:
try:
import cPickle as pickle
import copy_reg as copyreg
except ImportError:
import pickle
xrange = range if not PY2 else xrange
if not PY2:
text_type = str
unichr = chr
binary_type = bytes
else:
text_type = unicode
unichr = unichr
binary_type = str
<commit_msg>Use basestring to check for key validity in Python 2<commit_after>"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unquote_plus
else:
from urllib import quote as url_quote
from urllib import unquote as url_unquote
from urllib import quote_plus, unquote_plus
if not PY2:
from urllib.parse import urlparse
else:
from urlparse import urlparse
if not PY2:
imap = map
ifilter = filter
else:
from itertools import imap
from itertools import ifilter
if not PY2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
if not PY2:
import pickle
import copyreg
else:
try:
import cPickle as pickle
import copy_reg as copyreg
except ImportError:
import pickle
xrange = range if not PY2 else xrange
if not PY2:
text_type = str
unichr = chr
binary_type = bytes
else:
text_type = basestring
unichr = unichr
binary_type = str
|
a96ed550bd0c67b7a9ec0b9f636f71c530441e5f
|
graphene/types/abstracttype.py
|
graphene/types/abstracttype.py
|
from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation
class AbstractType(SubclassWithMeta):
def __init_subclass__(cls, *args, **kwargs):
warn_deprecation(
"Abstract type is deprecated, please use normal object inheritance instead.\n"
"See more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#deprecations"
)
super(AbstractType, cls).__init_subclass__(*args, **kwargs)
|
from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation
class AbstractType(SubclassWithMeta):
def __init_subclass__(cls, *args, **kwargs):
warn_deprecation(
"Abstract type is deprecated, please use normal object inheritance instead.\n"
"See more: https://github.com/graphql-python/graphene/blob/master/UPGRADE-v2.0.md#deprecations"
)
super(AbstractType, cls).__init_subclass__(*args, **kwargs)
|
Fix deprecations url in DeprecationWarning message.
|
Fix deprecations url in DeprecationWarning message.
|
Python
|
mit
|
graphql-python/graphene,graphql-python/graphene
|
from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation
class AbstractType(SubclassWithMeta):
def __init_subclass__(cls, *args, **kwargs):
warn_deprecation(
"Abstract type is deprecated, please use normal object inheritance instead.\n"
"See more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#deprecations"
)
super(AbstractType, cls).__init_subclass__(*args, **kwargs)
Fix deprecations url in DeprecationWarning message.
|
from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation
class AbstractType(SubclassWithMeta):
def __init_subclass__(cls, *args, **kwargs):
warn_deprecation(
"Abstract type is deprecated, please use normal object inheritance instead.\n"
"See more: https://github.com/graphql-python/graphene/blob/master/UPGRADE-v2.0.md#deprecations"
)
super(AbstractType, cls).__init_subclass__(*args, **kwargs)
|
<commit_before>from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation
class AbstractType(SubclassWithMeta):
def __init_subclass__(cls, *args, **kwargs):
warn_deprecation(
"Abstract type is deprecated, please use normal object inheritance instead.\n"
"See more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#deprecations"
)
super(AbstractType, cls).__init_subclass__(*args, **kwargs)
<commit_msg>Fix deprecations url in DeprecationWarning message.<commit_after>
|
from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation
class AbstractType(SubclassWithMeta):
def __init_subclass__(cls, *args, **kwargs):
warn_deprecation(
"Abstract type is deprecated, please use normal object inheritance instead.\n"
"See more: https://github.com/graphql-python/graphene/blob/master/UPGRADE-v2.0.md#deprecations"
)
super(AbstractType, cls).__init_subclass__(*args, **kwargs)
|
from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation
class AbstractType(SubclassWithMeta):
def __init_subclass__(cls, *args, **kwargs):
warn_deprecation(
"Abstract type is deprecated, please use normal object inheritance instead.\n"
"See more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#deprecations"
)
super(AbstractType, cls).__init_subclass__(*args, **kwargs)
Fix deprecations url in DeprecationWarning message.from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation
class AbstractType(SubclassWithMeta):
def __init_subclass__(cls, *args, **kwargs):
warn_deprecation(
"Abstract type is deprecated, please use normal object inheritance instead.\n"
"See more: https://github.com/graphql-python/graphene/blob/master/UPGRADE-v2.0.md#deprecations"
)
super(AbstractType, cls).__init_subclass__(*args, **kwargs)
|
<commit_before>from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation
class AbstractType(SubclassWithMeta):
def __init_subclass__(cls, *args, **kwargs):
warn_deprecation(
"Abstract type is deprecated, please use normal object inheritance instead.\n"
"See more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#deprecations"
)
super(AbstractType, cls).__init_subclass__(*args, **kwargs)
<commit_msg>Fix deprecations url in DeprecationWarning message.<commit_after>from ..utils.subclass_with_meta import SubclassWithMeta
from ..utils.deprecated import warn_deprecation
class AbstractType(SubclassWithMeta):
def __init_subclass__(cls, *args, **kwargs):
warn_deprecation(
"Abstract type is deprecated, please use normal object inheritance instead.\n"
"See more: https://github.com/graphql-python/graphene/blob/master/UPGRADE-v2.0.md#deprecations"
)
super(AbstractType, cls).__init_subclass__(*args, **kwargs)
|
ec176eaf054a9bad83573cc8942b9de402e02143
|
syncplayServer.py
|
syncplayServer.py
|
#coding:utf8
from twisted.internet import reactor
from syncplay.server import SyncFactory
from syncplay.ui.ConfigurationGetter import ServerConfigurationGetter
argsGetter = ServerConfigurationGetter()
args = argsGetter.getConfiguration()
reactor.listenTCP(args.port, SyncFactory(args.password, args.isolate_rooms))
reactor.run()
|
#coding:utf8
from twisted.internet import reactor
from syncplay.server import SyncFactory
from syncplay.ui.ConfigurationGetter import ServerConfigurationGetter
argsGetter = ServerConfigurationGetter()
args = argsGetter.getConfiguration()
reactor.listenTCP(int(args.port), SyncFactory(args.password, args.isolate_rooms))
reactor.run()
|
Fix on choosing ports for server
|
Fix on choosing ports for server
|
Python
|
apache-2.0
|
NeverDecaf/syncplay,NeverDecaf/syncplay,alby128/syncplay,alby128/syncplay,Syncplay/syncplay,Syncplay/syncplay
|
#coding:utf8
from twisted.internet import reactor
from syncplay.server import SyncFactory
from syncplay.ui.ConfigurationGetter import ServerConfigurationGetter
argsGetter = ServerConfigurationGetter()
args = argsGetter.getConfiguration()
reactor.listenTCP(args.port, SyncFactory(args.password, args.isolate_rooms))
reactor.run()
Fix on choosing ports for server
|
#coding:utf8
from twisted.internet import reactor
from syncplay.server import SyncFactory
from syncplay.ui.ConfigurationGetter import ServerConfigurationGetter
argsGetter = ServerConfigurationGetter()
args = argsGetter.getConfiguration()
reactor.listenTCP(int(args.port), SyncFactory(args.password, args.isolate_rooms))
reactor.run()
|
<commit_before>#coding:utf8
from twisted.internet import reactor
from syncplay.server import SyncFactory
from syncplay.ui.ConfigurationGetter import ServerConfigurationGetter
argsGetter = ServerConfigurationGetter()
args = argsGetter.getConfiguration()
reactor.listenTCP(args.port, SyncFactory(args.password, args.isolate_rooms))
reactor.run()
<commit_msg>Fix on choosing ports for server<commit_after>
|
#coding:utf8
from twisted.internet import reactor
from syncplay.server import SyncFactory
from syncplay.ui.ConfigurationGetter import ServerConfigurationGetter
argsGetter = ServerConfigurationGetter()
args = argsGetter.getConfiguration()
reactor.listenTCP(int(args.port), SyncFactory(args.password, args.isolate_rooms))
reactor.run()
|
#coding:utf8
from twisted.internet import reactor
from syncplay.server import SyncFactory
from syncplay.ui.ConfigurationGetter import ServerConfigurationGetter
argsGetter = ServerConfigurationGetter()
args = argsGetter.getConfiguration()
reactor.listenTCP(args.port, SyncFactory(args.password, args.isolate_rooms))
reactor.run()
Fix on choosing ports for server#coding:utf8
from twisted.internet import reactor
from syncplay.server import SyncFactory
from syncplay.ui.ConfigurationGetter import ServerConfigurationGetter
argsGetter = ServerConfigurationGetter()
args = argsGetter.getConfiguration()
reactor.listenTCP(int(args.port), SyncFactory(args.password, args.isolate_rooms))
reactor.run()
|
<commit_before>#coding:utf8
from twisted.internet import reactor
from syncplay.server import SyncFactory
from syncplay.ui.ConfigurationGetter import ServerConfigurationGetter
argsGetter = ServerConfigurationGetter()
args = argsGetter.getConfiguration()
reactor.listenTCP(args.port, SyncFactory(args.password, args.isolate_rooms))
reactor.run()
<commit_msg>Fix on choosing ports for server<commit_after>#coding:utf8
from twisted.internet import reactor
from syncplay.server import SyncFactory
from syncplay.ui.ConfigurationGetter import ServerConfigurationGetter
argsGetter = ServerConfigurationGetter()
args = argsGetter.getConfiguration()
reactor.listenTCP(int(args.port), SyncFactory(args.password, args.isolate_rooms))
reactor.run()
|
6654c3741f314e6617d53de6468f739b4304c5eb
|
tequila/deploy.py
|
tequila/deploy.py
|
import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
check_call(
['ansible-playbook',
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
'%s/deploy.yml' % tequila_dir,
]
)
|
import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
options = [
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
]
if os.path.exists('.vaultpassword'):
options.extend(
['--vault-password-file', '.vaultpassword',
'-e', '@inventory/secrets/%s' % envname,
]
)
else:
print("WARNING: No .vaultpassword file found, will not use any secrets.")
command = ['ansible-playbook'] + options + ['%s/deploy.yml' % tequila_dir]
check_call(command)
|
Add support for encrypted secrets
|
Add support for encrypted secrets
|
Python
|
bsd-3-clause
|
caktus/tequila-django
|
import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
check_call(
['ansible-playbook',
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
'%s/deploy.yml' % tequila_dir,
]
)
Add support for encrypted secrets
|
import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
options = [
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
]
if os.path.exists('.vaultpassword'):
options.extend(
['--vault-password-file', '.vaultpassword',
'-e', '@inventory/secrets/%s' % envname,
]
)
else:
print("WARNING: No .vaultpassword file found, will not use any secrets.")
command = ['ansible-playbook'] + options + ['%s/deploy.yml' % tequila_dir]
check_call(command)
|
<commit_before>import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
check_call(
['ansible-playbook',
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
'%s/deploy.yml' % tequila_dir,
]
)
<commit_msg>Add support for encrypted secrets<commit_after>
|
import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
options = [
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
]
if os.path.exists('.vaultpassword'):
options.extend(
['--vault-password-file', '.vaultpassword',
'-e', '@inventory/secrets/%s' % envname,
]
)
else:
print("WARNING: No .vaultpassword file found, will not use any secrets.")
command = ['ansible-playbook'] + options + ['%s/deploy.yml' % tequila_dir]
check_call(command)
|
import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
check_call(
['ansible-playbook',
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
'%s/deploy.yml' % tequila_dir,
]
)
Add support for encrypted secretsimport argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
options = [
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
]
if os.path.exists('.vaultpassword'):
options.extend(
['--vault-password-file', '.vaultpassword',
'-e', '@inventory/secrets/%s' % envname,
]
)
else:
print("WARNING: No .vaultpassword file found, will not use any secrets.")
command = ['ansible-playbook'] + options + ['%s/deploy.yml' % tequila_dir]
check_call(command)
|
<commit_before>import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
check_call(
['ansible-playbook',
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
'%s/deploy.yml' % tequila_dir,
]
)
<commit_msg>Add support for encrypted secrets<commit_after>import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
options = [
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
]
if os.path.exists('.vaultpassword'):
options.extend(
['--vault-password-file', '.vaultpassword',
'-e', '@inventory/secrets/%s' % envname,
]
)
else:
print("WARNING: No .vaultpassword file found, will not use any secrets.")
command = ['ansible-playbook'] + options + ['%s/deploy.yml' % tequila_dir]
check_call(command)
|
666a21cb17e65b7c3d6911fa1916029cedfd55e4
|
timmy/env.py
|
timmy/env.py
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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.
project_name = 'timmy'
version = '1.14.0'
if __name__ == '__main__':
exit(0)
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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.
project_name = 'timmy'
version = '1.14.1'
if __name__ == '__main__':
exit(0)
|
Bump version to test Travis pip publishing
|
Bump version to test Travis pip publishing
|
Python
|
apache-2.0
|
adobdin/timmy,adobdin/timmy
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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.
project_name = 'timmy'
version = '1.14.0'
if __name__ == '__main__':
exit(0)
Bump version to test Travis pip publishing
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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.
project_name = 'timmy'
version = '1.14.1'
if __name__ == '__main__':
exit(0)
|
<commit_before>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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.
project_name = 'timmy'
version = '1.14.0'
if __name__ == '__main__':
exit(0)
<commit_msg>Bump version to test Travis pip publishing<commit_after>
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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.
project_name = 'timmy'
version = '1.14.1'
if __name__ == '__main__':
exit(0)
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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.
project_name = 'timmy'
version = '1.14.0'
if __name__ == '__main__':
exit(0)
Bump version to test Travis pip publishing#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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.
project_name = 'timmy'
version = '1.14.1'
if __name__ == '__main__':
exit(0)
|
<commit_before>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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.
project_name = 'timmy'
version = '1.14.0'
if __name__ == '__main__':
exit(0)
<commit_msg>Bump version to test Travis pip publishing<commit_after>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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.
project_name = 'timmy'
version = '1.14.1'
if __name__ == '__main__':
exit(0)
|
ea90ef7193aa779bf6286ef59dc42229ed23c953
|
csat/collectors/pygit/__init__.py
|
csat/collectors/pygit/__init__.py
|
from csat.acquisition import base
__version__ = '0.1.0'
class GitPythonCollector(base.FactoryBase):
name = 'Git + Python dependencies analyzer'
key = 'pygit'
version = __version__
def build_parser(self, base):
parser = super(GitPythonCollector, self).build_parser(base)
parser.add_argument('repo_path')
return parser
def build_collector(self, task_manager, logger, args):
from .collector import GitPythonCollector
return GitPythonCollector(task_manager, logger, args.repo_path)
git_python_collector = GitPythonCollector()
if __name__ == '__main__':
from csat.acquisition.runner import get_runner
get_runner(git_python_collector).run()
|
try:
import git
except ImportError:
import warnings
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('No git module found, the pygit collector will not be '
'available', ImportWarning)
git = None
from csat.acquisition import base
__version__ = '0.1.0'
class GitPythonCollector(base.FactoryBase):
name = 'Git + Python dependencies analyzer'
key = 'pygit'
version = __version__
def build_parser(self, base):
parser = super(GitPythonCollector, self).build_parser(base)
parser.add_argument('repo_path')
return parser
def build_collector(self, task_manager, logger, args):
from .collector import GitPythonCollector
repo = git.Repo(args.repo_path)
return GitPythonCollector(task_manager, logger, repo)
if git is not None:
git_python_collector = GitPythonCollector()
if __name__ == '__main__':
from csat.acquisition.runner import get_runner
get_runner(git_python_collector).run()
|
Disable collector and only produce a warning if the git module is not installed
|
Disable collector and only produce a warning if the git module is not installed
|
Python
|
mit
|
GaretJax/csat,GaretJax/csat,GaretJax/csat,GaretJax/csat
|
from csat.acquisition import base
__version__ = '0.1.0'
class GitPythonCollector(base.FactoryBase):
name = 'Git + Python dependencies analyzer'
key = 'pygit'
version = __version__
def build_parser(self, base):
parser = super(GitPythonCollector, self).build_parser(base)
parser.add_argument('repo_path')
return parser
def build_collector(self, task_manager, logger, args):
from .collector import GitPythonCollector
return GitPythonCollector(task_manager, logger, args.repo_path)
git_python_collector = GitPythonCollector()
if __name__ == '__main__':
from csat.acquisition.runner import get_runner
get_runner(git_python_collector).run()
Disable collector and only produce a warning if the git module is not installed
|
try:
import git
except ImportError:
import warnings
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('No git module found, the pygit collector will not be '
'available', ImportWarning)
git = None
from csat.acquisition import base
__version__ = '0.1.0'
class GitPythonCollector(base.FactoryBase):
name = 'Git + Python dependencies analyzer'
key = 'pygit'
version = __version__
def build_parser(self, base):
parser = super(GitPythonCollector, self).build_parser(base)
parser.add_argument('repo_path')
return parser
def build_collector(self, task_manager, logger, args):
from .collector import GitPythonCollector
repo = git.Repo(args.repo_path)
return GitPythonCollector(task_manager, logger, repo)
if git is not None:
git_python_collector = GitPythonCollector()
if __name__ == '__main__':
from csat.acquisition.runner import get_runner
get_runner(git_python_collector).run()
|
<commit_before>from csat.acquisition import base
__version__ = '0.1.0'
class GitPythonCollector(base.FactoryBase):
name = 'Git + Python dependencies analyzer'
key = 'pygit'
version = __version__
def build_parser(self, base):
parser = super(GitPythonCollector, self).build_parser(base)
parser.add_argument('repo_path')
return parser
def build_collector(self, task_manager, logger, args):
from .collector import GitPythonCollector
return GitPythonCollector(task_manager, logger, args.repo_path)
git_python_collector = GitPythonCollector()
if __name__ == '__main__':
from csat.acquisition.runner import get_runner
get_runner(git_python_collector).run()
<commit_msg>Disable collector and only produce a warning if the git module is not installed<commit_after>
|
try:
import git
except ImportError:
import warnings
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('No git module found, the pygit collector will not be '
'available', ImportWarning)
git = None
from csat.acquisition import base
__version__ = '0.1.0'
class GitPythonCollector(base.FactoryBase):
name = 'Git + Python dependencies analyzer'
key = 'pygit'
version = __version__
def build_parser(self, base):
parser = super(GitPythonCollector, self).build_parser(base)
parser.add_argument('repo_path')
return parser
def build_collector(self, task_manager, logger, args):
from .collector import GitPythonCollector
repo = git.Repo(args.repo_path)
return GitPythonCollector(task_manager, logger, repo)
if git is not None:
git_python_collector = GitPythonCollector()
if __name__ == '__main__':
from csat.acquisition.runner import get_runner
get_runner(git_python_collector).run()
|
from csat.acquisition import base
__version__ = '0.1.0'
class GitPythonCollector(base.FactoryBase):
name = 'Git + Python dependencies analyzer'
key = 'pygit'
version = __version__
def build_parser(self, base):
parser = super(GitPythonCollector, self).build_parser(base)
parser.add_argument('repo_path')
return parser
def build_collector(self, task_manager, logger, args):
from .collector import GitPythonCollector
return GitPythonCollector(task_manager, logger, args.repo_path)
git_python_collector = GitPythonCollector()
if __name__ == '__main__':
from csat.acquisition.runner import get_runner
get_runner(git_python_collector).run()
Disable collector and only produce a warning if the git module is not installedtry:
import git
except ImportError:
import warnings
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('No git module found, the pygit collector will not be '
'available', ImportWarning)
git = None
from csat.acquisition import base
__version__ = '0.1.0'
class GitPythonCollector(base.FactoryBase):
name = 'Git + Python dependencies analyzer'
key = 'pygit'
version = __version__
def build_parser(self, base):
parser = super(GitPythonCollector, self).build_parser(base)
parser.add_argument('repo_path')
return parser
def build_collector(self, task_manager, logger, args):
from .collector import GitPythonCollector
repo = git.Repo(args.repo_path)
return GitPythonCollector(task_manager, logger, repo)
if git is not None:
git_python_collector = GitPythonCollector()
if __name__ == '__main__':
from csat.acquisition.runner import get_runner
get_runner(git_python_collector).run()
|
<commit_before>from csat.acquisition import base
__version__ = '0.1.0'
class GitPythonCollector(base.FactoryBase):
name = 'Git + Python dependencies analyzer'
key = 'pygit'
version = __version__
def build_parser(self, base):
parser = super(GitPythonCollector, self).build_parser(base)
parser.add_argument('repo_path')
return parser
def build_collector(self, task_manager, logger, args):
from .collector import GitPythonCollector
return GitPythonCollector(task_manager, logger, args.repo_path)
git_python_collector = GitPythonCollector()
if __name__ == '__main__':
from csat.acquisition.runner import get_runner
get_runner(git_python_collector).run()
<commit_msg>Disable collector and only produce a warning if the git module is not installed<commit_after>try:
import git
except ImportError:
import warnings
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('No git module found, the pygit collector will not be '
'available', ImportWarning)
git = None
from csat.acquisition import base
__version__ = '0.1.0'
class GitPythonCollector(base.FactoryBase):
name = 'Git + Python dependencies analyzer'
key = 'pygit'
version = __version__
def build_parser(self, base):
parser = super(GitPythonCollector, self).build_parser(base)
parser.add_argument('repo_path')
return parser
def build_collector(self, task_manager, logger, args):
from .collector import GitPythonCollector
repo = git.Repo(args.repo_path)
return GitPythonCollector(task_manager, logger, repo)
if git is not None:
git_python_collector = GitPythonCollector()
if __name__ == '__main__':
from csat.acquisition.runner import get_runner
get_runner(git_python_collector).run()
|
4a2b7b775d65aa95f160e1b1f16b7101fbd1e949
|
jellyblog/models.py
|
jellyblog/models.py
|
from django.db import models
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class Document(models.Model):
document_id = models.AutoField(primary_key=True)
category_id = models.ForeignKey(Category)
document_title = models.CharField(max_length=100)
document_content = models.TextField()
document_time = models.DateTimeField()
|
import datetime
from django.db import models
from django.utils import timezone
class Category(models.Model):
def __str__(self):
return self.category_name
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class Document(models.Model):
def __str__(self):
return self.choice_text
document_id = models.AutoField(primary_key=True)
category = models.ForeignKey(Category)
document_title = models.CharField(max_length=100)
document_content = models.TextField()
document_time = models.DateTimeField()
|
Document 모델의 category 칼럼명 수정
|
Document 모델의 category 칼럼명 수정
|
Python
|
apache-2.0
|
kyunooh/JellyBlog,kyunooh/JellyBlog,kyunooh/JellyBlog
|
from django.db import models
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class Document(models.Model):
document_id = models.AutoField(primary_key=True)
category_id = models.ForeignKey(Category)
document_title = models.CharField(max_length=100)
document_content = models.TextField()
document_time = models.DateTimeField()Document 모델의 category 칼럼명 수정
|
import datetime
from django.db import models
from django.utils import timezone
class Category(models.Model):
def __str__(self):
return self.category_name
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class Document(models.Model):
def __str__(self):
return self.choice_text
document_id = models.AutoField(primary_key=True)
category = models.ForeignKey(Category)
document_title = models.CharField(max_length=100)
document_content = models.TextField()
document_time = models.DateTimeField()
|
<commit_before>from django.db import models
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class Document(models.Model):
document_id = models.AutoField(primary_key=True)
category_id = models.ForeignKey(Category)
document_title = models.CharField(max_length=100)
document_content = models.TextField()
document_time = models.DateTimeField()<commit_msg>Document 모델의 category 칼럼명 수정<commit_after>
|
import datetime
from django.db import models
from django.utils import timezone
class Category(models.Model):
def __str__(self):
return self.category_name
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class Document(models.Model):
def __str__(self):
return self.choice_text
document_id = models.AutoField(primary_key=True)
category = models.ForeignKey(Category)
document_title = models.CharField(max_length=100)
document_content = models.TextField()
document_time = models.DateTimeField()
|
from django.db import models
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class Document(models.Model):
document_id = models.AutoField(primary_key=True)
category_id = models.ForeignKey(Category)
document_title = models.CharField(max_length=100)
document_content = models.TextField()
document_time = models.DateTimeField()Document 모델의 category 칼럼명 수정import datetime
from django.db import models
from django.utils import timezone
class Category(models.Model):
def __str__(self):
return self.category_name
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class Document(models.Model):
def __str__(self):
return self.choice_text
document_id = models.AutoField(primary_key=True)
category = models.ForeignKey(Category)
document_title = models.CharField(max_length=100)
document_content = models.TextField()
document_time = models.DateTimeField()
|
<commit_before>from django.db import models
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class Document(models.Model):
document_id = models.AutoField(primary_key=True)
category_id = models.ForeignKey(Category)
document_title = models.CharField(max_length=100)
document_content = models.TextField()
document_time = models.DateTimeField()<commit_msg>Document 모델의 category 칼럼명 수정<commit_after>import datetime
from django.db import models
from django.utils import timezone
class Category(models.Model):
def __str__(self):
return self.category_name
category_id = models.AutoField(primary_key=True)
category_parent_id = models.IntegerField(null=True)
category_name = models.CharField(max_length=20)
class Document(models.Model):
def __str__(self):
return self.choice_text
document_id = models.AutoField(primary_key=True)
category = models.ForeignKey(Category)
document_title = models.CharField(max_length=100)
document_content = models.TextField()
document_time = models.DateTimeField()
|
98dce0d4c7eb62edb599aafeb97e2291c01e4dc8
|
tests/serial_0.py
|
tests/serial_0.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
return int(codecs.encode(hexVal, 'hex'), 16)
while True:
data = sensor.read(size=1)
if (data == b'\x55'):
print('Get the data !')
sensor.read(size=10)
break
print('trying', data)
try:
while True:
data = sensor.read(size=11)
if not len(data) == 11:
print('Byte error !')
break
if data[1] == b'\x50':
print(convert(data[7]))
# Angle Output.
if (data[1] == b'\x53'):
pass
'''
if data[1] == b'\x54':
x = convert(data[2:4])
y = convert(data[4:6])
z = convert(data[6:8])
# print("Magnetic output:{}, {}, {}".format(x, y, z))
#Angle
'''
# print("----", data[0], data[1])
except KeyboardInterrupt:
sensor.close()
print('Close the sensor !')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
return codecs.encode(hexVal, 'hex')
while True:
data = sensor.read(size=1)
if (data == b'\x55'):
print('Get the data !')
sensor.read(size=10)
break
print('trying', data)
try:
while True:
data = sensor.read(size=11)
if not len(data) == 11:
print('Byte error !')
break
if data[1] == b'\x50':
# print(convert(data[7]))
pass
# Angle Output.
if (data[1] == b'\x53'):
hexVal = []
for i in range(11):
hexVal.append(convert(data[i]))
print(hexVal)
except KeyboardInterrupt:
sensor.close()
print('Close the sensor !')
|
Complete the data print interface.
|
Complete the data print interface.
|
Python
|
mit
|
EchoFUN/raspi
|
#!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
return int(codecs.encode(hexVal, 'hex'), 16)
while True:
data = sensor.read(size=1)
if (data == b'\x55'):
print('Get the data !')
sensor.read(size=10)
break
print('trying', data)
try:
while True:
data = sensor.read(size=11)
if not len(data) == 11:
print('Byte error !')
break
if data[1] == b'\x50':
print(convert(data[7]))
# Angle Output.
if (data[1] == b'\x53'):
pass
'''
if data[1] == b'\x54':
x = convert(data[2:4])
y = convert(data[4:6])
z = convert(data[6:8])
# print("Magnetic output:{}, {}, {}".format(x, y, z))
#Angle
'''
# print("----", data[0], data[1])
except KeyboardInterrupt:
sensor.close()
print('Close the sensor !')Complete the data print interface.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
return codecs.encode(hexVal, 'hex')
while True:
data = sensor.read(size=1)
if (data == b'\x55'):
print('Get the data !')
sensor.read(size=10)
break
print('trying', data)
try:
while True:
data = sensor.read(size=11)
if not len(data) == 11:
print('Byte error !')
break
if data[1] == b'\x50':
# print(convert(data[7]))
pass
# Angle Output.
if (data[1] == b'\x53'):
hexVal = []
for i in range(11):
hexVal.append(convert(data[i]))
print(hexVal)
except KeyboardInterrupt:
sensor.close()
print('Close the sensor !')
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
return int(codecs.encode(hexVal, 'hex'), 16)
while True:
data = sensor.read(size=1)
if (data == b'\x55'):
print('Get the data !')
sensor.read(size=10)
break
print('trying', data)
try:
while True:
data = sensor.read(size=11)
if not len(data) == 11:
print('Byte error !')
break
if data[1] == b'\x50':
print(convert(data[7]))
# Angle Output.
if (data[1] == b'\x53'):
pass
'''
if data[1] == b'\x54':
x = convert(data[2:4])
y = convert(data[4:6])
z = convert(data[6:8])
# print("Magnetic output:{}, {}, {}".format(x, y, z))
#Angle
'''
# print("----", data[0], data[1])
except KeyboardInterrupt:
sensor.close()
print('Close the sensor !')<commit_msg>Complete the data print interface.<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
return codecs.encode(hexVal, 'hex')
while True:
data = sensor.read(size=1)
if (data == b'\x55'):
print('Get the data !')
sensor.read(size=10)
break
print('trying', data)
try:
while True:
data = sensor.read(size=11)
if not len(data) == 11:
print('Byte error !')
break
if data[1] == b'\x50':
# print(convert(data[7]))
pass
# Angle Output.
if (data[1] == b'\x53'):
hexVal = []
for i in range(11):
hexVal.append(convert(data[i]))
print(hexVal)
except KeyboardInterrupt:
sensor.close()
print('Close the sensor !')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
return int(codecs.encode(hexVal, 'hex'), 16)
while True:
data = sensor.read(size=1)
if (data == b'\x55'):
print('Get the data !')
sensor.read(size=10)
break
print('trying', data)
try:
while True:
data = sensor.read(size=11)
if not len(data) == 11:
print('Byte error !')
break
if data[1] == b'\x50':
print(convert(data[7]))
# Angle Output.
if (data[1] == b'\x53'):
pass
'''
if data[1] == b'\x54':
x = convert(data[2:4])
y = convert(data[4:6])
z = convert(data[6:8])
# print("Magnetic output:{}, {}, {}".format(x, y, z))
#Angle
'''
# print("----", data[0], data[1])
except KeyboardInterrupt:
sensor.close()
print('Close the sensor !')Complete the data print interface.#!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
return codecs.encode(hexVal, 'hex')
while True:
data = sensor.read(size=1)
if (data == b'\x55'):
print('Get the data !')
sensor.read(size=10)
break
print('trying', data)
try:
while True:
data = sensor.read(size=11)
if not len(data) == 11:
print('Byte error !')
break
if data[1] == b'\x50':
# print(convert(data[7]))
pass
# Angle Output.
if (data[1] == b'\x53'):
hexVal = []
for i in range(11):
hexVal.append(convert(data[i]))
print(hexVal)
except KeyboardInterrupt:
sensor.close()
print('Close the sensor !')
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
return int(codecs.encode(hexVal, 'hex'), 16)
while True:
data = sensor.read(size=1)
if (data == b'\x55'):
print('Get the data !')
sensor.read(size=10)
break
print('trying', data)
try:
while True:
data = sensor.read(size=11)
if not len(data) == 11:
print('Byte error !')
break
if data[1] == b'\x50':
print(convert(data[7]))
# Angle Output.
if (data[1] == b'\x53'):
pass
'''
if data[1] == b'\x54':
x = convert(data[2:4])
y = convert(data[4:6])
z = convert(data[6:8])
# print("Magnetic output:{}, {}, {}".format(x, y, z))
#Angle
'''
# print("----", data[0], data[1])
except KeyboardInterrupt:
sensor.close()
print('Close the sensor !')<commit_msg>Complete the data print interface.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*
#
# @author XU Kai(xukai.ken@gmail.com)
# @date 2016-12-04 星期日
#
#
# #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息
#
#
#
import os
import sys
import math
import codecs
import serial
sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1)
def convert(hexVal):
return codecs.encode(hexVal, 'hex')
while True:
data = sensor.read(size=1)
if (data == b'\x55'):
print('Get the data !')
sensor.read(size=10)
break
print('trying', data)
try:
while True:
data = sensor.read(size=11)
if not len(data) == 11:
print('Byte error !')
break
if data[1] == b'\x50':
# print(convert(data[7]))
pass
# Angle Output.
if (data[1] == b'\x53'):
hexVal = []
for i in range(11):
hexVal.append(convert(data[i]))
print(hexVal)
except KeyboardInterrupt:
sensor.close()
print('Close the sensor !')
|
9753fe661ee59640363cd8e65c834204c1d4849c
|
ktbs_bench/utils/decorators.py
|
ktbs_bench/utils/decorators.py
|
from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res = [call_signature(f, *args, **kwargs),
timer.get_times()['real']] # TODO penser a quel temps garder
return res
return wrapped
def call_signature(f, *args, **kwargs):
"""Return a string representation of a function call"""
call_args = getcallargs(f, *args, **kwargs)
return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
@bench
def lala(a, b, c="default c", d="default d"):
print("lala est appelee")
if __name__ == '__main__':
print(lala("cest a", "cest b", d="change d"))
|
from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res = {call_signature(f, *args, **kwargs): timer.get_times()['real']} # TODO penser a quel temps garder
return res
return wrapped
def call_signature(f, *args, **kwargs):
"""Return a string representation of a function call."""
call_args = getcallargs(f, *args, **kwargs)
return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
@bench
def lala(a, b, c="default c", d="default d"):
print("lala est appelee")
if __name__ == '__main__':
print(lala("cest a", "cest b", d="change d"))
|
Fix bench decorator to return a dict instead of a list
|
Fix bench decorator to return a dict instead of a list
|
Python
|
mit
|
ktbs/ktbs-bench,ktbs/ktbs-bench
|
from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res = [call_signature(f, *args, **kwargs),
timer.get_times()['real']] # TODO penser a quel temps garder
return res
return wrapped
def call_signature(f, *args, **kwargs):
"""Return a string representation of a function call"""
call_args = getcallargs(f, *args, **kwargs)
return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
@bench
def lala(a, b, c="default c", d="default d"):
print("lala est appelee")
if __name__ == '__main__':
print(lala("cest a", "cest b", d="change d"))
Fix bench decorator to return a dict instead of a list
|
from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res = {call_signature(f, *args, **kwargs): timer.get_times()['real']} # TODO penser a quel temps garder
return res
return wrapped
def call_signature(f, *args, **kwargs):
"""Return a string representation of a function call."""
call_args = getcallargs(f, *args, **kwargs)
return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
@bench
def lala(a, b, c="default c", d="default d"):
print("lala est appelee")
if __name__ == '__main__':
print(lala("cest a", "cest b", d="change d"))
|
<commit_before>from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res = [call_signature(f, *args, **kwargs),
timer.get_times()['real']] # TODO penser a quel temps garder
return res
return wrapped
def call_signature(f, *args, **kwargs):
"""Return a string representation of a function call"""
call_args = getcallargs(f, *args, **kwargs)
return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
@bench
def lala(a, b, c="default c", d="default d"):
print("lala est appelee")
if __name__ == '__main__':
print(lala("cest a", "cest b", d="change d"))
<commit_msg>Fix bench decorator to return a dict instead of a list<commit_after>
|
from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res = {call_signature(f, *args, **kwargs): timer.get_times()['real']} # TODO penser a quel temps garder
return res
return wrapped
def call_signature(f, *args, **kwargs):
"""Return a string representation of a function call."""
call_args = getcallargs(f, *args, **kwargs)
return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
@bench
def lala(a, b, c="default c", d="default d"):
print("lala est appelee")
if __name__ == '__main__':
print(lala("cest a", "cest b", d="change d"))
|
from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res = [call_signature(f, *args, **kwargs),
timer.get_times()['real']] # TODO penser a quel temps garder
return res
return wrapped
def call_signature(f, *args, **kwargs):
"""Return a string representation of a function call"""
call_args = getcallargs(f, *args, **kwargs)
return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
@bench
def lala(a, b, c="default c", d="default d"):
print("lala est appelee")
if __name__ == '__main__':
print(lala("cest a", "cest b", d="change d"))
Fix bench decorator to return a dict instead of a listfrom functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res = {call_signature(f, *args, **kwargs): timer.get_times()['real']} # TODO penser a quel temps garder
return res
return wrapped
def call_signature(f, *args, **kwargs):
"""Return a string representation of a function call."""
call_args = getcallargs(f, *args, **kwargs)
return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
@bench
def lala(a, b, c="default c", d="default d"):
print("lala est appelee")
if __name__ == '__main__':
print(lala("cest a", "cest b", d="change d"))
|
<commit_before>from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res = [call_signature(f, *args, **kwargs),
timer.get_times()['real']] # TODO penser a quel temps garder
return res
return wrapped
def call_signature(f, *args, **kwargs):
"""Return a string representation of a function call"""
call_args = getcallargs(f, *args, **kwargs)
return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
@bench
def lala(a, b, c="default c", d="default d"):
print("lala est appelee")
if __name__ == '__main__':
print(lala("cest a", "cest b", d="change d"))
<commit_msg>Fix bench decorator to return a dict instead of a list<commit_after>from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res = {call_signature(f, *args, **kwargs): timer.get_times()['real']} # TODO penser a quel temps garder
return res
return wrapped
def call_signature(f, *args, **kwargs):
"""Return a string representation of a function call."""
call_args = getcallargs(f, *args, **kwargs)
return ';'.join(["%s=%s" % (k, v) for k, v in call_args.items()])
@bench
def lala(a, b, c="default c", d="default d"):
print("lala est appelee")
if __name__ == '__main__':
print(lala("cest a", "cest b", d="change d"))
|
b344d63ad3ff7abff0772a744e951d5d5c8438f3
|
carepoint/models/address_mixin.py
|
carepoint/models/address_mixin.py
|
# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(Integer, primary_key=True)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(
Integer,
ForeignKey('csaddr.addr_id'),
primary_key=True,
)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
Add ForeignKey on addr_id in carepoint cph address model
|
Add ForeignKey on addr_id in carepoint cph address model
|
Python
|
mit
|
laslabs/Python-Carepoint
|
# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(Integer, primary_key=True)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
Add ForeignKey on addr_id in carepoint cph address model
|
# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(
Integer,
ForeignKey('csaddr.addr_id'),
primary_key=True,
)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
<commit_before># -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(Integer, primary_key=True)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
<commit_msg>Add ForeignKey on addr_id in carepoint cph address model<commit_after>
|
# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(
Integer,
ForeignKey('csaddr.addr_id'),
primary_key=True,
)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(Integer, primary_key=True)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
Add ForeignKey on addr_id in carepoint cph address model# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(
Integer,
ForeignKey('csaddr.addr_id'),
primary_key=True,
)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
<commit_before># -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(Integer, primary_key=True)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
<commit_msg>Add ForeignKey on addr_id in carepoint cph address model<commit_after># -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from sqlalchemy import (Column,
Integer,
DateTime,
ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(
Integer,
ForeignKey('csaddr.addr_id'),
primary_key=True,
)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
4a07f271db4d1aa0b375914093479b3157c4496b
|
scheduler/listen.py
|
scheduler/listen.py
|
import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if event.change.project == 'openstack/keystone':
if isinstance(event, events.CommentAddedEvent):
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
|
import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if isinstance(event, events.CommentAddedEvent):
if event.change.project == 'openstack/keystone':
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
if event.change.project == 'openstack/keystone':
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
|
Make is so we run performance against merged patches
|
Make is so we run performance against merged patches
|
Python
|
apache-2.0
|
lbragstad/keystone-performance,lbragstad/keystone-performance,lbragstad/keystone-performance
|
import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if event.change.project == 'openstack/keystone':
if isinstance(event, events.CommentAddedEvent):
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
Make is so we run performance against merged patches
|
import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if isinstance(event, events.CommentAddedEvent):
if event.change.project == 'openstack/keystone':
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
if event.change.project == 'openstack/keystone':
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
|
<commit_before>import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if event.change.project == 'openstack/keystone':
if isinstance(event, events.CommentAddedEvent):
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
<commit_msg>Make is so we run performance against merged patches<commit_after>
|
import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if isinstance(event, events.CommentAddedEvent):
if event.change.project == 'openstack/keystone':
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
if event.change.project == 'openstack/keystone':
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
|
import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if event.change.project == 'openstack/keystone':
if isinstance(event, events.CommentAddedEvent):
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
Make is so we run performance against merged patchesimport ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if isinstance(event, events.CommentAddedEvent):
if event.change.project == 'openstack/keystone':
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
if event.change.project == 'openstack/keystone':
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
|
<commit_before>import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if event.change.project == 'openstack/keystone':
if isinstance(event, events.CommentAddedEvent):
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
<commit_msg>Make is so we run performance against merged patches<commit_after>import ConfigParser
import json
import time
from pygerrit import client
from pygerrit import events
class Listener(object):
def __init__(self, gerrit_user):
self.gerrit_user = gerrit_user
def start_listening(self):
self.gerrit = client.GerritClient(
host='review.openstack.org',
username=self.gerrit_user,
port=29418
)
print self.gerrit.gerrit_version()
def write_event(self, event):
print event
path = '/tmp/perf/'
fname = (path + event.change.number + '-' +
event.patchset.number + '.json')
with open(fname, 'w') as f:
f.write(json.dumps(event.json))
def listen_for_events(self):
self.gerrit.start_event_stream()
while True:
event = self.gerrit.get_event()
if event:
if isinstance(event, events.CommentAddedEvent):
if event.change.project == 'openstack/keystone':
if 'check performance' in event.comment:
self.write_event(event)
if isinstance(event, events.ChangeMergedEvent):
if event.change.project == 'openstack/keystone':
self.write_event(event)
else:
time.sleep(1)
if __name__ == '__main__':
config_parser = ConfigParser.ConfigParser()
config_parser.read('performance.conf')
gerrit_user = config_parser.get('global', 'gerrit_user')
listener = Listener(gerrit_user)
listener.start_listening()
listener.listen_for_events()
|
3cd07d2e1ee88d131066878bc21d8046b665b587
|
indico/core/signals/category.py
|
indico/core/signals/category.py
|
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from blinker import Namespace
_signals = Namespace()
moved = _signals.signal('moved', """
Called when a category is moved into another category. The `sender` is
the category and the old parent category is passed in the `old_parent`
kwarg.
""")
created = _signals.signal('created', """
Called when a new category is created. The `sender` is the new category.
""")
updated = _signals.signal('created', """
Called when a category is modified. The `sender` is the updated category.
""")
deleted = _signals.signal('deleted', """
Called when a category is deleted. The `sender` is the category.
""")
|
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from blinker import Namespace
_signals = Namespace()
moved = _signals.signal('moved', """
Called when a category is moved into another category. The `sender` is
the category and the old parent category is passed in the `old_parent`
kwarg.
""")
created = _signals.signal('created', """
Called when a new category is created. The `sender` is the new category.
""")
updated = _signals.signal('updated', """
Called when a category is modified. The `sender` is the updated category.
""")
deleted = _signals.signal('deleted', """
Called when a category is deleted. The `sender` is the category.
""")
|
Fix typo in signal name
|
Fix typo in signal name
|
Python
|
mit
|
indico/indico,DirkHoffmann/indico,indico/indico,indico/indico,pferreir/indico,DirkHoffmann/indico,indico/indico,DirkHoffmann/indico,DirkHoffmann/indico,pferreir/indico,pferreir/indico,pferreir/indico,ThiefMaster/indico,ThiefMaster/indico,ThiefMaster/indico,ThiefMaster/indico
|
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from blinker import Namespace
_signals = Namespace()
moved = _signals.signal('moved', """
Called when a category is moved into another category. The `sender` is
the category and the old parent category is passed in the `old_parent`
kwarg.
""")
created = _signals.signal('created', """
Called when a new category is created. The `sender` is the new category.
""")
updated = _signals.signal('created', """
Called when a category is modified. The `sender` is the updated category.
""")
deleted = _signals.signal('deleted', """
Called when a category is deleted. The `sender` is the category.
""")
Fix typo in signal name
|
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from blinker import Namespace
_signals = Namespace()
moved = _signals.signal('moved', """
Called when a category is moved into another category. The `sender` is
the category and the old parent category is passed in the `old_parent`
kwarg.
""")
created = _signals.signal('created', """
Called when a new category is created. The `sender` is the new category.
""")
updated = _signals.signal('updated', """
Called when a category is modified. The `sender` is the updated category.
""")
deleted = _signals.signal('deleted', """
Called when a category is deleted. The `sender` is the category.
""")
|
<commit_before># This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from blinker import Namespace
_signals = Namespace()
moved = _signals.signal('moved', """
Called when a category is moved into another category. The `sender` is
the category and the old parent category is passed in the `old_parent`
kwarg.
""")
created = _signals.signal('created', """
Called when a new category is created. The `sender` is the new category.
""")
updated = _signals.signal('created', """
Called when a category is modified. The `sender` is the updated category.
""")
deleted = _signals.signal('deleted', """
Called when a category is deleted. The `sender` is the category.
""")
<commit_msg>Fix typo in signal name<commit_after>
|
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from blinker import Namespace
_signals = Namespace()
moved = _signals.signal('moved', """
Called when a category is moved into another category. The `sender` is
the category and the old parent category is passed in the `old_parent`
kwarg.
""")
created = _signals.signal('created', """
Called when a new category is created. The `sender` is the new category.
""")
updated = _signals.signal('updated', """
Called when a category is modified. The `sender` is the updated category.
""")
deleted = _signals.signal('deleted', """
Called when a category is deleted. The `sender` is the category.
""")
|
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from blinker import Namespace
_signals = Namespace()
moved = _signals.signal('moved', """
Called when a category is moved into another category. The `sender` is
the category and the old parent category is passed in the `old_parent`
kwarg.
""")
created = _signals.signal('created', """
Called when a new category is created. The `sender` is the new category.
""")
updated = _signals.signal('created', """
Called when a category is modified. The `sender` is the updated category.
""")
deleted = _signals.signal('deleted', """
Called when a category is deleted. The `sender` is the category.
""")
Fix typo in signal name# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from blinker import Namespace
_signals = Namespace()
moved = _signals.signal('moved', """
Called when a category is moved into another category. The `sender` is
the category and the old parent category is passed in the `old_parent`
kwarg.
""")
created = _signals.signal('created', """
Called when a new category is created. The `sender` is the new category.
""")
updated = _signals.signal('updated', """
Called when a category is modified. The `sender` is the updated category.
""")
deleted = _signals.signal('deleted', """
Called when a category is deleted. The `sender` is the category.
""")
|
<commit_before># This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from blinker import Namespace
_signals = Namespace()
moved = _signals.signal('moved', """
Called when a category is moved into another category. The `sender` is
the category and the old parent category is passed in the `old_parent`
kwarg.
""")
created = _signals.signal('created', """
Called when a new category is created. The `sender` is the new category.
""")
updated = _signals.signal('created', """
Called when a category is modified. The `sender` is the updated category.
""")
deleted = _signals.signal('deleted', """
Called when a category is deleted. The `sender` is the category.
""")
<commit_msg>Fix typo in signal name<commit_after># This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from blinker import Namespace
_signals = Namespace()
moved = _signals.signal('moved', """
Called when a category is moved into another category. The `sender` is
the category and the old parent category is passed in the `old_parent`
kwarg.
""")
created = _signals.signal('created', """
Called when a new category is created. The `sender` is the new category.
""")
updated = _signals.signal('updated', """
Called when a category is modified. The `sender` is the updated category.
""")
deleted = _signals.signal('deleted', """
Called when a category is deleted. The `sender` is the category.
""")
|
6959458a8de9d0536ae859fca2a7fa62bb4bf169
|
greatbigcrane/project/forms.py
|
greatbigcrane/project/forms.py
|
"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 django import forms
from project.models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
|
"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 django import forms
from project.models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
class DjangoRecipeForm(forms.Form):
settings = forms.CharField()
version = forms.CharField()
eggs = forms.CharField()
project = forms.CharField()
extra_paths = forms.CharField()
fcgi = forms.BooleanField()
wsgi = forms.BooleanField()
|
Add a crappy form that will hopefully inspire me to write something else. Tired of staring into space.
|
Add a crappy form that will hopefully inspire me to write something else. Tired of staring into space.
|
Python
|
apache-2.0
|
pnomolos/greatbigcrane,pnomolos/greatbigcrane
|
"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 django import forms
from project.models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
Add a crappy form that will hopefully inspire me to write something else. Tired of staring into space.
|
"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 django import forms
from project.models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
class DjangoRecipeForm(forms.Form):
settings = forms.CharField()
version = forms.CharField()
eggs = forms.CharField()
project = forms.CharField()
extra_paths = forms.CharField()
fcgi = forms.BooleanField()
wsgi = forms.BooleanField()
|
<commit_before>"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 django import forms
from project.models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
<commit_msg>Add a crappy form that will hopefully inspire me to write something else. Tired of staring into space.<commit_after>
|
"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 django import forms
from project.models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
class DjangoRecipeForm(forms.Form):
settings = forms.CharField()
version = forms.CharField()
eggs = forms.CharField()
project = forms.CharField()
extra_paths = forms.CharField()
fcgi = forms.BooleanField()
wsgi = forms.BooleanField()
|
"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 django import forms
from project.models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
Add a crappy form that will hopefully inspire me to write something else. Tired of staring into space."""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 django import forms
from project.models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
class DjangoRecipeForm(forms.Form):
settings = forms.CharField()
version = forms.CharField()
eggs = forms.CharField()
project = forms.CharField()
extra_paths = forms.CharField()
fcgi = forms.BooleanField()
wsgi = forms.BooleanField()
|
<commit_before>"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 django import forms
from project.models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
<commit_msg>Add a crappy form that will hopefully inspire me to write something else. Tired of staring into space.<commit_after>"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 django import forms
from project.models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
class DjangoRecipeForm(forms.Form):
settings = forms.CharField()
version = forms.CharField()
eggs = forms.CharField()
project = forms.CharField()
extra_paths = forms.CharField()
fcgi = forms.BooleanField()
wsgi = forms.BooleanField()
|
d565aa0b3fa3239c3ed699c9d37f30b910d15a05
|
lbrynet/__init__.py
|
lbrynet/__init__.py
|
import logging
__version__ = "0.21.0rc9"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
import logging
__version__ = "0.21.0rc10"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
Bump version 0.21.0rc9 --> 0.21.0rc10
|
Bump version 0.21.0rc9 --> 0.21.0rc10
Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>
|
Python
|
mit
|
lbryio/lbry,lbryio/lbry,lbryio/lbry
|
import logging
__version__ = "0.21.0rc9"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
Bump version 0.21.0rc9 --> 0.21.0rc10
Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>
|
import logging
__version__ = "0.21.0rc10"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
<commit_before>import logging
__version__ = "0.21.0rc9"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
<commit_msg>Bump version 0.21.0rc9 --> 0.21.0rc10
Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io><commit_after>
|
import logging
__version__ = "0.21.0rc10"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
import logging
__version__ = "0.21.0rc9"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
Bump version 0.21.0rc9 --> 0.21.0rc10
Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io>import logging
__version__ = "0.21.0rc10"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
<commit_before>import logging
__version__ = "0.21.0rc9"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
<commit_msg>Bump version 0.21.0rc9 --> 0.21.0rc10
Signed-off-by: Jack Robison <40884020c67726395ea162083a125620dc32cdab@lbry.io><commit_after>import logging
__version__ = "0.21.0rc10"
version = tuple(__version__.split('.'))
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
42320a1baa7b4e69170b881090e17a25080bf45c
|
lib/assemblers/none.py
|
lib/assemblers/none.py
|
"""Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = join(prefix, 'blast_only.fasta')
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
|
"""Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = '{}.fasta'.format(prefix)
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
|
Change file name for output for no assembler given
|
Change file name for output for no assembler given
|
Python
|
bsd-3-clause
|
juliema/aTRAM
|
"""Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = join(prefix, 'blast_only.fasta')
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
Change file name for output for no assembler given
|
"""Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = '{}.fasta'.format(prefix)
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
|
<commit_before>"""Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = join(prefix, 'blast_only.fasta')
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
<commit_msg>Change file name for output for no assembler given<commit_after>
|
"""Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = '{}.fasta'.format(prefix)
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
|
"""Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = join(prefix, 'blast_only.fasta')
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
Change file name for output for no assembler given"""Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = '{}.fasta'.format(prefix)
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
|
<commit_before>"""Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = join(prefix, 'blast_only.fasta')
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
<commit_msg>Change file name for output for no assembler given<commit_after>"""Null object for the assemblers."""
from os.path import join
import lib.db as db
from lib.assemblers.base import BaseAssembler
class NoneAssembler(BaseAssembler):
"""Null object for the assemblers."""
def __init__(self, args, db_conn):
"""Build the assembler."""
super().__init__(args, db_conn)
self.steps = []
self.blast_only = True # Used to short-circuit the assembler
def write_final_output(self, blast_db, query):
"""Output this file if we are not assembling the contigs."""
prefix = self.final_output_prefix(blast_db, query)
file_name = '{}.fasta'.format(prefix)
with open(file_name, 'w') as output_file:
for row in db.get_sra_blast_hits(self.state['db_conn'], 1):
output_file.write('>{}{}\n'.format(
row['seq_name'], row['seq_end']))
output_file.write('{}\n'.format(row['seq']))
|
daceec30fc422ea035163e80c826423a806d0b85
|
django/wwwhisper_auth/backend.py
|
django/wwwhisper_auth/backend.py
|
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if result is None:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if not result:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
Correct check if assertion verification failed.
|
Correct check if assertion verification failed.
|
Python
|
mit
|
wrr/wwwhisper,wrr/wwwhisper,wrr/wwwhisper,wrr/wwwhisper
|
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if result is None:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
Correct check if assertion verification failed.
|
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if not result:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
<commit_before>"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if result is None:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
<commit_msg>Correct check if assertion verification failed.<commit_after>
|
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if not result:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if result is None:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
Correct check if assertion verification failed."""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if not result:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
<commit_before>"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if result is None:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
<commit_msg>Correct check if assertion verification failed.<commit_after>"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if not result:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
aee0c96593343b3b1064d38579bec666bd51c9fa
|
python/atemctrl.py
|
python/atemctrl.py
|
# Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
time.sleep(0.05)
if argv[1] == 'program':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, !TBD!)
elif argv[1] != 'source':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 1)
else:
ATEM.runLoop()
if time.time() > time_set:
ATEM.setProgramInputVideoSource(0, int(argv[2]))
ATEM.setPreviewInputVideoSource(0, int(argv[2]))
run_cmd = 0
if __name__ == "__main__":
main(sys.argv[1:])
|
# Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
time.sleep(0.05)
if argv[1] == 'program':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 10010)
run_cmd = 0
elif argv[1] == 'source':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 1)
run_cmd = 0
else:
ATEM.runLoop()
if time.time() > time_set:
ATEM.setProgramInputVideoSource(0, int(argv[2]))
ATEM.setPreviewInputVideoSource(0, int(argv[2]))
run_cmd = 0
if __name__ == "__main__":
main(sys.argv[1:])
|
Fix script ending. Set value to show program in aux output.
|
Fix script ending. Set value to show program in aux output.
|
Python
|
mit
|
qrila/khvidcontrol,qrila/khvidcontrol
|
# Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
time.sleep(0.05)
if argv[1] == 'program':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, !TBD!)
elif argv[1] != 'source':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 1)
else:
ATEM.runLoop()
if time.time() > time_set:
ATEM.setProgramInputVideoSource(0, int(argv[2]))
ATEM.setPreviewInputVideoSource(0, int(argv[2]))
run_cmd = 0
if __name__ == "__main__":
main(sys.argv[1:])
Fix script ending. Set value to show program in aux output.
|
# Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
time.sleep(0.05)
if argv[1] == 'program':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 10010)
run_cmd = 0
elif argv[1] == 'source':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 1)
run_cmd = 0
else:
ATEM.runLoop()
if time.time() > time_set:
ATEM.setProgramInputVideoSource(0, int(argv[2]))
ATEM.setPreviewInputVideoSource(0, int(argv[2]))
run_cmd = 0
if __name__ == "__main__":
main(sys.argv[1:])
|
<commit_before># Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
time.sleep(0.05)
if argv[1] == 'program':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, !TBD!)
elif argv[1] != 'source':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 1)
else:
ATEM.runLoop()
if time.time() > time_set:
ATEM.setProgramInputVideoSource(0, int(argv[2]))
ATEM.setPreviewInputVideoSource(0, int(argv[2]))
run_cmd = 0
if __name__ == "__main__":
main(sys.argv[1:])
<commit_msg>Fix script ending. Set value to show program in aux output.<commit_after>
|
# Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
time.sleep(0.05)
if argv[1] == 'program':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 10010)
run_cmd = 0
elif argv[1] == 'source':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 1)
run_cmd = 0
else:
ATEM.runLoop()
if time.time() > time_set:
ATEM.setProgramInputVideoSource(0, int(argv[2]))
ATEM.setPreviewInputVideoSource(0, int(argv[2]))
run_cmd = 0
if __name__ == "__main__":
main(sys.argv[1:])
|
# Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
time.sleep(0.05)
if argv[1] == 'program':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, !TBD!)
elif argv[1] != 'source':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 1)
else:
ATEM.runLoop()
if time.time() > time_set:
ATEM.setProgramInputVideoSource(0, int(argv[2]))
ATEM.setPreviewInputVideoSource(0, int(argv[2]))
run_cmd = 0
if __name__ == "__main__":
main(sys.argv[1:])
Fix script ending. Set value to show program in aux output.# Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
time.sleep(0.05)
if argv[1] == 'program':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 10010)
run_cmd = 0
elif argv[1] == 'source':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 1)
run_cmd = 0
else:
ATEM.runLoop()
if time.time() > time_set:
ATEM.setProgramInputVideoSource(0, int(argv[2]))
ATEM.setPreviewInputVideoSource(0, int(argv[2]))
run_cmd = 0
if __name__ == "__main__":
main(sys.argv[1:])
|
<commit_before># Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
time.sleep(0.05)
if argv[1] == 'program':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, !TBD!)
elif argv[1] != 'source':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 1)
else:
ATEM.runLoop()
if time.time() > time_set:
ATEM.setProgramInputVideoSource(0, int(argv[2]))
ATEM.setPreviewInputVideoSource(0, int(argv[2]))
run_cmd = 0
if __name__ == "__main__":
main(sys.argv[1:])
<commit_msg>Fix script ending. Set value to show program in aux output.<commit_after># Input format:
# python atemctrl.py <ip> <program input> <preview input>
import sys
import time
import ATEM
def main(argv):
run_cmd = 1
atem_ip = argv[0].split(".")
ATEM.begin(int(atem_ip[0]), int(atem_ip[1]), int(atem_ip[2]), int(atem_ip[3]))
time_set = time.time() + 0.500
while run_cmd == 1:
time.sleep(0.05)
if argv[1] == 'program':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 10010)
run_cmd = 0
elif argv[1] == 'source':
ATEM.runLoop()
if time.time() > time_set:
ATEM.setAuxSourceInput(0, 1)
run_cmd = 0
else:
ATEM.runLoop()
if time.time() > time_set:
ATEM.setProgramInputVideoSource(0, int(argv[2]))
ATEM.setPreviewInputVideoSource(0, int(argv[2]))
run_cmd = 0
if __name__ == "__main__":
main(sys.argv[1:])
|
3c0d52aa0a936b3ae138ddfba66e7ba9dcc5f934
|
sympy/plotting/proxy_pyglet.py
|
sympy/plotting/proxy_pyglet.py
|
from warnings import warn
from sympy.core.compatibility import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
|
from warnings import warn
from sympy.utilities.exceptions import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
|
Change the import location of DeprecationWarning used by plotting module
|
Change the import location of DeprecationWarning used by plotting module
The SympyDeprecationWarning was moved from its original location. The change
was done in the master branch. The same change must be mirrored in this
development branch.
|
Python
|
bsd-3-clause
|
pbrady/sympy,grevutiu-gabriel/sympy,rahuldan/sympy,atsao72/sympy,kmacinnis/sympy,yashsharan/sympy,drufat/sympy,iamutkarshtiwari/sympy,shikil/sympy,atsao72/sympy,jaimahajan1997/sympy,meghana1995/sympy,jerli/sympy,oliverlee/sympy,ahhda/sympy,garvitr/sympy,sahmed95/sympy,abloomston/sympy,kaushik94/sympy,jbbskinny/sympy,cswiercz/sympy,postvakje/sympy,maniteja123/sympy,asm666/sympy,dqnykamp/sympy,jamesblunt/sympy,Curious72/sympy,diofant/diofant,Titan-C/sympy,kaushik94/sympy,saurabhjn76/sympy,amitjamadagni/sympy,atreyv/sympy,kevalds51/sympy,abloomston/sympy,saurabhjn76/sympy,sampadsaha5/sympy,abhiii5459/sympy,chaffra/sympy,MechCoder/sympy,MridulS/sympy,hargup/sympy,aktech/sympy,abhiii5459/sympy,vipulroxx/sympy,amitjamadagni/sympy,pandeyadarsh/sympy,Vishluck/sympy,sunny94/temp,emon10005/sympy,kaichogami/sympy,MridulS/sympy,AunShiLord/sympy,pbrady/sympy,Curious72/sympy,kevalds51/sympy,wyom/sympy,Davidjohnwilson/sympy,wanglongqi/sympy,jamesblunt/sympy,liangjiaxing/sympy,yashsharan/sympy,MechCoder/sympy,moble/sympy,atreyv/sympy,meghana1995/sympy,Arafatk/sympy,lindsayad/sympy,pbrady/sympy,aktech/sympy,mafiya69/sympy,jbbskinny/sympy,asm666/sympy,ga7g08/sympy,ga7g08/sympy,cswiercz/sympy,kevalds51/sympy,sahmed95/sympy,Sumith1896/sympy,souravsingh/sympy,skirpichev/omg,drufat/sympy,sunny94/temp,jerli/sympy,toolforger/sympy,mafiya69/sympy,cccfran/sympy,MridulS/sympy,chaffra/sympy,yukoba/sympy,AunShiLord/sympy,iamutkarshtiwari/sympy,ChristinaZografou/sympy,toolforger/sympy,lindsayad/sympy,farhaanbukhsh/sympy,debugger22/sympy,kumarkrishna/sympy,pandeyadarsh/sympy,ga7g08/sympy,hargup/sympy,saurabhjn76/sympy,atreyv/sympy,Curious72/sympy,lidavidm/sympy,ahhda/sympy,sahilshekhawat/sympy,dqnykamp/sympy,liangjiaxing/sympy,chaffra/sympy,kaushik94/sympy,MechCoder/sympy,Designist/sympy,jbbskinny/sympy,garvitr/sympy,madan96/sympy,beni55/sympy,VaibhavAgarwalVA/sympy,wanglongqi/sympy,skidzo/sympy,debugger22/sympy,cccfran/sympy,hargup/sympy,AkademieOlympia/sympy,VaibhavAgarwalVA/sympy,ahhda/sympy,postvakje/sympy,vipulroxx/sympy,dqnykamp/sympy,Sumith1896/sympy,bukzor/sympy,mafiya69/sympy,sunny94/temp,shikil/sympy,mcdaniel67/sympy,grevutiu-gabriel/sympy,Shaswat27/sympy,shikil/sympy,sampadsaha5/sympy,Davidjohnwilson/sympy,abloomston/sympy,skidzo/sympy,Shaswat27/sympy,Gadal/sympy,emon10005/sympy,lidavidm/sympy,hrashk/sympy,beni55/sympy,kumarkrishna/sympy,wyom/sympy,souravsingh/sympy,oliverlee/sympy,wanglongqi/sympy,sahilshekhawat/sympy,kmacinnis/sympy,bukzor/sympy,ChristinaZografou/sympy,aktech/sympy,maniteja123/sympy,moble/sympy,hrashk/sympy,cccfran/sympy,lindsayad/sympy,yukoba/sympy,emon10005/sympy,Titan-C/sympy,lidavidm/sympy,shipci/sympy,vipulroxx/sympy,bukzor/sympy,moble/sympy,yashsharan/sympy,Mitchkoens/sympy,madan96/sympy,Designist/sympy,toolforger/sympy,Gadal/sympy,Vishluck/sympy,Mitchkoens/sympy,meghana1995/sympy,ChristinaZografou/sympy,madan96/sympy,sahmed95/sympy,sampadsaha5/sympy,AunShiLord/sympy,srjoglekar246/sympy,cswiercz/sympy,rahuldan/sympy,skidzo/sympy,jaimahajan1997/sympy,kaichogami/sympy,flacjacket/sympy,jaimahajan1997/sympy,Shaswat27/sympy,abhiii5459/sympy,Mitchkoens/sympy,iamutkarshtiwari/sympy,kumarkrishna/sympy,AkademieOlympia/sympy,asm666/sympy,pandeyadarsh/sympy,postvakje/sympy,jerli/sympy,AkademieOlympia/sympy,shipci/sympy,Titan-C/sympy,shipci/sympy,farhaanbukhsh/sympy,atsao72/sympy,debugger22/sympy,kmacinnis/sympy,grevutiu-gabriel/sympy,yukoba/sympy,mcdaniel67/sympy,Arafatk/sympy,maniteja123/sympy,garvitr/sympy,sahilshekhawat/sympy,liangjiaxing/sympy,drufat/sympy,Davidjohnwilson/sympy,beni55/sympy,Designist/sympy,kaichogami/sympy,souravsingh/sympy,Vishluck/sympy,hrashk/sympy,farhaanbukhsh/sympy,oliverlee/sympy,wyom/sympy,rahuldan/sympy,jamesblunt/sympy,Sumith1896/sympy,Arafatk/sympy,VaibhavAgarwalVA/sympy,mcdaniel67/sympy,Gadal/sympy
|
from warnings import warn
from sympy.core.compatibility import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
Change the import location of DeprecationWarning used by plotting module
The SympyDeprecationWarning was moved from its original location. The change
was done in the master branch. The same change must be mirrored in this
development branch.
|
from warnings import warn
from sympy.utilities.exceptions import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
|
<commit_before>from warnings import warn
from sympy.core.compatibility import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
<commit_msg>Change the import location of DeprecationWarning used by plotting module
The SympyDeprecationWarning was moved from its original location. The change
was done in the master branch. The same change must be mirrored in this
development branch.<commit_after>
|
from warnings import warn
from sympy.utilities.exceptions import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
|
from warnings import warn
from sympy.core.compatibility import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
Change the import location of DeprecationWarning used by plotting module
The SympyDeprecationWarning was moved from its original location. The change
was done in the master branch. The same change must be mirrored in this
development branch.from warnings import warn
from sympy.utilities.exceptions import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
|
<commit_before>from warnings import warn
from sympy.core.compatibility import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
<commit_msg>Change the import location of DeprecationWarning used by plotting module
The SympyDeprecationWarning was moved from its original location. The change
was done in the master branch. The same change must be mirrored in this
development branch.<commit_after>from warnings import warn
from sympy.utilities.exceptions import SymPyDeprecationWarning
from pygletplot import PygletPlot
def Plot(*args, **kwargs):
""" A temporary proxy for an interface under deprecation.
This proxy is the one imported by `from sympy import *`.
The Plot class will change in future versions of sympy to use the new
plotting module. That new plotting module is already used by the
plot() function (lowercase). To write code compatible with future versions
of sympy use that function (plot() lowercase). Or if you want to use the
old plotting module just import it directly:
`from sympy.plotting.pygletplot import PygletPlot`
To use Plot from the new plotting module do:
`from sympy.plotting.plot import Plot`
In future version of sympy you will also be able to use
`from sympy.plotting import Plot` but in the current version this will
import this proxy object. It's done for backward compatibility.
The old plotting module is not deprecated. Only the location will
change. The new location is sympy.plotting.pygletplot.
"""
warn('This interface will change in future versions of sympy.'
' As a precatuion use the plot() function (lowercase).'
' See the docstring for details.',
SymPyDeprecationWarning)
return PygletPlot(*args, **kwargs)
|
e507abe78dee3ae4a4261d8bde645f3df7d8b842
|
tests/atest/run_tests.py
|
tests/atest/run_tests.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from robot import run_cli
run_cli(sys.argv[1:] + [os.path.dirname(__file__)])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from pathlib import Path
from robot import run_cli
if __name__ == '__main__':
curdir = Path(__file__).parent
srcdir = curdir / '..' / '..' / 'src'
run_cli(sys.argv[1:] + ['-P', srcdir.resolve(), curdir])
|
Fix test runner for acceptance tests
|
Fix test runner for acceptance tests
|
Python
|
mit
|
Eficode/robotframework-imagehorizonlibrary
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from robot import run_cli
run_cli(sys.argv[1:] + [os.path.dirname(__file__)])
Fix test runner for acceptance tests
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from pathlib import Path
from robot import run_cli
if __name__ == '__main__':
curdir = Path(__file__).parent
srcdir = curdir / '..' / '..' / 'src'
run_cli(sys.argv[1:] + ['-P', srcdir.resolve(), curdir])
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from robot import run_cli
run_cli(sys.argv[1:] + [os.path.dirname(__file__)])
<commit_msg>Fix test runner for acceptance tests<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from pathlib import Path
from robot import run_cli
if __name__ == '__main__':
curdir = Path(__file__).parent
srcdir = curdir / '..' / '..' / 'src'
run_cli(sys.argv[1:] + ['-P', srcdir.resolve(), curdir])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from robot import run_cli
run_cli(sys.argv[1:] + [os.path.dirname(__file__)])
Fix test runner for acceptance tests#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from pathlib import Path
from robot import run_cli
if __name__ == '__main__':
curdir = Path(__file__).parent
srcdir = curdir / '..' / '..' / 'src'
run_cli(sys.argv[1:] + ['-P', srcdir.resolve(), curdir])
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from robot import run_cli
run_cli(sys.argv[1:] + [os.path.dirname(__file__)])
<commit_msg>Fix test runner for acceptance tests<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from pathlib import Path
from robot import run_cli
if __name__ == '__main__':
curdir = Path(__file__).parent
srcdir = curdir / '..' / '..' / 'src'
run_cli(sys.argv[1:] + ['-P', srcdir.resolve(), curdir])
|
b8421633753fae1c0ad849dcc496e1861833243f
|
memegen/routes/root.py
|
memegen/routes/root.py
|
from collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route("")
def get_index():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("index.html", ga_tid=tid))
@blueprint.route("flask-api/static/js/default.js")
def get_javascript():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("js/default.js", ga_tid=tid))
@blueprint.route("api")
def get():
"""Generate memes from templates."""
data = OrderedDict()
data['version'] = __version__
data['templates'] = url_for('templates.get', _external=True)
data['overview'] = url_for('overview.get', _external=True)
data['generator'] = url_for('generator.get', _external=True)
data['latest'] = url_for('latest.get', _external=True)
data['source'] = GITHUB_BASE
data['contributing'] = CONTRIBUTING
return data
@blueprint.route("CHECK")
def handle_checks():
"""Return CHECK_OK for zero-downtime deployment.
See: https://labnotes.org/zero-downtime-deploy-with-dokku
"""
return "CHECK_OK"
|
from collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route("")
def get_index():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("index.html", ga_tid=tid))
@blueprint.route("flask-api/static/js/default.js")
def get_javascript():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("js/default.js", ga_tid=tid))
@blueprint.route("api")
def get():
"""Generate memes from templates."""
data = OrderedDict()
data['templates'] = url_for('templates.get', _external=True)
data['overview'] = url_for('overview.get', _external=True)
data['generator'] = url_for('generator.get', _external=True)
data['latest'] = url_for('latest.get', _external=True)
data['source'] = GITHUB_BASE
data['contributing'] = CONTRIBUTING
data['version'] = __version__
return data
@blueprint.route("CHECK")
def handle_checks():
"""Return CHECK_OK for zero-downtime deployment.
See: https://labnotes.org/zero-downtime-deploy-with-dokku
"""
return "CHECK_OK"
|
Move version to the bottom of the list
|
Move version to the bottom of the list
|
Python
|
mit
|
DanLindeman/memegen,joshfriend/memegen,joshfriend/memegen,DanLindeman/memegen,joshfriend/memegen,DanLindeman/memegen,joshfriend/memegen,DanLindeman/memegen
|
from collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route("")
def get_index():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("index.html", ga_tid=tid))
@blueprint.route("flask-api/static/js/default.js")
def get_javascript():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("js/default.js", ga_tid=tid))
@blueprint.route("api")
def get():
"""Generate memes from templates."""
data = OrderedDict()
data['version'] = __version__
data['templates'] = url_for('templates.get', _external=True)
data['overview'] = url_for('overview.get', _external=True)
data['generator'] = url_for('generator.get', _external=True)
data['latest'] = url_for('latest.get', _external=True)
data['source'] = GITHUB_BASE
data['contributing'] = CONTRIBUTING
return data
@blueprint.route("CHECK")
def handle_checks():
"""Return CHECK_OK for zero-downtime deployment.
See: https://labnotes.org/zero-downtime-deploy-with-dokku
"""
return "CHECK_OK"
Move version to the bottom of the list
|
from collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route("")
def get_index():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("index.html", ga_tid=tid))
@blueprint.route("flask-api/static/js/default.js")
def get_javascript():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("js/default.js", ga_tid=tid))
@blueprint.route("api")
def get():
"""Generate memes from templates."""
data = OrderedDict()
data['templates'] = url_for('templates.get', _external=True)
data['overview'] = url_for('overview.get', _external=True)
data['generator'] = url_for('generator.get', _external=True)
data['latest'] = url_for('latest.get', _external=True)
data['source'] = GITHUB_BASE
data['contributing'] = CONTRIBUTING
data['version'] = __version__
return data
@blueprint.route("CHECK")
def handle_checks():
"""Return CHECK_OK for zero-downtime deployment.
See: https://labnotes.org/zero-downtime-deploy-with-dokku
"""
return "CHECK_OK"
|
<commit_before>from collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route("")
def get_index():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("index.html", ga_tid=tid))
@blueprint.route("flask-api/static/js/default.js")
def get_javascript():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("js/default.js", ga_tid=tid))
@blueprint.route("api")
def get():
"""Generate memes from templates."""
data = OrderedDict()
data['version'] = __version__
data['templates'] = url_for('templates.get', _external=True)
data['overview'] = url_for('overview.get', _external=True)
data['generator'] = url_for('generator.get', _external=True)
data['latest'] = url_for('latest.get', _external=True)
data['source'] = GITHUB_BASE
data['contributing'] = CONTRIBUTING
return data
@blueprint.route("CHECK")
def handle_checks():
"""Return CHECK_OK for zero-downtime deployment.
See: https://labnotes.org/zero-downtime-deploy-with-dokku
"""
return "CHECK_OK"
<commit_msg>Move version to the bottom of the list<commit_after>
|
from collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route("")
def get_index():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("index.html", ga_tid=tid))
@blueprint.route("flask-api/static/js/default.js")
def get_javascript():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("js/default.js", ga_tid=tid))
@blueprint.route("api")
def get():
"""Generate memes from templates."""
data = OrderedDict()
data['templates'] = url_for('templates.get', _external=True)
data['overview'] = url_for('overview.get', _external=True)
data['generator'] = url_for('generator.get', _external=True)
data['latest'] = url_for('latest.get', _external=True)
data['source'] = GITHUB_BASE
data['contributing'] = CONTRIBUTING
data['version'] = __version__
return data
@blueprint.route("CHECK")
def handle_checks():
"""Return CHECK_OK for zero-downtime deployment.
See: https://labnotes.org/zero-downtime-deploy-with-dokku
"""
return "CHECK_OK"
|
from collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route("")
def get_index():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("index.html", ga_tid=tid))
@blueprint.route("flask-api/static/js/default.js")
def get_javascript():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("js/default.js", ga_tid=tid))
@blueprint.route("api")
def get():
"""Generate memes from templates."""
data = OrderedDict()
data['version'] = __version__
data['templates'] = url_for('templates.get', _external=True)
data['overview'] = url_for('overview.get', _external=True)
data['generator'] = url_for('generator.get', _external=True)
data['latest'] = url_for('latest.get', _external=True)
data['source'] = GITHUB_BASE
data['contributing'] = CONTRIBUTING
return data
@blueprint.route("CHECK")
def handle_checks():
"""Return CHECK_OK for zero-downtime deployment.
See: https://labnotes.org/zero-downtime-deploy-with-dokku
"""
return "CHECK_OK"
Move version to the bottom of the listfrom collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route("")
def get_index():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("index.html", ga_tid=tid))
@blueprint.route("flask-api/static/js/default.js")
def get_javascript():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("js/default.js", ga_tid=tid))
@blueprint.route("api")
def get():
"""Generate memes from templates."""
data = OrderedDict()
data['templates'] = url_for('templates.get', _external=True)
data['overview'] = url_for('overview.get', _external=True)
data['generator'] = url_for('generator.get', _external=True)
data['latest'] = url_for('latest.get', _external=True)
data['source'] = GITHUB_BASE
data['contributing'] = CONTRIBUTING
data['version'] = __version__
return data
@blueprint.route("CHECK")
def handle_checks():
"""Return CHECK_OK for zero-downtime deployment.
See: https://labnotes.org/zero-downtime-deploy-with-dokku
"""
return "CHECK_OK"
|
<commit_before>from collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route("")
def get_index():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("index.html", ga_tid=tid))
@blueprint.route("flask-api/static/js/default.js")
def get_javascript():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("js/default.js", ga_tid=tid))
@blueprint.route("api")
def get():
"""Generate memes from templates."""
data = OrderedDict()
data['version'] = __version__
data['templates'] = url_for('templates.get', _external=True)
data['overview'] = url_for('overview.get', _external=True)
data['generator'] = url_for('generator.get', _external=True)
data['latest'] = url_for('latest.get', _external=True)
data['source'] = GITHUB_BASE
data['contributing'] = CONTRIBUTING
return data
@blueprint.route("CHECK")
def handle_checks():
"""Return CHECK_OK for zero-downtime deployment.
See: https://labnotes.org/zero-downtime-deploy-with-dokku
"""
return "CHECK_OK"
<commit_msg>Move version to the bottom of the list<commit_after>from collections import OrderedDict
from flask import Blueprint, current_app, render_template, Response
from .. import __version__
from ._common import GITHUB_BASE, CONTRIBUTING, url_for
blueprint = Blueprint('root', __name__, url_prefix="/",
template_folder="../templates")
@blueprint.route("")
def get_index():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("index.html", ga_tid=tid))
@blueprint.route("flask-api/static/js/default.js")
def get_javascript():
tid = current_app.config['GOOGLE_ANALYTICS_TID']
return Response(render_template("js/default.js", ga_tid=tid))
@blueprint.route("api")
def get():
"""Generate memes from templates."""
data = OrderedDict()
data['templates'] = url_for('templates.get', _external=True)
data['overview'] = url_for('overview.get', _external=True)
data['generator'] = url_for('generator.get', _external=True)
data['latest'] = url_for('latest.get', _external=True)
data['source'] = GITHUB_BASE
data['contributing'] = CONTRIBUTING
data['version'] = __version__
return data
@blueprint.route("CHECK")
def handle_checks():
"""Return CHECK_OK for zero-downtime deployment.
See: https://labnotes.org/zero-downtime-deploy-with-dokku
"""
return "CHECK_OK"
|
6a79b7801184148dd1b329a5c41af1ae0fc3b4b9
|
docs/conf.py
|
docs/conf.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'jaraco.timing'
copyright = '2015 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..')
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'jaraco.timing'
copyright = '2015 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..', relative_to=__file__)
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
|
Fix version detection for tests
|
Fix version detection for tests
|
Python
|
mit
|
jaraco/tempora
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'jaraco.timing'
copyright = '2015 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..')
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
Fix version detection for tests
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'jaraco.timing'
copyright = '2015 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..', relative_to=__file__)
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
|
<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'jaraco.timing'
copyright = '2015 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..')
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
<commit_msg>Fix version detection for tests<commit_after>
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'jaraco.timing'
copyright = '2015 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..', relative_to=__file__)
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'jaraco.timing'
copyright = '2015 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..')
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
Fix version detection for tests#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'jaraco.timing'
copyright = '2015 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..', relative_to=__file__)
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
|
<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'jaraco.timing'
copyright = '2015 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..')
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
<commit_msg>Fix version detection for tests<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'jaraco.timing'
copyright = '2015 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..', relative_to=__file__)
# The full version, including alpha/beta/rc tags.
release = version
master_doc = 'index'
|
b9d8ac45f9cfec1fd1c3a3b0831815026e448a24
|
members/views.py
|
members/views.py
|
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')
|
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
from protocols.models import Protocol
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')
def archive_student_council(request):
protocols = Protocol.objects.all().order_by('-conducted_at')
return render(request, 'members/archive.html', locals())
|
Add view function for councili arhive
|
Add view function for councili arhive
|
Python
|
mit
|
Hackfmi/Diaphanum,Hackfmi/Diaphanum
|
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')Add view function for councili arhive
|
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
from protocols.models import Protocol
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')
def archive_student_council(request):
protocols = Protocol.objects.all().order_by('-conducted_at')
return render(request, 'members/archive.html', locals())
|
<commit_before># -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')<commit_msg>Add view function for councili arhive<commit_after>
|
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
from protocols.models import Protocol
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')
def archive_student_council(request):
protocols = Protocol.objects.all().order_by('-conducted_at')
return render(request, 'members/archive.html', locals())
|
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')Add view function for councili arhive# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
from protocols.models import Protocol
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')
def archive_student_council(request):
protocols = Protocol.objects.all().order_by('-conducted_at')
return render(request, 'members/archive.html', locals())
|
<commit_before># -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')<commit_msg>Add view function for councili arhive<commit_after># -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import auth
from hackfmi.utils import json_view
from .models import User
from protocols.models import Protocol
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
User.objects.filter(last_name__icontains=name) or \
User.objects.filter(username__icontains=name)
json_data = [dict(
id=member.id,
faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
for member in members]
return json_data
def login(request):
if request.user.is_authenticated():
return redirect('members.views.homepage')
else:
return auth.views.login(request, template_name='members/login_form.html')
def archive_student_council(request):
protocols = Protocol.objects.all().order_by('-conducted_at')
return render(request, 'members/archive.html', locals())
|
ae4af32bf5ca21b2c7d80e2034560ed23f6a2ea7
|
src/main-rpython.py
|
src/main-rpython.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
# __________ Entry points __________
def entry_point(argv):
try:
main(argv)
except Exit as e:
return e.code
except ParseError as e:
os.write(2, str(e))
return 1
except Exception as e:
os.write(2, "ERROR: %s thrown during execution.\n" % e)
return 1
return 1
# _____ Define and setup target ___
def target(driver, args):
exe_name = 'som-'
if is_ast_interpreter():
exe_name += 'ast-'
elif is_bytecode_interpreter():
exe_name += 'bc-'
if driver.config.translation.jit:
exe_name += 'jit'
else:
exe_name += 'interp'
driver.exe_name = exe_name
return entry_point, None
def jitpolicy(driver):
from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
from rpython.translator.driver import TranslationDriver
f, _ = target(TranslationDriver(), sys.argv)
sys.exit(f(sys.argv))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
try:
import rpython.rlib
except ImportError:
print("Failed to load RPython library. Please make sure it is on PYTHONPATH")
sys.exit(1)
# __________ Entry points __________
def entry_point(argv):
try:
main(argv)
except Exit as e:
return e.code
except ParseError as e:
os.write(2, str(e))
return 1
except Exception as e:
os.write(2, "ERROR: %s thrown during execution.\n" % e)
return 1
return 1
# _____ Define and setup target ___
def target(driver, args):
exe_name = 'som-'
if is_ast_interpreter():
exe_name += 'ast-'
elif is_bytecode_interpreter():
exe_name += 'bc-'
if driver.config.translation.jit:
exe_name += 'jit'
else:
exe_name += 'interp'
driver.exe_name = exe_name
return entry_point, None
def jitpolicy(driver):
from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
from rpython.translator.driver import TranslationDriver
f, _ = target(TranslationDriver(), sys.argv)
sys.exit(f(sys.argv))
|
Add error to make sure we have RPython when using the RPython main
|
Add error to make sure we have RPython when using the RPython main
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
|
Python
|
mit
|
SOM-st/RPySOM,smarr/PySOM,smarr/PySOM,SOM-st/PySOM,SOM-st/RPySOM,SOM-st/PySOM
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
# __________ Entry points __________
def entry_point(argv):
try:
main(argv)
except Exit as e:
return e.code
except ParseError as e:
os.write(2, str(e))
return 1
except Exception as e:
os.write(2, "ERROR: %s thrown during execution.\n" % e)
return 1
return 1
# _____ Define and setup target ___
def target(driver, args):
exe_name = 'som-'
if is_ast_interpreter():
exe_name += 'ast-'
elif is_bytecode_interpreter():
exe_name += 'bc-'
if driver.config.translation.jit:
exe_name += 'jit'
else:
exe_name += 'interp'
driver.exe_name = exe_name
return entry_point, None
def jitpolicy(driver):
from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
from rpython.translator.driver import TranslationDriver
f, _ = target(TranslationDriver(), sys.argv)
sys.exit(f(sys.argv))
Add error to make sure we have RPython when using the RPython main
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
try:
import rpython.rlib
except ImportError:
print("Failed to load RPython library. Please make sure it is on PYTHONPATH")
sys.exit(1)
# __________ Entry points __________
def entry_point(argv):
try:
main(argv)
except Exit as e:
return e.code
except ParseError as e:
os.write(2, str(e))
return 1
except Exception as e:
os.write(2, "ERROR: %s thrown during execution.\n" % e)
return 1
return 1
# _____ Define and setup target ___
def target(driver, args):
exe_name = 'som-'
if is_ast_interpreter():
exe_name += 'ast-'
elif is_bytecode_interpreter():
exe_name += 'bc-'
if driver.config.translation.jit:
exe_name += 'jit'
else:
exe_name += 'interp'
driver.exe_name = exe_name
return entry_point, None
def jitpolicy(driver):
from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
from rpython.translator.driver import TranslationDriver
f, _ = target(TranslationDriver(), sys.argv)
sys.exit(f(sys.argv))
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
# __________ Entry points __________
def entry_point(argv):
try:
main(argv)
except Exit as e:
return e.code
except ParseError as e:
os.write(2, str(e))
return 1
except Exception as e:
os.write(2, "ERROR: %s thrown during execution.\n" % e)
return 1
return 1
# _____ Define and setup target ___
def target(driver, args):
exe_name = 'som-'
if is_ast_interpreter():
exe_name += 'ast-'
elif is_bytecode_interpreter():
exe_name += 'bc-'
if driver.config.translation.jit:
exe_name += 'jit'
else:
exe_name += 'interp'
driver.exe_name = exe_name
return entry_point, None
def jitpolicy(driver):
from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
from rpython.translator.driver import TranslationDriver
f, _ = target(TranslationDriver(), sys.argv)
sys.exit(f(sys.argv))
<commit_msg>Add error to make sure we have RPython when using the RPython main
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de><commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
try:
import rpython.rlib
except ImportError:
print("Failed to load RPython library. Please make sure it is on PYTHONPATH")
sys.exit(1)
# __________ Entry points __________
def entry_point(argv):
try:
main(argv)
except Exit as e:
return e.code
except ParseError as e:
os.write(2, str(e))
return 1
except Exception as e:
os.write(2, "ERROR: %s thrown during execution.\n" % e)
return 1
return 1
# _____ Define and setup target ___
def target(driver, args):
exe_name = 'som-'
if is_ast_interpreter():
exe_name += 'ast-'
elif is_bytecode_interpreter():
exe_name += 'bc-'
if driver.config.translation.jit:
exe_name += 'jit'
else:
exe_name += 'interp'
driver.exe_name = exe_name
return entry_point, None
def jitpolicy(driver):
from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
from rpython.translator.driver import TranslationDriver
f, _ = target(TranslationDriver(), sys.argv)
sys.exit(f(sys.argv))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
# __________ Entry points __________
def entry_point(argv):
try:
main(argv)
except Exit as e:
return e.code
except ParseError as e:
os.write(2, str(e))
return 1
except Exception as e:
os.write(2, "ERROR: %s thrown during execution.\n" % e)
return 1
return 1
# _____ Define and setup target ___
def target(driver, args):
exe_name = 'som-'
if is_ast_interpreter():
exe_name += 'ast-'
elif is_bytecode_interpreter():
exe_name += 'bc-'
if driver.config.translation.jit:
exe_name += 'jit'
else:
exe_name += 'interp'
driver.exe_name = exe_name
return entry_point, None
def jitpolicy(driver):
from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
from rpython.translator.driver import TranslationDriver
f, _ = target(TranslationDriver(), sys.argv)
sys.exit(f(sys.argv))
Add error to make sure we have RPython when using the RPython main
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
try:
import rpython.rlib
except ImportError:
print("Failed to load RPython library. Please make sure it is on PYTHONPATH")
sys.exit(1)
# __________ Entry points __________
def entry_point(argv):
try:
main(argv)
except Exit as e:
return e.code
except ParseError as e:
os.write(2, str(e))
return 1
except Exception as e:
os.write(2, "ERROR: %s thrown during execution.\n" % e)
return 1
return 1
# _____ Define and setup target ___
def target(driver, args):
exe_name = 'som-'
if is_ast_interpreter():
exe_name += 'ast-'
elif is_bytecode_interpreter():
exe_name += 'bc-'
if driver.config.translation.jit:
exe_name += 'jit'
else:
exe_name += 'interp'
driver.exe_name = exe_name
return entry_point, None
def jitpolicy(driver):
from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
from rpython.translator.driver import TranslationDriver
f, _ = target(TranslationDriver(), sys.argv)
sys.exit(f(sys.argv))
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
# __________ Entry points __________
def entry_point(argv):
try:
main(argv)
except Exit as e:
return e.code
except ParseError as e:
os.write(2, str(e))
return 1
except Exception as e:
os.write(2, "ERROR: %s thrown during execution.\n" % e)
return 1
return 1
# _____ Define and setup target ___
def target(driver, args):
exe_name = 'som-'
if is_ast_interpreter():
exe_name += 'ast-'
elif is_bytecode_interpreter():
exe_name += 'bc-'
if driver.config.translation.jit:
exe_name += 'jit'
else:
exe_name += 'interp'
driver.exe_name = exe_name
return entry_point, None
def jitpolicy(driver):
from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
from rpython.translator.driver import TranslationDriver
f, _ = target(TranslationDriver(), sys.argv)
sys.exit(f(sys.argv))
<commit_msg>Add error to make sure we have RPython when using the RPython main
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de><commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from som.compiler.parse_error import ParseError
from som.interp_type import is_ast_interpreter, is_bytecode_interpreter
from som.vm.universe import main, Exit
import os
try:
import rpython.rlib
except ImportError:
print("Failed to load RPython library. Please make sure it is on PYTHONPATH")
sys.exit(1)
# __________ Entry points __________
def entry_point(argv):
try:
main(argv)
except Exit as e:
return e.code
except ParseError as e:
os.write(2, str(e))
return 1
except Exception as e:
os.write(2, "ERROR: %s thrown during execution.\n" % e)
return 1
return 1
# _____ Define and setup target ___
def target(driver, args):
exe_name = 'som-'
if is_ast_interpreter():
exe_name += 'ast-'
elif is_bytecode_interpreter():
exe_name += 'bc-'
if driver.config.translation.jit:
exe_name += 'jit'
else:
exe_name += 'interp'
driver.exe_name = exe_name
return entry_point, None
def jitpolicy(driver):
from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
from rpython.translator.driver import TranslationDriver
f, _ = target(TranslationDriver(), sys.argv)
sys.exit(f(sys.argv))
|
86d6b1cb8655d1734bcd5e5987e9e3df7e69c534
|
mkt/operators/views.py
|
mkt/operators/views.py
|
from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import RestOAuthAuthentication
from mkt.developers.models import PreloadTestPlan
from mkt.site.decorators import permission_required
from mkt.users.models import UserProfile
from .models import OperatorPermission
from .serializers import OperatorPermissionSerializer
@permission_required([('Operators', '*')])
@waffle_switch('preload-apps')
def preloads(request):
preloads = (PreloadTestPlan.objects.filter(status=amo.STATUS_PUBLIC)
.order_by('-created'))
preloads = paginate(request, preloads, per_page=20)
return render(request, 'operators/preloads.html', {'preloads': preloads})
class OperatorPermissionViewSet(CORSMixin, mixins.ListModelMixin,
viewsets.GenericViewSet):
authentication_classes = [RestOAuthAuthentication]
cors_allowed_methods = ('GET',)
queryset = OperatorPermission.objects.all()
permission_classes = []
serializer_class = OperatorPermissionSerializer
def get_queryset(self):
if isinstance(self.request.user, UserProfile):
return self.queryset.filter(user=self.request.user)
return self.queryset.none()
|
from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import (RestOAuthAuthentication,
RestSharedSecretAuthentication)
from mkt.developers.models import PreloadTestPlan
from mkt.site.decorators import permission_required
from mkt.users.models import UserProfile
from .models import OperatorPermission
from .serializers import OperatorPermissionSerializer
@permission_required([('Operators', '*')])
@waffle_switch('preload-apps')
def preloads(request):
preloads = (PreloadTestPlan.objects.filter(status=amo.STATUS_PUBLIC)
.order_by('-created'))
preloads = paginate(request, preloads, per_page=20)
return render(request, 'operators/preloads.html', {'preloads': preloads})
class OperatorPermissionViewSet(CORSMixin, mixins.ListModelMixin,
viewsets.GenericViewSet):
authentication_classes = [RestOAuthAuthentication,
RestSharedSecretAuthentication]
cors_allowed_methods = ('GET',)
queryset = OperatorPermission.objects.all()
permission_classes = []
serializer_class = OperatorPermissionSerializer
def get_queryset(self):
if isinstance(self.request.user, UserProfile):
return self.queryset.filter(user=self.request.user)
return self.queryset.none()
|
Allow shared secret auth on OperatorPermissionViewSet.
|
Allow shared secret auth on OperatorPermissionViewSet.
|
Python
|
bsd-3-clause
|
clouserw/zamboni,mozilla/zamboni,mudithkr/zamboni,mstriemer/zamboni,mozilla/zamboni,washort/zamboni,ayushagrawal288/zamboni,Jobava/zamboni,Jobava/zamboni,ayushagrawal288/zamboni,elysium001/zamboni,ingenioustechie/zamboni,eviljeff/zamboni,washort/zamboni,ddurst/zamboni,elysium001/zamboni,eviljeff/zamboni,tsl143/zamboni,washort/zamboni,shahbaz17/zamboni,elysium001/zamboni,jasonthomas/zamboni,luckylavish/zamboni,Jobava/zamboni,ddurst/zamboni,ingenioustechie/zamboni,Jobava/zamboni,kumar303/zamboni,luckylavish/zamboni,ayushagrawal288/zamboni,tsl143/zamboni,diox/zamboni,mudithkr/zamboni,mudithkr/zamboni,clouserw/zamboni,eviljeff/zamboni,diox/zamboni,kumar303/zamboni,mozilla/zamboni,diox/zamboni,clouserw/zamboni,ayushagrawal288/zamboni,tsl143/zamboni,shahbaz17/zamboni,Hitechverma/zamboni,washort/zamboni,shahbaz17/zamboni,clouserw/zamboni,mstriemer/zamboni,jamesthechamp/zamboni,kumar303/zamboni,diox/zamboni,ddurst/zamboni,jasonthomas/zamboni,ddurst/zamboni,elysium001/zamboni,mstriemer/zamboni,jasonthomas/zamboni,jamesthechamp/zamboni,ingenioustechie/zamboni,shahbaz17/zamboni,mozilla/zamboni,Hitechverma/zamboni,tsl143/zamboni,jamesthechamp/zamboni,mstriemer/zamboni,jamesthechamp/zamboni,ingenioustechie/zamboni,mudithkr/zamboni,Hitechverma/zamboni,Hitechverma/zamboni,eviljeff/zamboni,jasonthomas/zamboni,luckylavish/zamboni,luckylavish/zamboni,kumar303/zamboni
|
from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import RestOAuthAuthentication
from mkt.developers.models import PreloadTestPlan
from mkt.site.decorators import permission_required
from mkt.users.models import UserProfile
from .models import OperatorPermission
from .serializers import OperatorPermissionSerializer
@permission_required([('Operators', '*')])
@waffle_switch('preload-apps')
def preloads(request):
preloads = (PreloadTestPlan.objects.filter(status=amo.STATUS_PUBLIC)
.order_by('-created'))
preloads = paginate(request, preloads, per_page=20)
return render(request, 'operators/preloads.html', {'preloads': preloads})
class OperatorPermissionViewSet(CORSMixin, mixins.ListModelMixin,
viewsets.GenericViewSet):
authentication_classes = [RestOAuthAuthentication]
cors_allowed_methods = ('GET',)
queryset = OperatorPermission.objects.all()
permission_classes = []
serializer_class = OperatorPermissionSerializer
def get_queryset(self):
if isinstance(self.request.user, UserProfile):
return self.queryset.filter(user=self.request.user)
return self.queryset.none()
Allow shared secret auth on OperatorPermissionViewSet.
|
from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import (RestOAuthAuthentication,
RestSharedSecretAuthentication)
from mkt.developers.models import PreloadTestPlan
from mkt.site.decorators import permission_required
from mkt.users.models import UserProfile
from .models import OperatorPermission
from .serializers import OperatorPermissionSerializer
@permission_required([('Operators', '*')])
@waffle_switch('preload-apps')
def preloads(request):
preloads = (PreloadTestPlan.objects.filter(status=amo.STATUS_PUBLIC)
.order_by('-created'))
preloads = paginate(request, preloads, per_page=20)
return render(request, 'operators/preloads.html', {'preloads': preloads})
class OperatorPermissionViewSet(CORSMixin, mixins.ListModelMixin,
viewsets.GenericViewSet):
authentication_classes = [RestOAuthAuthentication,
RestSharedSecretAuthentication]
cors_allowed_methods = ('GET',)
queryset = OperatorPermission.objects.all()
permission_classes = []
serializer_class = OperatorPermissionSerializer
def get_queryset(self):
if isinstance(self.request.user, UserProfile):
return self.queryset.filter(user=self.request.user)
return self.queryset.none()
|
<commit_before>from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import RestOAuthAuthentication
from mkt.developers.models import PreloadTestPlan
from mkt.site.decorators import permission_required
from mkt.users.models import UserProfile
from .models import OperatorPermission
from .serializers import OperatorPermissionSerializer
@permission_required([('Operators', '*')])
@waffle_switch('preload-apps')
def preloads(request):
preloads = (PreloadTestPlan.objects.filter(status=amo.STATUS_PUBLIC)
.order_by('-created'))
preloads = paginate(request, preloads, per_page=20)
return render(request, 'operators/preloads.html', {'preloads': preloads})
class OperatorPermissionViewSet(CORSMixin, mixins.ListModelMixin,
viewsets.GenericViewSet):
authentication_classes = [RestOAuthAuthentication]
cors_allowed_methods = ('GET',)
queryset = OperatorPermission.objects.all()
permission_classes = []
serializer_class = OperatorPermissionSerializer
def get_queryset(self):
if isinstance(self.request.user, UserProfile):
return self.queryset.filter(user=self.request.user)
return self.queryset.none()
<commit_msg>Allow shared secret auth on OperatorPermissionViewSet.<commit_after>
|
from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import (RestOAuthAuthentication,
RestSharedSecretAuthentication)
from mkt.developers.models import PreloadTestPlan
from mkt.site.decorators import permission_required
from mkt.users.models import UserProfile
from .models import OperatorPermission
from .serializers import OperatorPermissionSerializer
@permission_required([('Operators', '*')])
@waffle_switch('preload-apps')
def preloads(request):
preloads = (PreloadTestPlan.objects.filter(status=amo.STATUS_PUBLIC)
.order_by('-created'))
preloads = paginate(request, preloads, per_page=20)
return render(request, 'operators/preloads.html', {'preloads': preloads})
class OperatorPermissionViewSet(CORSMixin, mixins.ListModelMixin,
viewsets.GenericViewSet):
authentication_classes = [RestOAuthAuthentication,
RestSharedSecretAuthentication]
cors_allowed_methods = ('GET',)
queryset = OperatorPermission.objects.all()
permission_classes = []
serializer_class = OperatorPermissionSerializer
def get_queryset(self):
if isinstance(self.request.user, UserProfile):
return self.queryset.filter(user=self.request.user)
return self.queryset.none()
|
from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import RestOAuthAuthentication
from mkt.developers.models import PreloadTestPlan
from mkt.site.decorators import permission_required
from mkt.users.models import UserProfile
from .models import OperatorPermission
from .serializers import OperatorPermissionSerializer
@permission_required([('Operators', '*')])
@waffle_switch('preload-apps')
def preloads(request):
preloads = (PreloadTestPlan.objects.filter(status=amo.STATUS_PUBLIC)
.order_by('-created'))
preloads = paginate(request, preloads, per_page=20)
return render(request, 'operators/preloads.html', {'preloads': preloads})
class OperatorPermissionViewSet(CORSMixin, mixins.ListModelMixin,
viewsets.GenericViewSet):
authentication_classes = [RestOAuthAuthentication]
cors_allowed_methods = ('GET',)
queryset = OperatorPermission.objects.all()
permission_classes = []
serializer_class = OperatorPermissionSerializer
def get_queryset(self):
if isinstance(self.request.user, UserProfile):
return self.queryset.filter(user=self.request.user)
return self.queryset.none()
Allow shared secret auth on OperatorPermissionViewSet.from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import (RestOAuthAuthentication,
RestSharedSecretAuthentication)
from mkt.developers.models import PreloadTestPlan
from mkt.site.decorators import permission_required
from mkt.users.models import UserProfile
from .models import OperatorPermission
from .serializers import OperatorPermissionSerializer
@permission_required([('Operators', '*')])
@waffle_switch('preload-apps')
def preloads(request):
preloads = (PreloadTestPlan.objects.filter(status=amo.STATUS_PUBLIC)
.order_by('-created'))
preloads = paginate(request, preloads, per_page=20)
return render(request, 'operators/preloads.html', {'preloads': preloads})
class OperatorPermissionViewSet(CORSMixin, mixins.ListModelMixin,
viewsets.GenericViewSet):
authentication_classes = [RestOAuthAuthentication,
RestSharedSecretAuthentication]
cors_allowed_methods = ('GET',)
queryset = OperatorPermission.objects.all()
permission_classes = []
serializer_class = OperatorPermissionSerializer
def get_queryset(self):
if isinstance(self.request.user, UserProfile):
return self.queryset.filter(user=self.request.user)
return self.queryset.none()
|
<commit_before>from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import RestOAuthAuthentication
from mkt.developers.models import PreloadTestPlan
from mkt.site.decorators import permission_required
from mkt.users.models import UserProfile
from .models import OperatorPermission
from .serializers import OperatorPermissionSerializer
@permission_required([('Operators', '*')])
@waffle_switch('preload-apps')
def preloads(request):
preloads = (PreloadTestPlan.objects.filter(status=amo.STATUS_PUBLIC)
.order_by('-created'))
preloads = paginate(request, preloads, per_page=20)
return render(request, 'operators/preloads.html', {'preloads': preloads})
class OperatorPermissionViewSet(CORSMixin, mixins.ListModelMixin,
viewsets.GenericViewSet):
authentication_classes = [RestOAuthAuthentication]
cors_allowed_methods = ('GET',)
queryset = OperatorPermission.objects.all()
permission_classes = []
serializer_class = OperatorPermissionSerializer
def get_queryset(self):
if isinstance(self.request.user, UserProfile):
return self.queryset.filter(user=self.request.user)
return self.queryset.none()
<commit_msg>Allow shared secret auth on OperatorPermissionViewSet.<commit_after>from django.shortcuts import render
from rest_framework import mixins, viewsets
from waffle.decorators import waffle_switch
import amo
from amo.utils import paginate
from mkt.api.base import CORSMixin
from mkt.api.authentication import (RestOAuthAuthentication,
RestSharedSecretAuthentication)
from mkt.developers.models import PreloadTestPlan
from mkt.site.decorators import permission_required
from mkt.users.models import UserProfile
from .models import OperatorPermission
from .serializers import OperatorPermissionSerializer
@permission_required([('Operators', '*')])
@waffle_switch('preload-apps')
def preloads(request):
preloads = (PreloadTestPlan.objects.filter(status=amo.STATUS_PUBLIC)
.order_by('-created'))
preloads = paginate(request, preloads, per_page=20)
return render(request, 'operators/preloads.html', {'preloads': preloads})
class OperatorPermissionViewSet(CORSMixin, mixins.ListModelMixin,
viewsets.GenericViewSet):
authentication_classes = [RestOAuthAuthentication,
RestSharedSecretAuthentication]
cors_allowed_methods = ('GET',)
queryset = OperatorPermission.objects.all()
permission_classes = []
serializer_class = OperatorPermissionSerializer
def get_queryset(self):
if isinstance(self.request.user, UserProfile):
return self.queryset.filter(user=self.request.user)
return self.queryset.none()
|
e56fe4e39db2a6043493542664d320c6127d4741
|
ecmd-core/pyapi/init/__init__.py
|
ecmd-core/pyapi/init/__init__.py
|
# import the right SWIG module depending on Python version
from sys import version_info
import sys, os
if version_info[0] >= 3:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python3"))
from .python3 import *
else:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python2"))
from .python2 import *
del sys, os, version_info
|
# import the right SWIG module depending on Python version
from sys import version_info
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python2"))
from .python2 import *
del sys_path, os_path, version_info
|
Rework of path insert since del line was causing issues
|
Rework of path insert since del line was causing issues
|
Python
|
apache-2.0
|
open-power/eCMD,open-power/eCMD,mklight/eCMD,mklight/eCMD,open-power/eCMD,open-power/eCMD,mklight/eCMD,open-power/eCMD,mklight/eCMD,mklight/eCMD
|
# import the right SWIG module depending on Python version
from sys import version_info
import sys, os
if version_info[0] >= 3:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python3"))
from .python3 import *
else:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python2"))
from .python2 import *
del sys, os, version_info
Rework of path insert since del line was causing issues
|
# import the right SWIG module depending on Python version
from sys import version_info
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python2"))
from .python2 import *
del sys_path, os_path, version_info
|
<commit_before># import the right SWIG module depending on Python version
from sys import version_info
import sys, os
if version_info[0] >= 3:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python3"))
from .python3 import *
else:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python2"))
from .python2 import *
del sys, os, version_info
<commit_msg>Rework of path insert since del line was causing issues<commit_after>
|
# import the right SWIG module depending on Python version
from sys import version_info
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python2"))
from .python2 import *
del sys_path, os_path, version_info
|
# import the right SWIG module depending on Python version
from sys import version_info
import sys, os
if version_info[0] >= 3:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python3"))
from .python3 import *
else:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python2"))
from .python2 import *
del sys, os, version_info
Rework of path insert since del line was causing issues# import the right SWIG module depending on Python version
from sys import version_info
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python2"))
from .python2 import *
del sys_path, os_path, version_info
|
<commit_before># import the right SWIG module depending on Python version
from sys import version_info
import sys, os
if version_info[0] >= 3:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python3"))
from .python3 import *
else:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "python2"))
from .python2 import *
del sys, os, version_info
<commit_msg>Rework of path insert since del line was causing issues<commit_after># import the right SWIG module depending on Python version
from sys import version_info
from sys import path as sys_path
from os import path as os_path
if version_info[0] >= 3:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3"))
from .python3 import *
else:
sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python2"))
from .python2 import *
del sys_path, os_path, version_info
|
c04103b457040355da9dcf6a1059539bf6470092
|
mutt-addressbook.py
|
mutt-addressbook.py
|
#!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
with ldap3.Connection(d[0], auto_bind=True) as conn:
print(d[0] + ' … ', end='', flush=True)
flt = '(&' + FILTER + \
'(|(mail=' + argv[1] + '*)(cn=' + argv[1] + '*)))'
conn.search(d[1], flt, attributes=ATTRS)
entries.extend(conn.entries)
if len(entries) == 0:
print('No entries found!')
exit(1)
print(str(len(entries)) + ' entries found!')
for i in entries:
for m in i.mail.values:
print(m + '\t' + i.cn[0] + '\t' + i.entry_dn)
except Exception as e:
print("Error: " + type(e).__name__ + ": " + str(e))
exit(1)
|
#!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
with ldap3.Connection(d[0], auto_bind=True) as conn:
print(''.join((d[0], ' … ')), end='', flush=True)
flt = '(&{0}(|(mail={1}*)(cn={1}*)))'.format(FILTER, argv[1])
conn.search(d[1], flt, attributes=ATTRS)
entries.extend(conn.entries)
if len(entries) == 0:
print('No entries found!')
exit(1)
print('{:d} entries found!'.format(len(entries)))
for i in entries:
for m in i.mail.values:
print('{}\t{}\t{}'.format(m, i.cn[0], i.entry_dn))
except Exception as e:
print('Error: {}: {}'.format(type(e).__name__, e))
exit(1)
|
Rework string concatenation with join and format
|
Rework string concatenation with join and format
Signed-off-by: Alwed <b03a9dbc84dbfcd49b3dd10dfbe7e015dc04cee5@t-online.de>
|
Python
|
isc
|
qsuscs/mutt-addressbook
|
#!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
with ldap3.Connection(d[0], auto_bind=True) as conn:
print(d[0] + ' … ', end='', flush=True)
flt = '(&' + FILTER + \
'(|(mail=' + argv[1] + '*)(cn=' + argv[1] + '*)))'
conn.search(d[1], flt, attributes=ATTRS)
entries.extend(conn.entries)
if len(entries) == 0:
print('No entries found!')
exit(1)
print(str(len(entries)) + ' entries found!')
for i in entries:
for m in i.mail.values:
print(m + '\t' + i.cn[0] + '\t' + i.entry_dn)
except Exception as e:
print("Error: " + type(e).__name__ + ": " + str(e))
exit(1)
Rework string concatenation with join and format
Signed-off-by: Alwed <b03a9dbc84dbfcd49b3dd10dfbe7e015dc04cee5@t-online.de>
|
#!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
with ldap3.Connection(d[0], auto_bind=True) as conn:
print(''.join((d[0], ' … ')), end='', flush=True)
flt = '(&{0}(|(mail={1}*)(cn={1}*)))'.format(FILTER, argv[1])
conn.search(d[1], flt, attributes=ATTRS)
entries.extend(conn.entries)
if len(entries) == 0:
print('No entries found!')
exit(1)
print('{:d} entries found!'.format(len(entries)))
for i in entries:
for m in i.mail.values:
print('{}\t{}\t{}'.format(m, i.cn[0], i.entry_dn))
except Exception as e:
print('Error: {}: {}'.format(type(e).__name__, e))
exit(1)
|
<commit_before>#!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
with ldap3.Connection(d[0], auto_bind=True) as conn:
print(d[0] + ' … ', end='', flush=True)
flt = '(&' + FILTER + \
'(|(mail=' + argv[1] + '*)(cn=' + argv[1] + '*)))'
conn.search(d[1], flt, attributes=ATTRS)
entries.extend(conn.entries)
if len(entries) == 0:
print('No entries found!')
exit(1)
print(str(len(entries)) + ' entries found!')
for i in entries:
for m in i.mail.values:
print(m + '\t' + i.cn[0] + '\t' + i.entry_dn)
except Exception as e:
print("Error: " + type(e).__name__ + ": " + str(e))
exit(1)
<commit_msg>Rework string concatenation with join and format
Signed-off-by: Alwed <b03a9dbc84dbfcd49b3dd10dfbe7e015dc04cee5@t-online.de><commit_after>
|
#!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
with ldap3.Connection(d[0], auto_bind=True) as conn:
print(''.join((d[0], ' … ')), end='', flush=True)
flt = '(&{0}(|(mail={1}*)(cn={1}*)))'.format(FILTER, argv[1])
conn.search(d[1], flt, attributes=ATTRS)
entries.extend(conn.entries)
if len(entries) == 0:
print('No entries found!')
exit(1)
print('{:d} entries found!'.format(len(entries)))
for i in entries:
for m in i.mail.values:
print('{}\t{}\t{}'.format(m, i.cn[0], i.entry_dn))
except Exception as e:
print('Error: {}: {}'.format(type(e).__name__, e))
exit(1)
|
#!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
with ldap3.Connection(d[0], auto_bind=True) as conn:
print(d[0] + ' … ', end='', flush=True)
flt = '(&' + FILTER + \
'(|(mail=' + argv[1] + '*)(cn=' + argv[1] + '*)))'
conn.search(d[1], flt, attributes=ATTRS)
entries.extend(conn.entries)
if len(entries) == 0:
print('No entries found!')
exit(1)
print(str(len(entries)) + ' entries found!')
for i in entries:
for m in i.mail.values:
print(m + '\t' + i.cn[0] + '\t' + i.entry_dn)
except Exception as e:
print("Error: " + type(e).__name__ + ": " + str(e))
exit(1)
Rework string concatenation with join and format
Signed-off-by: Alwed <b03a9dbc84dbfcd49b3dd10dfbe7e015dc04cee5@t-online.de>#!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
with ldap3.Connection(d[0], auto_bind=True) as conn:
print(''.join((d[0], ' … ')), end='', flush=True)
flt = '(&{0}(|(mail={1}*)(cn={1}*)))'.format(FILTER, argv[1])
conn.search(d[1], flt, attributes=ATTRS)
entries.extend(conn.entries)
if len(entries) == 0:
print('No entries found!')
exit(1)
print('{:d} entries found!'.format(len(entries)))
for i in entries:
for m in i.mail.values:
print('{}\t{}\t{}'.format(m, i.cn[0], i.entry_dn))
except Exception as e:
print('Error: {}: {}'.format(type(e).__name__, e))
exit(1)
|
<commit_before>#!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
with ldap3.Connection(d[0], auto_bind=True) as conn:
print(d[0] + ' … ', end='', flush=True)
flt = '(&' + FILTER + \
'(|(mail=' + argv[1] + '*)(cn=' + argv[1] + '*)))'
conn.search(d[1], flt, attributes=ATTRS)
entries.extend(conn.entries)
if len(entries) == 0:
print('No entries found!')
exit(1)
print(str(len(entries)) + ' entries found!')
for i in entries:
for m in i.mail.values:
print(m + '\t' + i.cn[0] + '\t' + i.entry_dn)
except Exception as e:
print("Error: " + type(e).__name__ + ": " + str(e))
exit(1)
<commit_msg>Rework string concatenation with join and format
Signed-off-by: Alwed <b03a9dbc84dbfcd49b3dd10dfbe7e015dc04cee5@t-online.de><commit_after>#!/usr/bin/env python3
try:
from sys import argv
import ldap3
LDAPDIRS = [
('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de')
]
FILTER = '(mail=*)'
ATTRS = ['cn', 'mail']
print('Searching … ', end='', flush=True)
entries = []
for d in LDAPDIRS:
with ldap3.Connection(d[0], auto_bind=True) as conn:
print(''.join((d[0], ' … ')), end='', flush=True)
flt = '(&{0}(|(mail={1}*)(cn={1}*)))'.format(FILTER, argv[1])
conn.search(d[1], flt, attributes=ATTRS)
entries.extend(conn.entries)
if len(entries) == 0:
print('No entries found!')
exit(1)
print('{:d} entries found!'.format(len(entries)))
for i in entries:
for m in i.mail.values:
print('{}\t{}\t{}'.format(m, i.cn[0], i.entry_dn))
except Exception as e:
print('Error: {}: {}'.format(type(e).__name__, e))
exit(1)
|
89a8cc53f2ad373eb8ff0508dbb5f111e6ee2b6e
|
nashvegas/models.py
|
nashvegas/models.py
|
from django.db import models
from django.utils import timezone
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=timezone.now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return unicode("%s [%s]" % (self.migration_label, self.scm_version))
|
from django.db import models
try:
from django.utils.timezone import now
except ImportError:
from datetime.datetime import now
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return unicode("%s [%s]" % (self.migration_label, self.scm_version))
|
Fix import error for Django 1.3.1
|
Fix import error for Django 1.3.1
|
Python
|
mit
|
paltman-archive/nashvegas,jonathanchu/nashvegas,iivvoo/nashvegas,dcramer/nashvegas,paltman/nashvegas
|
from django.db import models
from django.utils import timezone
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=timezone.now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return unicode("%s [%s]" % (self.migration_label, self.scm_version))
Fix import error for Django 1.3.1
|
from django.db import models
try:
from django.utils.timezone import now
except ImportError:
from datetime.datetime import now
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return unicode("%s [%s]" % (self.migration_label, self.scm_version))
|
<commit_before>from django.db import models
from django.utils import timezone
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=timezone.now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return unicode("%s [%s]" % (self.migration_label, self.scm_version))
<commit_msg>Fix import error for Django 1.3.1<commit_after>
|
from django.db import models
try:
from django.utils.timezone import now
except ImportError:
from datetime.datetime import now
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return unicode("%s [%s]" % (self.migration_label, self.scm_version))
|
from django.db import models
from django.utils import timezone
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=timezone.now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return unicode("%s [%s]" % (self.migration_label, self.scm_version))
Fix import error for Django 1.3.1from django.db import models
try:
from django.utils.timezone import now
except ImportError:
from datetime.datetime import now
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return unicode("%s [%s]" % (self.migration_label, self.scm_version))
|
<commit_before>from django.db import models
from django.utils import timezone
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=timezone.now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return unicode("%s [%s]" % (self.migration_label, self.scm_version))
<commit_msg>Fix import error for Django 1.3.1<commit_after>from django.db import models
try:
from django.utils.timezone import now
except ImportError:
from datetime.datetime import now
class Migration(models.Model):
migration_label = models.CharField(max_length=200)
date_created = models.DateTimeField(default=now)
content = models.TextField()
scm_version = models.CharField(max_length=50, null=True, blank=True)
def __unicode__(self):
return unicode("%s [%s]" % (self.migration_label, self.scm_version))
|
292b4843fdb0efbf3cc8d7c97aaa8abd2cd22a28
|
optimization/simple.py
|
optimization/simple.py
|
#!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
|
#!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
#m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
coef=[1,2]
var=[x1,x2]
s=[]
for c,v in zip(coef,var):
print(c,v)
s.append(c*v)
m.setObjective(sum(s),GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
|
Use sum function to construct objective function.
|
Use sum function to construct objective function.
|
Python
|
apache-2.0
|
MiddelkoopT/CompOpt-2014-Fall,MiddelkoopT/CompOpt-2014-Fall
|
#!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
Use sum function to construct objective function.
|
#!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
#m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
coef=[1,2]
var=[x1,x2]
s=[]
for c,v in zip(coef,var):
print(c,v)
s.append(c*v)
m.setObjective(sum(s),GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
|
<commit_before>#!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
<commit_msg>Use sum function to construct objective function.<commit_after>
|
#!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
#m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
coef=[1,2]
var=[x1,x2]
s=[]
for c,v in zip(coef,var):
print(c,v)
s.append(c*v)
m.setObjective(sum(s),GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
|
#!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
Use sum function to construct objective function.#!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
#m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
coef=[1,2]
var=[x1,x2]
s=[]
for c,v in zip(coef,var):
print(c,v)
s.append(c*v)
m.setObjective(sum(s),GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
|
<commit_before>#!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
<commit_msg>Use sum function to construct objective function.<commit_after>#!/usr/bin/python3
"""
Maximize
1 x1 + 2 x2
Subject To
C1: x1 + x2 <= 40
Nickel: 2 x1 + 1 x2 <= 60
Bounds
x1 >= 0
x2 >= 0
End
"""
from gurobipy import *
m = Model("simple")
x1 = m.addVar(name="x1")
x2 = m.addVar(name="x2")
m.update()
print("x1:%s x2:%s" % (x1,x2))
#m.setObjective(x1 + 2*x2, GRB.MAXIMIZE)
coef=[1,2]
var=[x1,x2]
s=[]
for c,v in zip(coef,var):
print(c,v)
s.append(c*v)
m.setObjective(sum(s),GRB.MAXIMIZE)
m.addConstr(x1 + x2 <= 40, "C1")
m.addConstr(2*x1 + x2 <= 60, "C2")
m.optimize()
print("Solution: %f" % (m.objVal,))
for v in m.getVars():
print("%s:%f" % (v.varName, v.x))
|
432a7f72c790ca7ba18f4d575706461e337da593
|
src/hunter/const.py
|
src/hunter/const.py
|
import os
import site
import stat
import sys
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(stat.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
|
import os
import site
import stat
import sys
import sysconfig
SITE_PACKAGES_PATHS = set()
for scheme in sysconfig.get_scheme_names():
for name in ['platlib', 'purelib']:
try:
SITE_PACKAGES_PATHS.add(sysconfig.get_path(name, scheme))
except KeyError:
pass
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
if sys.version_info >= (3, 10):
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(stat.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
|
Use new method to get package paths that works without deprecations on Python 3.10
|
Use new method to get package paths that works without deprecations on Python 3.10
|
Python
|
bsd-2-clause
|
ionelmc/python-hunter
|
import os
import site
import stat
import sys
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(stat.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
Use new method to get package paths that works without deprecations on Python 3.10
|
import os
import site
import stat
import sys
import sysconfig
SITE_PACKAGES_PATHS = set()
for scheme in sysconfig.get_scheme_names():
for name in ['platlib', 'purelib']:
try:
SITE_PACKAGES_PATHS.add(sysconfig.get_path(name, scheme))
except KeyError:
pass
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
if sys.version_info >= (3, 10):
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(stat.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
|
<commit_before>import os
import site
import stat
import sys
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(stat.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
<commit_msg>Use new method to get package paths that works without deprecations on Python 3.10<commit_after>
|
import os
import site
import stat
import sys
import sysconfig
SITE_PACKAGES_PATHS = set()
for scheme in sysconfig.get_scheme_names():
for name in ['platlib', 'purelib']:
try:
SITE_PACKAGES_PATHS.add(sysconfig.get_path(name, scheme))
except KeyError:
pass
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
if sys.version_info >= (3, 10):
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(stat.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
|
import os
import site
import stat
import sys
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(stat.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
Use new method to get package paths that works without deprecations on Python 3.10import os
import site
import stat
import sys
import sysconfig
SITE_PACKAGES_PATHS = set()
for scheme in sysconfig.get_scheme_names():
for name in ['platlib', 'purelib']:
try:
SITE_PACKAGES_PATHS.add(sysconfig.get_path(name, scheme))
except KeyError:
pass
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
if sys.version_info >= (3, 10):
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(stat.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
|
<commit_before>import os
import site
import stat
import sys
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(stat.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
<commit_msg>Use new method to get package paths that works without deprecations on Python 3.10<commit_after>import os
import site
import stat
import sys
import sysconfig
SITE_PACKAGES_PATHS = set()
for scheme in sysconfig.get_scheme_names():
for name in ['platlib', 'purelib']:
try:
SITE_PACKAGES_PATHS.add(sysconfig.get_path(name, scheme))
except KeyError:
pass
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
if sys.version_info >= (3, 10):
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS.add(os.path.dirname(os.path.dirname(__file__)))
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
'<frozen zipimport>',
'<frozen importlib._bootstrap>',
'<frozen importlib._bootstrap_external>',
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(stat.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
|
88734c5aaf3bdddd1e41beff3bdb70b27590490c
|
projects/urls.py
|
projects/urls.py
|
from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
)
|
from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', 'projects_archive', name='projects_archive'),
)
|
Add url leading to the archive page
|
Add url leading to the archive page
|
Python
|
mit
|
Hackfmi/Diaphanum,Hackfmi/Diaphanum
|
from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
)
Add url leading to the archive page
|
from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', 'projects_archive', name='projects_archive'),
)
|
<commit_before>from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
)
<commit_msg>Add url leading to the archive page<commit_after>
|
from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', 'projects_archive', name='projects_archive'),
)
|
from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
)
Add url leading to the archive pagefrom django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', 'projects_archive', name='projects_archive'),
)
|
<commit_before>from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
)
<commit_msg>Add url leading to the archive page<commit_after>from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>.*)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>.*)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', 'projects_archive', name='projects_archive'),
)
|
7a735bebf195f766a0db97b3fba6793a69a5731a
|
microcosm_elasticsearch/main.py
|
microcosm_elasticsearch/main.py
|
"""
CLI entry point hook.
"""
from argparse import ArgumentParser
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
|
"""
CLI entry point hook.
"""
from argparse import ArgumentParser
from json import dump, loads
from sys import stdout
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
def query_main(graph, default_index):
parser = ArgumentParser()
parser.add_argument("--index", default=default_index)
parser.add_argument("--query", default='{"match_all": {}}')
args = parser.parse_args()
try:
query = loads(args.query)
except:
parser.error("query must be valid json")
response = graph.elasticsearch_client.search(
index=args.index,
body=dict(query=query),
)
dump(response, stdout)
|
Add a query entry point
|
Add a query entry point
|
Python
|
apache-2.0
|
globality-corp/microcosm-elasticsearch,globality-corp/microcosm-elasticsearch
|
"""
CLI entry point hook.
"""
from argparse import ArgumentParser
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
Add a query entry point
|
"""
CLI entry point hook.
"""
from argparse import ArgumentParser
from json import dump, loads
from sys import stdout
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
def query_main(graph, default_index):
parser = ArgumentParser()
parser.add_argument("--index", default=default_index)
parser.add_argument("--query", default='{"match_all": {}}')
args = parser.parse_args()
try:
query = loads(args.query)
except:
parser.error("query must be valid json")
response = graph.elasticsearch_client.search(
index=args.index,
body=dict(query=query),
)
dump(response, stdout)
|
<commit_before>"""
CLI entry point hook.
"""
from argparse import ArgumentParser
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
<commit_msg>Add a query entry point<commit_after>
|
"""
CLI entry point hook.
"""
from argparse import ArgumentParser
from json import dump, loads
from sys import stdout
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
def query_main(graph, default_index):
parser = ArgumentParser()
parser.add_argument("--index", default=default_index)
parser.add_argument("--query", default='{"match_all": {}}')
args = parser.parse_args()
try:
query = loads(args.query)
except:
parser.error("query must be valid json")
response = graph.elasticsearch_client.search(
index=args.index,
body=dict(query=query),
)
dump(response, stdout)
|
"""
CLI entry point hook.
"""
from argparse import ArgumentParser
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
Add a query entry point"""
CLI entry point hook.
"""
from argparse import ArgumentParser
from json import dump, loads
from sys import stdout
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
def query_main(graph, default_index):
parser = ArgumentParser()
parser.add_argument("--index", default=default_index)
parser.add_argument("--query", default='{"match_all": {}}')
args = parser.parse_args()
try:
query = loads(args.query)
except:
parser.error("query must be valid json")
response = graph.elasticsearch_client.search(
index=args.index,
body=dict(query=query),
)
dump(response, stdout)
|
<commit_before>"""
CLI entry point hook.
"""
from argparse import ArgumentParser
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
<commit_msg>Add a query entry point<commit_after>"""
CLI entry point hook.
"""
from argparse import ArgumentParser
from json import dump, loads
from sys import stdout
def createall_main(graph):
"""
Initialize indexes and mappings.
"""
parser = ArgumentParser()
parser.add_argument("--only", action="append")
parser.add_argument("--skip", action="append")
parser.add_argument("-D", "--drop", action="store_true")
args = parser.parse_args()
graph.elasticsearch_index_registry.createall(
force=args.drop,
only=args.only,
skip=args.skip,
)
def query_main(graph, default_index):
parser = ArgumentParser()
parser.add_argument("--index", default=default_index)
parser.add_argument("--query", default='{"match_all": {}}')
args = parser.parse_args()
try:
query = loads(args.query)
except:
parser.error("query must be valid json")
response = graph.elasticsearch_client.search(
index=args.index,
body=dict(query=query),
)
dump(response, stdout)
|
9cf6e843eeb865eeaf90e4023bdccd1325e74535
|
test_rle.py
|
test_rle.py
|
import pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array([3, 1, 1, 2, 1, 3], dtype=cur_type))
|
import pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array([3, 1, 1, 2, 1, 3], dtype=cur_type))
def test_decompression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
input_values = np.array(np.random.randint(100, size=1000),
dtype=cur_type)
compressed = pypolycomp.rle_compress(input_values)
output_values = pypolycomp.rle_decompress(compressed)
assert np.all(input_values == output_values)
|
Add test for RLE decompression
|
Add test for RLE decompression
|
Python
|
bsd-3-clause
|
ziotom78/polycomp
|
import pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array([3, 1, 1, 2, 1, 3], dtype=cur_type))
Add test for RLE decompression
|
import pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array([3, 1, 1, 2, 1, 3], dtype=cur_type))
def test_decompression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
input_values = np.array(np.random.randint(100, size=1000),
dtype=cur_type)
compressed = pypolycomp.rle_compress(input_values)
output_values = pypolycomp.rle_decompress(compressed)
assert np.all(input_values == output_values)
|
<commit_before>import pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array([3, 1, 1, 2, 1, 3], dtype=cur_type))
<commit_msg>Add test for RLE decompression<commit_after>
|
import pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array([3, 1, 1, 2, 1, 3], dtype=cur_type))
def test_decompression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
input_values = np.array(np.random.randint(100, size=1000),
dtype=cur_type)
compressed = pypolycomp.rle_compress(input_values)
output_values = pypolycomp.rle_decompress(compressed)
assert np.all(input_values == output_values)
|
import pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array([3, 1, 1, 2, 1, 3], dtype=cur_type))
Add test for RLE decompressionimport pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array([3, 1, 1, 2, 1, 3], dtype=cur_type))
def test_decompression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
input_values = np.array(np.random.randint(100, size=1000),
dtype=cur_type)
compressed = pypolycomp.rle_compress(input_values)
output_values = pypolycomp.rle_decompress(compressed)
assert np.all(input_values == output_values)
|
<commit_before>import pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array([3, 1, 1, 2, 1, 3], dtype=cur_type))
<commit_msg>Add test for RLE decompression<commit_after>import pypolycomp
import numpy as np
def test_compression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
compressed = pypolycomp.rle_compress(np.array([1, 1, 1, 2, 3], dtype=cur_type))
assert np.all(compressed == np.array([3, 1, 1, 2, 1, 3], dtype=cur_type))
def test_decompression():
for cur_type in (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64):
input_values = np.array(np.random.randint(100, size=1000),
dtype=cur_type)
compressed = pypolycomp.rle_compress(input_values)
output_values = pypolycomp.rle_decompress(compressed)
assert np.all(input_values == output_values)
|
a5e5cef7793c0692e556fc8c09e03af8ad33566a
|
mne/datasets/sample/__init__.py
|
mne/datasets/sample/__init__.py
|
# Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
"""
archive_name = "MNE-sample-data-processed.tar.gz"
url = "ftp://surfer.nmr.mgh.harvard.edu/pub/data/" + archive_name
folder_name = "MNE-sample-data-processed"
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print "Downloading data, please Wait (600 MB)..."
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print "Decompressiong the archive: " + archive_name
tarfile.open(archive_name, "r:gz").extractall(path=path)
print
path = op.join(path, folder_name)
return path
|
# Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
"""
archive_name = "MNE-sample-data-processed.tar.gz"
url = "ftp://surfer.nmr.mgh.harvard.edu/pub/data/" + archive_name
folder_name = "MNE-sample-data"
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print "Downloading data, please Wait (600 MB)..."
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print "Decompressiong the archive: " + archive_name
tarfile.open(archive_name, "r:gz").extractall(path=path)
print
path = op.join(path, folder_name)
return path
|
FIX : in handling of sample dataset
|
FIX : in handling of sample dataset
|
Python
|
bsd-3-clause
|
aestrivex/mne-python,agramfort/mne-python,leggitta/mne-python,yousrabk/mne-python,larsoner/mne-python,teonlamont/mne-python,antiface/mne-python,cjayb/mne-python,mne-tools/mne-python,kambysese/mne-python,lorenzo-desantis/mne-python,jmontoyam/mne-python,kingjr/mne-python,dimkal/mne-python,agramfort/mne-python,nicproulx/mne-python,bloyl/mne-python,dgwakeman/mne-python,kingjr/mne-python,alexandrebarachant/mne-python,olafhauk/mne-python,jaeilepp/mne-python,cmoutard/mne-python,drammock/mne-python,jniediek/mne-python,leggitta/mne-python,olafhauk/mne-python,larsoner/mne-python,lorenzo-desantis/mne-python,kingjr/mne-python,cmoutard/mne-python,trachelr/mne-python,wronk/mne-python,jaeilepp/mne-python,pravsripad/mne-python,jmontoyam/mne-python,mne-tools/mne-python,aestrivex/mne-python,ARudiuk/mne-python,dimkal/mne-python,effigies/mne-python,pravsripad/mne-python,andyh616/mne-python,larsoner/mne-python,wmvanvliet/mne-python,antiface/mne-python,Teekuningas/mne-python,wmvanvliet/mne-python,matthew-tucker/mne-python,dgwakeman/mne-python,matthew-tucker/mne-python,adykstra/mne-python,wronk/mne-python,drammock/mne-python,kambysese/mne-python,mne-tools/mne-python,jniediek/mne-python,olafhauk/mne-python,andyh616/mne-python,rkmaddox/mne-python,adykstra/mne-python,effigies/mne-python,ARudiuk/mne-python,pravsripad/mne-python,Odingod/mne-python,alexandrebarachant/mne-python,Odingod/mne-python,wmvanvliet/mne-python,Teekuningas/mne-python,cjayb/mne-python,rkmaddox/mne-python,Eric89GXL/mne-python,yousrabk/mne-python,Eric89GXL/mne-python,trachelr/mne-python,drammock/mne-python,nicproulx/mne-python,teonlamont/mne-python,bloyl/mne-python,Teekuningas/mne-python
|
# Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
"""
archive_name = "MNE-sample-data-processed.tar.gz"
url = "ftp://surfer.nmr.mgh.harvard.edu/pub/data/" + archive_name
folder_name = "MNE-sample-data-processed"
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print "Downloading data, please Wait (600 MB)..."
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print "Decompressiong the archive: " + archive_name
tarfile.open(archive_name, "r:gz").extractall(path=path)
print
path = op.join(path, folder_name)
return path
FIX : in handling of sample dataset
|
# Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
"""
archive_name = "MNE-sample-data-processed.tar.gz"
url = "ftp://surfer.nmr.mgh.harvard.edu/pub/data/" + archive_name
folder_name = "MNE-sample-data"
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print "Downloading data, please Wait (600 MB)..."
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print "Decompressiong the archive: " + archive_name
tarfile.open(archive_name, "r:gz").extractall(path=path)
print
path = op.join(path, folder_name)
return path
|
<commit_before># Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
"""
archive_name = "MNE-sample-data-processed.tar.gz"
url = "ftp://surfer.nmr.mgh.harvard.edu/pub/data/" + archive_name
folder_name = "MNE-sample-data-processed"
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print "Downloading data, please Wait (600 MB)..."
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print "Decompressiong the archive: " + archive_name
tarfile.open(archive_name, "r:gz").extractall(path=path)
print
path = op.join(path, folder_name)
return path
<commit_msg>FIX : in handling of sample dataset<commit_after>
|
# Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
"""
archive_name = "MNE-sample-data-processed.tar.gz"
url = "ftp://surfer.nmr.mgh.harvard.edu/pub/data/" + archive_name
folder_name = "MNE-sample-data"
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print "Downloading data, please Wait (600 MB)..."
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print "Decompressiong the archive: " + archive_name
tarfile.open(archive_name, "r:gz").extractall(path=path)
print
path = op.join(path, folder_name)
return path
|
# Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
"""
archive_name = "MNE-sample-data-processed.tar.gz"
url = "ftp://surfer.nmr.mgh.harvard.edu/pub/data/" + archive_name
folder_name = "MNE-sample-data-processed"
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print "Downloading data, please Wait (600 MB)..."
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print "Decompressiong the archive: " + archive_name
tarfile.open(archive_name, "r:gz").extractall(path=path)
print
path = op.join(path, folder_name)
return path
FIX : in handling of sample dataset# Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
"""
archive_name = "MNE-sample-data-processed.tar.gz"
url = "ftp://surfer.nmr.mgh.harvard.edu/pub/data/" + archive_name
folder_name = "MNE-sample-data"
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print "Downloading data, please Wait (600 MB)..."
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print "Decompressiong the archive: " + archive_name
tarfile.open(archive_name, "r:gz").extractall(path=path)
print
path = op.join(path, folder_name)
return path
|
<commit_before># Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
"""
archive_name = "MNE-sample-data-processed.tar.gz"
url = "ftp://surfer.nmr.mgh.harvard.edu/pub/data/" + archive_name
folder_name = "MNE-sample-data-processed"
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print "Downloading data, please Wait (600 MB)..."
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print "Decompressiong the archive: " + archive_name
tarfile.open(archive_name, "r:gz").extractall(path=path)
print
path = op.join(path, folder_name)
return path
<commit_msg>FIX : in handling of sample dataset<commit_after># Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
"""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
"""
archive_name = "MNE-sample-data-processed.tar.gz"
url = "ftp://surfer.nmr.mgh.harvard.edu/pub/data/" + archive_name
folder_name = "MNE-sample-data"
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print "Downloading data, please Wait (600 MB)..."
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print "Decompressiong the archive: " + archive_name
tarfile.open(archive_name, "r:gz").extractall(path=path)
print
path = op.join(path, folder_name)
return path
|
bea9d879d648853c5bd4c54bfa0ec3af857c7887
|
ModuleInterface.py
|
ModuleInterface.py
|
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = 1
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2
|
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = ModuleAccessLevels.ANYONE
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2
|
Revert "[Core] Okay maybe this?"
|
Revert "[Core] Okay maybe this?"
This reverts commit 1fda217b32310c0db4e3a5e5b337071eeee376d1.
|
Python
|
mit
|
HubbeKing/Hubbot_Twisted
|
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = 1
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2Revert "[Core] Okay maybe this?"
This reverts commit 1fda217b32310c0db4e3a5e5b337071eeee376d1.
|
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = ModuleAccessLevels.ANYONE
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2
|
<commit_before>
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = 1
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2<commit_msg>Revert "[Core] Okay maybe this?"
This reverts commit 1fda217b32310c0db4e3a5e5b337071eeee376d1.<commit_after>
|
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = ModuleAccessLevels.ANYONE
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2
|
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = 1
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2Revert "[Core] Okay maybe this?"
This reverts commit 1fda217b32310c0db4e3a5e5b337071eeee376d1.
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = ModuleAccessLevels.ANYONE
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2
|
<commit_before>
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = 1
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2<commit_msg>Revert "[Core] Okay maybe this?"
This reverts commit 1fda217b32310c0db4e3a5e5b337071eeee376d1.<commit_after>
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
accessLevel = ModuleAccessLevels.ANYONE
def __init__(self, bot):
self.bot = bot
self.onLoad()
def onLoad(self):
pass
def onUnload(self):
pass
def shouldTrigger(self, message):
if message.Type not in self.acceptedTypes:
return False
if message.Command not in self.triggers:
return False
return True
def onTrigger(self, message):
pass
class ModuleAccessLevels(object):
ANYONE = 1
ADMINS = 2
|
8f247a0c4564af085bf6b3c9829d2892e818e565
|
tools/update_manifest.py
|
tools/update_manifest.py
|
#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
f.extractall()
|
#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
names = f.namelist()
if len(names) != 1:
raise Exception("too many entries: %s", names)
f.extractall(path=os.path.dirname(sys.argv[2]))
os.symlink(names[0], sys.argv[2])
|
Add a symlink to downloaded manifest.
|
Add a symlink to downloaded manifest.
|
Python
|
mit
|
zhirsch/destinykioskstatus,zhirsch/destinykioskstatus
|
#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
f.extractall()
Add a symlink to downloaded manifest.
|
#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
names = f.namelist()
if len(names) != 1:
raise Exception("too many entries: %s", names)
f.extractall(path=os.path.dirname(sys.argv[2]))
os.symlink(names[0], sys.argv[2])
|
<commit_before>#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
f.extractall()
<commit_msg>Add a symlink to downloaded manifest.<commit_after>
|
#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
names = f.namelist()
if len(names) != 1:
raise Exception("too many entries: %s", names)
f.extractall(path=os.path.dirname(sys.argv[2]))
os.symlink(names[0], sys.argv[2])
|
#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
f.extractall()
Add a symlink to downloaded manifest.#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
names = f.namelist()
if len(names) != 1:
raise Exception("too many entries: %s", names)
f.extractall(path=os.path.dirname(sys.argv[2]))
os.symlink(names[0], sys.argv[2])
|
<commit_before>#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
f.extractall()
<commit_msg>Add a symlink to downloaded manifest.<commit_after>#!/usr/bin/python
import json
import os
import sys
import tempfile
import urllib2
import zipfile
# Get the manifest urls.
req = urllib2.Request(
"https://www.bungie.net//platform/Destiny/Manifest/",
headers={'X-API-Key': sys.argv[1]},
)
resp = json.loads(urllib2.urlopen(req).read())
if resp['ErrorCode'] != 1:
raise Exception("error: %s", resp)
with tempfile.TemporaryFile() as tf:
# Download the zipped database.
path = resp['Response']['mobileWorldContentPaths']['en']
resp = urllib2.urlopen("https://www.bungie.net%s" % path)
while True:
chunk = resp.read(16 << 10)
if not chunk:
break
tf.write(chunk)
# Unzip the database to the current directory.
tf.seek(0)
with zipfile.ZipFile(tf, 'r') as f:
names = f.namelist()
if len(names) != 1:
raise Exception("too many entries: %s", names)
f.extractall(path=os.path.dirname(sys.argv[2]))
os.symlink(names[0], sys.argv[2])
|
d6bb78235b8cec2ec65a4fb67641746565f77c20
|
normandy/selfrepair/tests/test_views.py
|
normandy/selfrepair/tests/test_views.py
|
from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
|
from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
def test_sets_no_cookies(self, client):
res = client.get('/en-US/repair')
assert res.status_code == 200
assert res.client.cookies == {}
|
Test that self-repair endpoint does not set cookies
|
Test that self-repair endpoint does not set cookies
|
Python
|
mpl-2.0
|
mozilla/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy,mozilla/normandy,Osmose/normandy
|
from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
Test that self-repair endpoint does not set cookies
|
from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
def test_sets_no_cookies(self, client):
res = client.get('/en-US/repair')
assert res.status_code == 200
assert res.client.cookies == {}
|
<commit_before>from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
<commit_msg>Test that self-repair endpoint does not set cookies<commit_after>
|
from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
def test_sets_no_cookies(self, client):
res = client.get('/en-US/repair')
assert res.status_code == 200
assert res.client.cookies == {}
|
from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
Test that self-repair endpoint does not set cookiesfrom django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
def test_sets_no_cookies(self, client):
res = client.get('/en-US/repair')
assert res.status_code == 200
assert res.client.cookies == {}
|
<commit_before>from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
<commit_msg>Test that self-repair endpoint does not set cookies<commit_after>from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
def test_sets_no_cookies(self, client):
res = client.get('/en-US/repair')
assert res.status_code == 200
assert res.client.cookies == {}
|
78915664179c4c2b3fc974fcf54cfe253689c154
|
zinnia/tests/__init__.py
|
zinnia/tests/__init__.py
|
"""Unit tests for Zinnia"""
from zinnia.signals import disconnect_entry_signals
from zinnia.signals import disconnect_discussion_signals
disconnect_entry_signals()
disconnect_discussion_signals()
|
"""Unit tests for Zinnia"""
|
Remove disconnection of the signals when loading the zinnia.tests modules for compatibility
|
Remove disconnection of the signals when loading the zinnia.tests modules for compatibility
|
Python
|
bsd-3-clause
|
petecummings/django-blog-zinnia,bywbilly/django-blog-zinnia,ghachey/django-blog-zinnia,extertioner/django-blog-zinnia,1844144/django-blog-zinnia,Fantomas42/django-blog-zinnia,1844144/django-blog-zinnia,aorzh/django-blog-zinnia,extertioner/django-blog-zinnia,marctc/django-blog-zinnia,Zopieux/django-blog-zinnia,Maplecroft/django-blog-zinnia,aorzh/django-blog-zinnia,ZuluPro/django-blog-zinnia,ZuluPro/django-blog-zinnia,dapeng0802/django-blog-zinnia,1844144/django-blog-zinnia,ghachey/django-blog-zinnia,petecummings/django-blog-zinnia,dapeng0802/django-blog-zinnia,Maplecroft/django-blog-zinnia,extertioner/django-blog-zinnia,Fantomas42/django-blog-zinnia,aorzh/django-blog-zinnia,bywbilly/django-blog-zinnia,marctc/django-blog-zinnia,Maplecroft/django-blog-zinnia,bywbilly/django-blog-zinnia,ZuluPro/django-blog-zinnia,Fantomas42/django-blog-zinnia,Zopieux/django-blog-zinnia,petecummings/django-blog-zinnia,Zopieux/django-blog-zinnia,dapeng0802/django-blog-zinnia,marctc/django-blog-zinnia,ghachey/django-blog-zinnia
|
"""Unit tests for Zinnia"""
from zinnia.signals import disconnect_entry_signals
from zinnia.signals import disconnect_discussion_signals
disconnect_entry_signals()
disconnect_discussion_signals()
Remove disconnection of the signals when loading the zinnia.tests modules for compatibility
|
"""Unit tests for Zinnia"""
|
<commit_before>"""Unit tests for Zinnia"""
from zinnia.signals import disconnect_entry_signals
from zinnia.signals import disconnect_discussion_signals
disconnect_entry_signals()
disconnect_discussion_signals()
<commit_msg>Remove disconnection of the signals when loading the zinnia.tests modules for compatibility<commit_after>
|
"""Unit tests for Zinnia"""
|
"""Unit tests for Zinnia"""
from zinnia.signals import disconnect_entry_signals
from zinnia.signals import disconnect_discussion_signals
disconnect_entry_signals()
disconnect_discussion_signals()
Remove disconnection of the signals when loading the zinnia.tests modules for compatibility"""Unit tests for Zinnia"""
|
<commit_before>"""Unit tests for Zinnia"""
from zinnia.signals import disconnect_entry_signals
from zinnia.signals import disconnect_discussion_signals
disconnect_entry_signals()
disconnect_discussion_signals()
<commit_msg>Remove disconnection of the signals when loading the zinnia.tests modules for compatibility<commit_after>"""Unit tests for Zinnia"""
|
49d7f90ef4991bddea392ce1294bc952fc0e0b93
|
seaworthy/stream/_timeout.py
|
seaworthy/stream/_timeout.py
|
import threading
def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in seconds.
:param timeout_msg:
Message to raise in the exception when a timeout occurs.
"""
timed_out = threading.Event()
def timeout_func():
timed_out.set()
stream.close()
timer = threading.Timer(timeout, timeout_func)
try:
timer.start()
for item in stream:
yield item
# A timeout looks the same as the loop ending. So we need to check a
# flag to determine whether a timeout occurred or not.
if timed_out.is_set():
raise TimeoutError(timeout_msg)
finally:
timer.cancel()
# Close the stream's underlying response object (if it has one) to
# avoid potential socket leaks.
if hasattr(stream, '_response'):
stream._response.close()
|
import threading
def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in seconds.
:param timeout_msg:
Message to raise in the exception when a timeout occurs.
"""
timed_out = threading.Event()
def timeout_func():
timed_out.set()
stream.close()
timer = threading.Timer(timeout, timeout_func)
try:
timer.start()
for item in stream:
yield item
# A timeout looks the same as the loop ending. So we need to check a
# flag to determine whether a timeout occurred or not.
if timed_out.is_set():
raise TimeoutError(timeout_msg)
finally:
timer.cancel()
# Close the stream's underlying response object (if it has one) to
# avoid potential socket leaks.
# This method seems to have more success at preventing ResourceWarnings
# than just stream.close() (should this be improved upstream?)
# FIXME: Potential race condition if Timer thread closes the stream at
# the same time we do here, but hopefully not with serious side effects
if hasattr(stream, '_response'):
stream._response.close()
|
Add a comment about closing the stream
|
Add a comment about closing the stream
|
Python
|
bsd-3-clause
|
praekeltfoundation/seaworthy
|
import threading
def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in seconds.
:param timeout_msg:
Message to raise in the exception when a timeout occurs.
"""
timed_out = threading.Event()
def timeout_func():
timed_out.set()
stream.close()
timer = threading.Timer(timeout, timeout_func)
try:
timer.start()
for item in stream:
yield item
# A timeout looks the same as the loop ending. So we need to check a
# flag to determine whether a timeout occurred or not.
if timed_out.is_set():
raise TimeoutError(timeout_msg)
finally:
timer.cancel()
# Close the stream's underlying response object (if it has one) to
# avoid potential socket leaks.
if hasattr(stream, '_response'):
stream._response.close()
Add a comment about closing the stream
|
import threading
def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in seconds.
:param timeout_msg:
Message to raise in the exception when a timeout occurs.
"""
timed_out = threading.Event()
def timeout_func():
timed_out.set()
stream.close()
timer = threading.Timer(timeout, timeout_func)
try:
timer.start()
for item in stream:
yield item
# A timeout looks the same as the loop ending. So we need to check a
# flag to determine whether a timeout occurred or not.
if timed_out.is_set():
raise TimeoutError(timeout_msg)
finally:
timer.cancel()
# Close the stream's underlying response object (if it has one) to
# avoid potential socket leaks.
# This method seems to have more success at preventing ResourceWarnings
# than just stream.close() (should this be improved upstream?)
# FIXME: Potential race condition if Timer thread closes the stream at
# the same time we do here, but hopefully not with serious side effects
if hasattr(stream, '_response'):
stream._response.close()
|
<commit_before>import threading
def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in seconds.
:param timeout_msg:
Message to raise in the exception when a timeout occurs.
"""
timed_out = threading.Event()
def timeout_func():
timed_out.set()
stream.close()
timer = threading.Timer(timeout, timeout_func)
try:
timer.start()
for item in stream:
yield item
# A timeout looks the same as the loop ending. So we need to check a
# flag to determine whether a timeout occurred or not.
if timed_out.is_set():
raise TimeoutError(timeout_msg)
finally:
timer.cancel()
# Close the stream's underlying response object (if it has one) to
# avoid potential socket leaks.
if hasattr(stream, '_response'):
stream._response.close()
<commit_msg>Add a comment about closing the stream<commit_after>
|
import threading
def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in seconds.
:param timeout_msg:
Message to raise in the exception when a timeout occurs.
"""
timed_out = threading.Event()
def timeout_func():
timed_out.set()
stream.close()
timer = threading.Timer(timeout, timeout_func)
try:
timer.start()
for item in stream:
yield item
# A timeout looks the same as the loop ending. So we need to check a
# flag to determine whether a timeout occurred or not.
if timed_out.is_set():
raise TimeoutError(timeout_msg)
finally:
timer.cancel()
# Close the stream's underlying response object (if it has one) to
# avoid potential socket leaks.
# This method seems to have more success at preventing ResourceWarnings
# than just stream.close() (should this be improved upstream?)
# FIXME: Potential race condition if Timer thread closes the stream at
# the same time we do here, but hopefully not with serious side effects
if hasattr(stream, '_response'):
stream._response.close()
|
import threading
def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in seconds.
:param timeout_msg:
Message to raise in the exception when a timeout occurs.
"""
timed_out = threading.Event()
def timeout_func():
timed_out.set()
stream.close()
timer = threading.Timer(timeout, timeout_func)
try:
timer.start()
for item in stream:
yield item
# A timeout looks the same as the loop ending. So we need to check a
# flag to determine whether a timeout occurred or not.
if timed_out.is_set():
raise TimeoutError(timeout_msg)
finally:
timer.cancel()
# Close the stream's underlying response object (if it has one) to
# avoid potential socket leaks.
if hasattr(stream, '_response'):
stream._response.close()
Add a comment about closing the streamimport threading
def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in seconds.
:param timeout_msg:
Message to raise in the exception when a timeout occurs.
"""
timed_out = threading.Event()
def timeout_func():
timed_out.set()
stream.close()
timer = threading.Timer(timeout, timeout_func)
try:
timer.start()
for item in stream:
yield item
# A timeout looks the same as the loop ending. So we need to check a
# flag to determine whether a timeout occurred or not.
if timed_out.is_set():
raise TimeoutError(timeout_msg)
finally:
timer.cancel()
# Close the stream's underlying response object (if it has one) to
# avoid potential socket leaks.
# This method seems to have more success at preventing ResourceWarnings
# than just stream.close() (should this be improved upstream?)
# FIXME: Potential race condition if Timer thread closes the stream at
# the same time we do here, but hopefully not with serious side effects
if hasattr(stream, '_response'):
stream._response.close()
|
<commit_before>import threading
def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in seconds.
:param timeout_msg:
Message to raise in the exception when a timeout occurs.
"""
timed_out = threading.Event()
def timeout_func():
timed_out.set()
stream.close()
timer = threading.Timer(timeout, timeout_func)
try:
timer.start()
for item in stream:
yield item
# A timeout looks the same as the loop ending. So we need to check a
# flag to determine whether a timeout occurred or not.
if timed_out.is_set():
raise TimeoutError(timeout_msg)
finally:
timer.cancel()
# Close the stream's underlying response object (if it has one) to
# avoid potential socket leaks.
if hasattr(stream, '_response'):
stream._response.close()
<commit_msg>Add a comment about closing the stream<commit_after>import threading
def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in seconds.
:param timeout_msg:
Message to raise in the exception when a timeout occurs.
"""
timed_out = threading.Event()
def timeout_func():
timed_out.set()
stream.close()
timer = threading.Timer(timeout, timeout_func)
try:
timer.start()
for item in stream:
yield item
# A timeout looks the same as the loop ending. So we need to check a
# flag to determine whether a timeout occurred or not.
if timed_out.is_set():
raise TimeoutError(timeout_msg)
finally:
timer.cancel()
# Close the stream's underlying response object (if it has one) to
# avoid potential socket leaks.
# This method seems to have more success at preventing ResourceWarnings
# than just stream.close() (should this be improved upstream?)
# FIXME: Potential race condition if Timer thread closes the stream at
# the same time we do here, but hopefully not with serious side effects
if hasattr(stream, '_response'):
stream._response.close()
|
e4a7e8dea024a51036d66e2a357e83e7c085430e
|
opps/channels/tests/__init__.py
|
opps/channels/tests/__init__.py
|
# -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
|
# -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
from opps.channels.tests.test_forms import *
|
Add channel forms test in test case
|
Add channel forms test in test case
|
Python
|
mit
|
jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,williamroot/opps,williamroot/opps,williamroot/opps
|
# -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
Add channel forms test in test case
|
# -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
from opps.channels.tests.test_forms import *
|
<commit_before># -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
<commit_msg>Add channel forms test in test case<commit_after>
|
# -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
from opps.channels.tests.test_forms import *
|
# -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
Add channel forms test in test case# -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
from opps.channels.tests.test_forms import *
|
<commit_before># -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
<commit_msg>Add channel forms test in test case<commit_after># -*- coding: utf-8 -*-
from opps.channels.tests.test_context_processors import *
from opps.channels.tests.test_models import *
from opps.channels.tests.test_forms import *
|
c8efd29a8a47aa9c2612d9932dde704fe9b1cd6d
|
us_ignite/people/urls.py
|
us_ignite/people/urls.py
|
from django.conf.urls import patterns, url
urlpatterns = patterns(
'us_ignite.people.views',
url(r'^$', 'profile_list', name='profile_list'),
url(r'^(?P<slug>\w{1,32})/$', 'profile_detail', name='profile_detail'),
)
|
from django.conf.urls import patterns, url
urlpatterns = patterns(
'us_ignite.people.views',
url(r'^$', 'profile_list', name='profile_list'),
url(r'^(?P<slug>[-\w]{1,32})/$', 'profile_detail', name='profile_detail'),
)
|
Increase user ``Profile`` slug details.
|
Increase user ``Profile`` slug details.
The slug in the user profile accept ``-`` as well.
|
Python
|
bsd-3-clause
|
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
|
from django.conf.urls import patterns, url
urlpatterns = patterns(
'us_ignite.people.views',
url(r'^$', 'profile_list', name='profile_list'),
url(r'^(?P<slug>\w{1,32})/$', 'profile_detail', name='profile_detail'),
)
Increase user ``Profile`` slug details.
The slug in the user profile accept ``-`` as well.
|
from django.conf.urls import patterns, url
urlpatterns = patterns(
'us_ignite.people.views',
url(r'^$', 'profile_list', name='profile_list'),
url(r'^(?P<slug>[-\w]{1,32})/$', 'profile_detail', name='profile_detail'),
)
|
<commit_before>from django.conf.urls import patterns, url
urlpatterns = patterns(
'us_ignite.people.views',
url(r'^$', 'profile_list', name='profile_list'),
url(r'^(?P<slug>\w{1,32})/$', 'profile_detail', name='profile_detail'),
)
<commit_msg>Increase user ``Profile`` slug details.
The slug in the user profile accept ``-`` as well.<commit_after>
|
from django.conf.urls import patterns, url
urlpatterns = patterns(
'us_ignite.people.views',
url(r'^$', 'profile_list', name='profile_list'),
url(r'^(?P<slug>[-\w]{1,32})/$', 'profile_detail', name='profile_detail'),
)
|
from django.conf.urls import patterns, url
urlpatterns = patterns(
'us_ignite.people.views',
url(r'^$', 'profile_list', name='profile_list'),
url(r'^(?P<slug>\w{1,32})/$', 'profile_detail', name='profile_detail'),
)
Increase user ``Profile`` slug details.
The slug in the user profile accept ``-`` as well.from django.conf.urls import patterns, url
urlpatterns = patterns(
'us_ignite.people.views',
url(r'^$', 'profile_list', name='profile_list'),
url(r'^(?P<slug>[-\w]{1,32})/$', 'profile_detail', name='profile_detail'),
)
|
<commit_before>from django.conf.urls import patterns, url
urlpatterns = patterns(
'us_ignite.people.views',
url(r'^$', 'profile_list', name='profile_list'),
url(r'^(?P<slug>\w{1,32})/$', 'profile_detail', name='profile_detail'),
)
<commit_msg>Increase user ``Profile`` slug details.
The slug in the user profile accept ``-`` as well.<commit_after>from django.conf.urls import patterns, url
urlpatterns = patterns(
'us_ignite.people.views',
url(r'^$', 'profile_list', name='profile_list'),
url(r'^(?P<slug>[-\w]{1,32})/$', 'profile_detail', name='profile_detail'),
)
|
d8b9dec51e3d01fb662ed1bc779d06fe9f723cb5
|
openedx/core/djangoapps/content/course_overviews/management/commands/generate_course_overview.py
|
openedx/core/djangoapps/content/course_overviews/management/commands/generate_course_overview.py
|
"""
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
option_list = BaseCommand.option_list + (
make_option('--all',
action='store_true',
default=False,
help='Generate course overview for all courses.'),
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
|
"""
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
def add_arguments(self, parser):
"""
Add arguments to the command parser.
"""
parser.add_argument(
'--all',
action='store_true',
dest='all',
default=False,
help='Generate course overview for all courses.',
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
|
Update this command for Django 1.8
|
Update this command for Django 1.8
|
Python
|
agpl-3.0
|
louyihua/edx-platform,itsjeyd/edx-platform,solashirai/edx-platform,alu042/edx-platform,procangroup/edx-platform,Edraak/edraak-platform,jjmiranda/edx-platform,raccoongang/edx-platform,TeachAtTUM/edx-platform,jolyonb/edx-platform,raccoongang/edx-platform,shabab12/edx-platform,hastexo/edx-platform,eduNEXT/edunext-platform,chrisndodge/edx-platform,gymnasium/edx-platform,hastexo/edx-platform,alu042/edx-platform,antoviaque/edx-platform,cpennington/edx-platform,marcore/edx-platform,shabab12/edx-platform,kmoocdev2/edx-platform,devs1991/test_edx_docmode,gymnasium/edx-platform,Endika/edx-platform,marcore/edx-platform,ampax/edx-platform,analyseuc3m/ANALYSE-v1,pabloborrego93/edx-platform,defance/edx-platform,jzoldak/edx-platform,ahmedaljazzar/edx-platform,kmoocdev2/edx-platform,eduNEXT/edx-platform,longmen21/edx-platform,romain-li/edx-platform,lduarte1991/edx-platform,analyseuc3m/ANALYSE-v1,prarthitm/edxplatform,msegado/edx-platform,longmen21/edx-platform,alu042/edx-platform,ahmedaljazzar/edx-platform,amir-qayyum-khan/edx-platform,CredoReference/edx-platform,hastexo/edx-platform,ahmedaljazzar/edx-platform,EDUlib/edx-platform,devs1991/test_edx_docmode,arbrandes/edx-platform,waheedahmed/edx-platform,EDUlib/edx-platform,eduNEXT/edx-platform,deepsrijit1105/edx-platform,gsehub/edx-platform,eduNEXT/edunext-platform,miptliot/edx-platform,defance/edx-platform,defance/edx-platform,angelapper/edx-platform,louyihua/edx-platform,naresh21/synergetics-edx-platform,shabab12/edx-platform,prarthitm/edxplatform,teltek/edx-platform,chrisndodge/edx-platform,pepeportela/edx-platform,lduarte1991/edx-platform,amir-qayyum-khan/edx-platform,waheedahmed/edx-platform,mitocw/edx-platform,Livit/Livit.Learn.EdX,jjmiranda/edx-platform,TeachAtTUM/edx-platform,gsehub/edx-platform,cecep-edu/edx-platform,romain-li/edx-platform,synergeticsedx/deployment-wipro,gymnasium/edx-platform,philanthropy-u/edx-platform,UOMx/edx-platform,gymnasium/edx-platform,waheedahmed/edx-platform,lduarte1991/edx-platform,BehavioralInsightsTeam/edx-platform,pabloborrego93/edx-platform,analyseuc3m/ANALYSE-v1,a-parhom/edx-platform,angelapper/edx-platform,angelapper/edx-platform,teltek/edx-platform,proversity-org/edx-platform,CourseTalk/edx-platform,gsehub/edx-platform,deepsrijit1105/edx-platform,synergeticsedx/deployment-wipro,CredoReference/edx-platform,fintech-circle/edx-platform,mbareta/edx-platform-ft,appsembler/edx-platform,Livit/Livit.Learn.EdX,pabloborrego93/edx-platform,msegado/edx-platform,procangroup/edx-platform,Lektorium-LLC/edx-platform,proversity-org/edx-platform,UOMx/edx-platform,romain-li/edx-platform,eduNEXT/edx-platform,Stanford-Online/edx-platform,CredoReference/edx-platform,antoviaque/edx-platform,CredoReference/edx-platform,proversity-org/edx-platform,Stanford-Online/edx-platform,fintech-circle/edx-platform,teltek/edx-platform,kmoocdev2/edx-platform,pepeportela/edx-platform,caesar2164/edx-platform,10clouds/edx-platform,stvstnfrd/edx-platform,synergeticsedx/deployment-wipro,edx/edx-platform,edx-solutions/edx-platform,pepeportela/edx-platform,philanthropy-u/edx-platform,edx/edx-platform,Endika/edx-platform,naresh21/synergetics-edx-platform,caesar2164/edx-platform,analyseuc3m/ANALYSE-v1,prarthitm/edxplatform,raccoongang/edx-platform,appsembler/edx-platform,solashirai/edx-platform,msegado/edx-platform,edx/edx-platform,jolyonb/edx-platform,amir-qayyum-khan/edx-platform,amir-qayyum-khan/edx-platform,Stanford-Online/edx-platform,procangroup/edx-platform,10clouds/edx-platform,EDUlib/edx-platform,edx-solutions/edx-platform,stvstnfrd/edx-platform,stvstnfrd/edx-platform,synergeticsedx/deployment-wipro,Lektorium-LLC/edx-platform,kmoocdev2/edx-platform,ESOedX/edx-platform,pabloborrego93/edx-platform,arbrandes/edx-platform,solashirai/edx-platform,CourseTalk/edx-platform,devs1991/test_edx_docmode,proversity-org/edx-platform,miptliot/edx-platform,Lektorium-LLC/edx-platform,fintech-circle/edx-platform,Endika/edx-platform,Edraak/edraak-platform,jjmiranda/edx-platform,devs1991/test_edx_docmode,UOMx/edx-platform,angelapper/edx-platform,msegado/edx-platform,marcore/edx-platform,10clouds/edx-platform,naresh21/synergetics-edx-platform,devs1991/test_edx_docmode,arbrandes/edx-platform,cpennington/edx-platform,deepsrijit1105/edx-platform,cpennington/edx-platform,JioEducation/edx-platform,itsjeyd/edx-platform,CourseTalk/edx-platform,devs1991/test_edx_docmode,eduNEXT/edunext-platform,edx/edx-platform,jzoldak/edx-platform,longmen21/edx-platform,shabab12/edx-platform,BehavioralInsightsTeam/edx-platform,prarthitm/edxplatform,ESOedX/edx-platform,itsjeyd/edx-platform,raccoongang/edx-platform,Livit/Livit.Learn.EdX,gsehub/edx-platform,jolyonb/edx-platform,tanmaykm/edx-platform,marcore/edx-platform,caesar2164/edx-platform,JioEducation/edx-platform,deepsrijit1105/edx-platform,procangroup/edx-platform,tanmaykm/edx-platform,caesar2164/edx-platform,romain-li/edx-platform,cecep-edu/edx-platform,eduNEXT/edx-platform,JioEducation/edx-platform,solashirai/edx-platform,ESOedX/edx-platform,Edraak/edraak-platform,alu042/edx-platform,TeachAtTUM/edx-platform,BehavioralInsightsTeam/edx-platform,tanmaykm/edx-platform,10clouds/edx-platform,mbareta/edx-platform-ft,msegado/edx-platform,edx-solutions/edx-platform,mitocw/edx-platform,devs1991/test_edx_docmode,miptliot/edx-platform,arbrandes/edx-platform,philanthropy-u/edx-platform,louyihua/edx-platform,fintech-circle/edx-platform,mitocw/edx-platform,mitocw/edx-platform,tanmaykm/edx-platform,cecep-edu/edx-platform,philanthropy-u/edx-platform,TeachAtTUM/edx-platform,pepeportela/edx-platform,lduarte1991/edx-platform,Livit/Livit.Learn.EdX,ampax/edx-platform,jolyonb/edx-platform,appsembler/edx-platform,solashirai/edx-platform,ampax/edx-platform,antoviaque/edx-platform,a-parhom/edx-platform,Endika/edx-platform,cecep-edu/edx-platform,eduNEXT/edunext-platform,waheedahmed/edx-platform,mbareta/edx-platform-ft,edx-solutions/edx-platform,stvstnfrd/edx-platform,a-parhom/edx-platform,chrisndodge/edx-platform,defance/edx-platform,cecep-edu/edx-platform,Lektorium-LLC/edx-platform,Stanford-Online/edx-platform,chrisndodge/edx-platform,devs1991/test_edx_docmode,cpennington/edx-platform,jjmiranda/edx-platform,miptliot/edx-platform,waheedahmed/edx-platform,Edraak/edraak-platform,UOMx/edx-platform,CourseTalk/edx-platform,ahmedaljazzar/edx-platform,EDUlib/edx-platform,longmen21/edx-platform,romain-li/edx-platform,hastexo/edx-platform,jzoldak/edx-platform,longmen21/edx-platform,naresh21/synergetics-edx-platform,itsjeyd/edx-platform,BehavioralInsightsTeam/edx-platform,jzoldak/edx-platform,JioEducation/edx-platform,ESOedX/edx-platform,ampax/edx-platform,teltek/edx-platform,appsembler/edx-platform,louyihua/edx-platform,mbareta/edx-platform-ft,kmoocdev2/edx-platform,antoviaque/edx-platform,a-parhom/edx-platform
|
"""
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
option_list = BaseCommand.option_list + (
make_option('--all',
action='store_true',
default=False,
help='Generate course overview for all courses.'),
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
Update this command for Django 1.8
|
"""
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
def add_arguments(self, parser):
"""
Add arguments to the command parser.
"""
parser.add_argument(
'--all',
action='store_true',
dest='all',
default=False,
help='Generate course overview for all courses.',
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
|
<commit_before>"""
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
option_list = BaseCommand.option_list + (
make_option('--all',
action='store_true',
default=False,
help='Generate course overview for all courses.'),
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
<commit_msg>Update this command for Django 1.8<commit_after>
|
"""
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
def add_arguments(self, parser):
"""
Add arguments to the command parser.
"""
parser.add_argument(
'--all',
action='store_true',
dest='all',
default=False,
help='Generate course overview for all courses.',
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
|
"""
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
option_list = BaseCommand.option_list + (
make_option('--all',
action='store_true',
default=False,
help='Generate course overview for all courses.'),
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
Update this command for Django 1.8"""
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
def add_arguments(self, parser):
"""
Add arguments to the command parser.
"""
parser.add_argument(
'--all',
action='store_true',
dest='all',
default=False,
help='Generate course overview for all courses.',
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
|
<commit_before>"""
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
option_list = BaseCommand.option_list + (
make_option('--all',
action='store_true',
default=False,
help='Generate course overview for all courses.'),
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
<commit_msg>Update this command for Django 1.8<commit_after>"""
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Example usage:
$ ./manage.py lms generate_course_overview --all --settings=devstack
$ ./manage.py lms generate_course_overview 'edX/DemoX/Demo_Course' --settings=devstack
"""
args = '<course_id course_id ...>'
help = 'Generates and stores course overview for one or more courses.'
def add_arguments(self, parser):
"""
Add arguments to the command parser.
"""
parser.add_argument(
'--all',
action='store_true',
dest='all',
default=False,
help='Generate course overview for all courses.',
)
def handle(self, *args, **options):
if options['all']:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
if len(args) < 1:
raise CommandError('At least one course or --all must be specified.')
try:
course_keys = [CourseKey.from_string(arg) for arg in args]
except InvalidKeyError:
raise CommandError('Invalid key specified.')
CourseOverview.get_select_courses(course_keys)
|
bea572a086a9d8390a8e5fce5a275b889fa52338
|
pymetabiosis/test/test_numpy_convert.py
|
pymetabiosis/test/test_numpy_convert.py
|
from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
numpy = import_module("numpy")
assert numpy.bool_(True) is True
assert numpy.bool_(False) is False
assert numpy.int8(10) == 10
assert numpy.int16(-10) == -10
assert numpy.int32(2**31-1) == 2**31-1
assert numpy.int64(42) == 42
assert numpy.float16(10.0) == 10.0
assert numpy.float32(-10) == -10.0
assert numpy.float64(42.0) == 42.0
assert numpy.float128(-42.0) == -42.0
|
import pytest
from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
try:
numpy = import_module("numpy")
except ImportError:
pytest.skip("numpy isn't installed on the cpython side")
assert numpy.bool_(True) is True
assert numpy.bool_(False) is False
assert numpy.int8(10) == 10
assert numpy.int16(-10) == -10
assert numpy.int32(2**31-1) == 2**31-1
assert numpy.int64(42) == 42
assert numpy.float16(10.0) == 10.0
assert numpy.float32(-10) == -10.0
assert numpy.float64(42.0) == 42.0
if hasattr(numpy, "float128"):
assert numpy.float128(-42.0) == -42.0
|
Make sure numpy exists on the cpython side
|
Make sure numpy exists on the cpython side
|
Python
|
mit
|
prabhuramachandran/pymetabiosis,rguillebert/pymetabiosis
|
from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
numpy = import_module("numpy")
assert numpy.bool_(True) is True
assert numpy.bool_(False) is False
assert numpy.int8(10) == 10
assert numpy.int16(-10) == -10
assert numpy.int32(2**31-1) == 2**31-1
assert numpy.int64(42) == 42
assert numpy.float16(10.0) == 10.0
assert numpy.float32(-10) == -10.0
assert numpy.float64(42.0) == 42.0
assert numpy.float128(-42.0) == -42.0
Make sure numpy exists on the cpython side
|
import pytest
from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
try:
numpy = import_module("numpy")
except ImportError:
pytest.skip("numpy isn't installed on the cpython side")
assert numpy.bool_(True) is True
assert numpy.bool_(False) is False
assert numpy.int8(10) == 10
assert numpy.int16(-10) == -10
assert numpy.int32(2**31-1) == 2**31-1
assert numpy.int64(42) == 42
assert numpy.float16(10.0) == 10.0
assert numpy.float32(-10) == -10.0
assert numpy.float64(42.0) == 42.0
if hasattr(numpy, "float128"):
assert numpy.float128(-42.0) == -42.0
|
<commit_before>from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
numpy = import_module("numpy")
assert numpy.bool_(True) is True
assert numpy.bool_(False) is False
assert numpy.int8(10) == 10
assert numpy.int16(-10) == -10
assert numpy.int32(2**31-1) == 2**31-1
assert numpy.int64(42) == 42
assert numpy.float16(10.0) == 10.0
assert numpy.float32(-10) == -10.0
assert numpy.float64(42.0) == 42.0
assert numpy.float128(-42.0) == -42.0
<commit_msg>Make sure numpy exists on the cpython side<commit_after>
|
import pytest
from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
try:
numpy = import_module("numpy")
except ImportError:
pytest.skip("numpy isn't installed on the cpython side")
assert numpy.bool_(True) is True
assert numpy.bool_(False) is False
assert numpy.int8(10) == 10
assert numpy.int16(-10) == -10
assert numpy.int32(2**31-1) == 2**31-1
assert numpy.int64(42) == 42
assert numpy.float16(10.0) == 10.0
assert numpy.float32(-10) == -10.0
assert numpy.float64(42.0) == 42.0
if hasattr(numpy, "float128"):
assert numpy.float128(-42.0) == -42.0
|
from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
numpy = import_module("numpy")
assert numpy.bool_(True) is True
assert numpy.bool_(False) is False
assert numpy.int8(10) == 10
assert numpy.int16(-10) == -10
assert numpy.int32(2**31-1) == 2**31-1
assert numpy.int64(42) == 42
assert numpy.float16(10.0) == 10.0
assert numpy.float32(-10) == -10.0
assert numpy.float64(42.0) == 42.0
assert numpy.float128(-42.0) == -42.0
Make sure numpy exists on the cpython sideimport pytest
from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
try:
numpy = import_module("numpy")
except ImportError:
pytest.skip("numpy isn't installed on the cpython side")
assert numpy.bool_(True) is True
assert numpy.bool_(False) is False
assert numpy.int8(10) == 10
assert numpy.int16(-10) == -10
assert numpy.int32(2**31-1) == 2**31-1
assert numpy.int64(42) == 42
assert numpy.float16(10.0) == 10.0
assert numpy.float32(-10) == -10.0
assert numpy.float64(42.0) == 42.0
if hasattr(numpy, "float128"):
assert numpy.float128(-42.0) == -42.0
|
<commit_before>from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
numpy = import_module("numpy")
assert numpy.bool_(True) is True
assert numpy.bool_(False) is False
assert numpy.int8(10) == 10
assert numpy.int16(-10) == -10
assert numpy.int32(2**31-1) == 2**31-1
assert numpy.int64(42) == 42
assert numpy.float16(10.0) == 10.0
assert numpy.float32(-10) == -10.0
assert numpy.float64(42.0) == 42.0
assert numpy.float128(-42.0) == -42.0
<commit_msg>Make sure numpy exists on the cpython side<commit_after>import pytest
from pymetabiosis.module import import_module
from pymetabiosis.numpy_convert import \
register_cpy_numpy_to_pypy_builtin_converters
register_cpy_numpy_to_pypy_builtin_converters()
def test_scalar_converter():
try:
numpy = import_module("numpy")
except ImportError:
pytest.skip("numpy isn't installed on the cpython side")
assert numpy.bool_(True) is True
assert numpy.bool_(False) is False
assert numpy.int8(10) == 10
assert numpy.int16(-10) == -10
assert numpy.int32(2**31-1) == 2**31-1
assert numpy.int64(42) == 42
assert numpy.float16(10.0) == 10.0
assert numpy.float32(-10) == -10.0
assert numpy.float64(42.0) == 42.0
if hasattr(numpy, "float128"):
assert numpy.float128(-42.0) == -42.0
|
68f50e83f4b06d3e45bfe1610d50d88e73bde8af
|
examples/load_table_from_url.py
|
examples/load_table_from_url.py
|
#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks",
"html")
with open("hoge.rst", "w", encoding="utf-8") as f:
for table_data in loader.load():
print("{:s}".format(table_data.dumps()))
f.write(table_data.dumps())
|
#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import io
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks",
"html")
with io.open("hoge.rst", "w", encoding=loader.encoding) as f:
for table_data in loader.load():
print("{:s}".format(table_data.dumps()))
f.write(table_data.dumps())
|
Fix for python 2 compatibility
|
Fix for python 2 compatibility
|
Python
|
mit
|
thombashi/pytablereader,thombashi/pytablereader,thombashi/pytablereader
|
#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks",
"html")
with open("hoge.rst", "w", encoding="utf-8") as f:
for table_data in loader.load():
print("{:s}".format(table_data.dumps()))
f.write(table_data.dumps())
Fix for python 2 compatibility
|
#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import io
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks",
"html")
with io.open("hoge.rst", "w", encoding=loader.encoding) as f:
for table_data in loader.load():
print("{:s}".format(table_data.dumps()))
f.write(table_data.dumps())
|
<commit_before>#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks",
"html")
with open("hoge.rst", "w", encoding="utf-8") as f:
for table_data in loader.load():
print("{:s}".format(table_data.dumps()))
f.write(table_data.dumps())
<commit_msg>Fix for python 2 compatibility<commit_after>
|
#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import io
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks",
"html")
with io.open("hoge.rst", "w", encoding=loader.encoding) as f:
for table_data in loader.load():
print("{:s}".format(table_data.dumps()))
f.write(table_data.dumps())
|
#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks",
"html")
with open("hoge.rst", "w", encoding="utf-8") as f:
for table_data in loader.load():
print("{:s}".format(table_data.dumps()))
f.write(table_data.dumps())
Fix for python 2 compatibility#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import io
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks",
"html")
with io.open("hoge.rst", "w", encoding=loader.encoding) as f:
for table_data in loader.load():
print("{:s}".format(table_data.dumps()))
f.write(table_data.dumps())
|
<commit_before>#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks",
"html")
with open("hoge.rst", "w", encoding="utf-8") as f:
for table_data in loader.load():
print("{:s}".format(table_data.dumps()))
f.write(table_data.dumps())
<commit_msg>Fix for python 2 compatibility<commit_after>#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import io
import pytablereader
print("\n".join([
"load from URL",
"==============",
]))
loader = pytablereader.TableUrlLoader(
"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks",
"html")
with io.open("hoge.rst", "w", encoding=loader.encoding) as f:
for table_data in loader.load():
print("{:s}".format(table_data.dumps()))
f.write(table_data.dumps())
|
78c70c0bdcf3b264cf522136ae35bc1ec5b12b62
|
tests/test_basic.py
|
tests/test_basic.py
|
import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--defaultsettings', '--test','examples/CountWords/']
pubrunner.command_line.main()
def test_textminingcounter():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--defaultsettings', '--test','examples/TextMiningCounter/']
pubrunner.command_line.main()
|
import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
parentDir = os.path.dirname(os.path.abspath(__file__))
projectPath = os.path.join(parentDir,'examples','CountWords')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line.main()
def test_textminingcounter():
parentDir = os.path.dirname(os.path.abspath(__file__))
projectPath = os.path.join(parentDir,'examples','TextMiningCount')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line.main()
|
Use absolute path for running tests
|
Use absolute path for running tests
|
Python
|
mit
|
jakelever/pubrunner,jakelever/pubrunner
|
import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--defaultsettings', '--test','examples/CountWords/']
pubrunner.command_line.main()
def test_textminingcounter():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--defaultsettings', '--test','examples/TextMiningCounter/']
pubrunner.command_line.main()
Use absolute path for running tests
|
import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
parentDir = os.path.dirname(os.path.abspath(__file__))
projectPath = os.path.join(parentDir,'examples','CountWords')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line.main()
def test_textminingcounter():
parentDir = os.path.dirname(os.path.abspath(__file__))
projectPath = os.path.join(parentDir,'examples','TextMiningCount')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line.main()
|
<commit_before>import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--defaultsettings', '--test','examples/CountWords/']
pubrunner.command_line.main()
def test_textminingcounter():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--defaultsettings', '--test','examples/TextMiningCounter/']
pubrunner.command_line.main()
<commit_msg>Use absolute path for running tests<commit_after>
|
import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
parentDir = os.path.dirname(os.path.abspath(__file__))
projectPath = os.path.join(parentDir,'examples','CountWords')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line.main()
def test_textminingcounter():
parentDir = os.path.dirname(os.path.abspath(__file__))
projectPath = os.path.join(parentDir,'examples','TextMiningCount')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line.main()
|
import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--defaultsettings', '--test','examples/CountWords/']
pubrunner.command_line.main()
def test_textminingcounter():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--defaultsettings', '--test','examples/TextMiningCounter/']
pubrunner.command_line.main()
Use absolute path for running testsimport sys
import pubrunner
import pubrunner.command_line
def test_countwords():
parentDir = os.path.dirname(os.path.abspath(__file__))
projectPath = os.path.join(parentDir,'examples','CountWords')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line.main()
def test_textminingcounter():
parentDir = os.path.dirname(os.path.abspath(__file__))
projectPath = os.path.join(parentDir,'examples','TextMiningCount')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line.main()
|
<commit_before>import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--defaultsettings', '--test','examples/CountWords/']
pubrunner.command_line.main()
def test_textminingcounter():
#pubrunner.pubrun('examples/CountWords/',True,True)
sys.argv = ['pubrunner', '--defaultsettings', '--test','examples/TextMiningCounter/']
pubrunner.command_line.main()
<commit_msg>Use absolute path for running tests<commit_after>import sys
import pubrunner
import pubrunner.command_line
def test_countwords():
parentDir = os.path.dirname(os.path.abspath(__file__))
projectPath = os.path.join(parentDir,'examples','CountWords')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line.main()
def test_textminingcounter():
parentDir = os.path.dirname(os.path.abspath(__file__))
projectPath = os.path.join(parentDir,'examples','TextMiningCount')
sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
pubrunner.command_line.main()
|
80676409b706f3927b463afef6aa844d00aeb107
|
pymatgen/core/__init__.py
|
pymatgen/core/__init__.py
|
"""
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .lattice import *
from .sites import *
from .operations import *
|
"""
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .lattice import *
from .sites import *
from .operations import *
from .units import *
|
Add units to Core import.
|
Add units to Core import.
|
Python
|
mit
|
migueldiascosta/pymatgen,Bismarrck/pymatgen,sonium0/pymatgen,ctoher/pymatgen,Bismarrck/pymatgen,migueldiascosta/pymatgen,sonium0/pymatgen,migueldiascosta/pymatgen,yanikou19/pymatgen,Bismarrck/pymatgen,rousseab/pymatgen,Bismarrck/pymatgen,rousseab/pymatgen,rousseab/pymatgen,sonium0/pymatgen,yanikou19/pymatgen,Dioptas/pymatgen,Dioptas/pymatgen,ctoher/pymatgen,yanikou19/pymatgen,ctoher/pymatgen,Bismarrck/pymatgen
|
"""
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .lattice import *
from .sites import *
from .operations import *
Add units to Core import.
|
"""
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .lattice import *
from .sites import *
from .operations import *
from .units import *
|
<commit_before>"""
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .lattice import *
from .sites import *
from .operations import *
<commit_msg>Add units to Core import.<commit_after>
|
"""
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .lattice import *
from .sites import *
from .operations import *
from .units import *
|
"""
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .lattice import *
from .sites import *
from .operations import *
Add units to Core import."""
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .lattice import *
from .sites import *
from .operations import *
from .units import *
|
<commit_before>"""
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .lattice import *
from .sites import *
from .operations import *
<commit_msg>Add units to Core import.<commit_after>"""
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .lattice import *
from .sites import *
from .operations import *
from .units import *
|
900fa2acbdb4cde05ab26cb134d95870d68ce004
|
salt/states/host.py
|
salt/states/host.py
|
'''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
|
'''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already present'.format(name)
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already absent'.format(name)
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
|
Clean up strings to use format and add better comments
|
Clean up strings to use format and add better comments
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
'''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
Clean up strings to use format and add better comments
|
'''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already present'.format(name)
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already absent'.format(name)
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
|
<commit_before>'''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
<commit_msg>Clean up strings to use format and add better comments<commit_after>
|
'''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already present'.format(name)
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already absent'.format(name)
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
|
'''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
Clean up strings to use format and add better comments'''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already present'.format(name)
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already absent'.format(name)
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
|
<commit_before>'''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host ' + name
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
<commit_msg>Clean up strings to use format and add better comments<commit_after>'''
Manage the state of the hosts file
'''
def present(name, ip):
'''
Ensures that the named host is present with the given ip
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already present'.format(name)
return ret
if __salt__['hosts.add_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Added host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to set host'
return ret
def absent(name, ip):
'''
Ensure that the the named host is absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['hosts.has_pair'](ip, name):
ret['result'] = True
ret['comment'] = 'Host {0} already absent'.format(name)
return ret
if __salt__['hosts.rm_host'](ip, name):
ret['changes'] = {'host': name}
ret['result'] = True
ret['comment'] = 'Removed host {0}'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to remove host'
return ret
|
f1d48525f1e8cde2af9a49636f38360b87b0ecb6
|
function/univariate_function.py
|
function/univariate_function.py
|
"""
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abstractmethod
def eval(self, v):
pass
@property
@abstractmethod
def domain_start(self):
pass
@property
@abstractmethod
def domain_end(self):
pass
|
"""
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abstractmethod
def eval(self, v):
"""
Evaluate the univariate function with input v, and return that value
:param v: Typically some kind of numeric.
:return:
"""
pass
@property
@abstractmethod
def domain_start(self):
"""
Return the start value of the domain.
:return:
"""
pass
@property
@abstractmethod
def domain_end(self):
"""
Return the end value of the domain.
:return:
"""
pass
|
Add comments to abstract methods.
|
Add comments to abstract methods.
|
Python
|
mit
|
dpazel/music_rep
|
"""
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abstractmethod
def eval(self, v):
pass
@property
@abstractmethod
def domain_start(self):
pass
@property
@abstractmethod
def domain_end(self):
pass
Add comments to abstract methods.
|
"""
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abstractmethod
def eval(self, v):
"""
Evaluate the univariate function with input v, and return that value
:param v: Typically some kind of numeric.
:return:
"""
pass
@property
@abstractmethod
def domain_start(self):
"""
Return the start value of the domain.
:return:
"""
pass
@property
@abstractmethod
def domain_end(self):
"""
Return the end value of the domain.
:return:
"""
pass
|
<commit_before>"""
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abstractmethod
def eval(self, v):
pass
@property
@abstractmethod
def domain_start(self):
pass
@property
@abstractmethod
def domain_end(self):
pass
<commit_msg>Add comments to abstract methods.<commit_after>
|
"""
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abstractmethod
def eval(self, v):
"""
Evaluate the univariate function with input v, and return that value
:param v: Typically some kind of numeric.
:return:
"""
pass
@property
@abstractmethod
def domain_start(self):
"""
Return the start value of the domain.
:return:
"""
pass
@property
@abstractmethod
def domain_end(self):
"""
Return the end value of the domain.
:return:
"""
pass
|
"""
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abstractmethod
def eval(self, v):
pass
@property
@abstractmethod
def domain_start(self):
pass
@property
@abstractmethod
def domain_end(self):
pass
Add comments to abstract methods."""
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abstractmethod
def eval(self, v):
"""
Evaluate the univariate function with input v, and return that value
:param v: Typically some kind of numeric.
:return:
"""
pass
@property
@abstractmethod
def domain_start(self):
"""
Return the start value of the domain.
:return:
"""
pass
@property
@abstractmethod
def domain_end(self):
"""
Return the end value of the domain.
:return:
"""
pass
|
<commit_before>"""
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abstractmethod
def eval(self, v):
pass
@property
@abstractmethod
def domain_start(self):
pass
@property
@abstractmethod
def domain_end(self):
pass
<commit_msg>Add comments to abstract methods.<commit_after>"""
File: univariate_function.py
Purpose: Class that defines a generic (abstract) univariate function.
"""
from abc import ABC, abstractmethod
class UnivariateFunction(ABC):
"""
Class that defines a generic (abstract) univariate function.
"""
def __init(self):
super().__init__()
@abstractmethod
def eval(self, v):
"""
Evaluate the univariate function with input v, and return that value
:param v: Typically some kind of numeric.
:return:
"""
pass
@property
@abstractmethod
def domain_start(self):
"""
Return the start value of the domain.
:return:
"""
pass
@property
@abstractmethod
def domain_end(self):
"""
Return the end value of the domain.
:return:
"""
pass
|
0e4641734f101d0d972d66b05c19a5c2dc8043e1
|
journal/tests/test_activity.py
|
journal/tests/test_activity.py
|
import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='CA', learning_obj='123',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
|
import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='1', learning_obj='1,2,3',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
|
Fix Activity CSV field test
|
Fix Activity CSV field test
|
Python
|
apache-2.0
|
WildCAS/CASCategorization,WildCAS/CASCategorization,WildCAS/CASCategorization
|
import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='CA', learning_obj='123',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
Fix Activity CSV field test
|
import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='1', learning_obj='1,2,3',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
|
<commit_before>import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='CA', learning_obj='123',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
<commit_msg>Fix Activity CSV field test<commit_after>
|
import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='1', learning_obj='1,2,3',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
|
import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='CA', learning_obj='123',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
Fix Activity CSV field testimport datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='1', learning_obj='1,2,3',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
|
<commit_before>import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='CA', learning_obj='123',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
<commit_msg>Fix Activity CSV field test<commit_after>import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='1', learning_obj='1,2,3',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
|
bea0006566cb5512f1ae515689111339be27e42b
|
tk/material/apps.py
|
tk/material/apps.py
|
from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated titles and descriptions into the search index.
The translated fields are stored as metadata.
"""
@property
def store(self):
return ['title', 'urls', 'brief']
def _join_translations(self, field: LocalizedField) -> str:
return ' '.join([v for v in field.values() if v is not None])
def get_title(self, obj):
return self._join_translations(getattr(obj, 'title'))
def get_description(self, obj):
return self._join_translations(getattr(obj, 'brief'))
def urls(self, obj):
urls = {}
for lang, _ in settings.LANGUAGES:
translation.activate(lang)
urls[lang] = obj.get_absolute_url()
return urls
def get_url(self, obj):
# URLs are localized, cannot store in a text field
return ''
class MaterialConfig(AppConfig):
name = 'tk.material'
def ready(self):
for mn in ['Activity', 'Reading', 'Video', 'Link']:
m = self.get_model(mn)
search.register(m.objects.approved(), MaterialSearchAdapter)
|
from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated titles and descriptions into the search index.
The translated fields are stored as metadata.
"""
@property
def store(self):
return ['title', 'urls', 'brief']
def _join_translations(self, field: LocalizedField) -> str:
return ' '.join([v for v in field.values() if v is not None])
def get_title(self, obj):
return self._join_translations(getattr(obj, 'title'))
def get_description(self, obj):
return self._join_translations(getattr(obj, 'brief'))
def urls(self, obj):
urls = {}
for lang, _ in settings.LANGUAGES:
with translation.override(lang):
urls[lang] = obj.get_absolute_url()
return urls
def get_url(self, obj):
# URLs are localized, cannot store in a text field
return ''
class MaterialConfig(AppConfig):
name = 'tk.material'
def ready(self):
for mn in ['Activity', 'Reading', 'Video', 'Link']:
m = self.get_model(mn)
search.register(m.objects.approved(), MaterialSearchAdapter)
|
Change current language only within context when building search indexes
|
Change current language only within context when building search indexes
|
Python
|
agpl-3.0
|
GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa
|
from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated titles and descriptions into the search index.
The translated fields are stored as metadata.
"""
@property
def store(self):
return ['title', 'urls', 'brief']
def _join_translations(self, field: LocalizedField) -> str:
return ' '.join([v for v in field.values() if v is not None])
def get_title(self, obj):
return self._join_translations(getattr(obj, 'title'))
def get_description(self, obj):
return self._join_translations(getattr(obj, 'brief'))
def urls(self, obj):
urls = {}
for lang, _ in settings.LANGUAGES:
translation.activate(lang)
urls[lang] = obj.get_absolute_url()
return urls
def get_url(self, obj):
# URLs are localized, cannot store in a text field
return ''
class MaterialConfig(AppConfig):
name = 'tk.material'
def ready(self):
for mn in ['Activity', 'Reading', 'Video', 'Link']:
m = self.get_model(mn)
search.register(m.objects.approved(), MaterialSearchAdapter)
Change current language only within context when building search indexes
|
from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated titles and descriptions into the search index.
The translated fields are stored as metadata.
"""
@property
def store(self):
return ['title', 'urls', 'brief']
def _join_translations(self, field: LocalizedField) -> str:
return ' '.join([v for v in field.values() if v is not None])
def get_title(self, obj):
return self._join_translations(getattr(obj, 'title'))
def get_description(self, obj):
return self._join_translations(getattr(obj, 'brief'))
def urls(self, obj):
urls = {}
for lang, _ in settings.LANGUAGES:
with translation.override(lang):
urls[lang] = obj.get_absolute_url()
return urls
def get_url(self, obj):
# URLs are localized, cannot store in a text field
return ''
class MaterialConfig(AppConfig):
name = 'tk.material'
def ready(self):
for mn in ['Activity', 'Reading', 'Video', 'Link']:
m = self.get_model(mn)
search.register(m.objects.approved(), MaterialSearchAdapter)
|
<commit_before>from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated titles and descriptions into the search index.
The translated fields are stored as metadata.
"""
@property
def store(self):
return ['title', 'urls', 'brief']
def _join_translations(self, field: LocalizedField) -> str:
return ' '.join([v for v in field.values() if v is not None])
def get_title(self, obj):
return self._join_translations(getattr(obj, 'title'))
def get_description(self, obj):
return self._join_translations(getattr(obj, 'brief'))
def urls(self, obj):
urls = {}
for lang, _ in settings.LANGUAGES:
translation.activate(lang)
urls[lang] = obj.get_absolute_url()
return urls
def get_url(self, obj):
# URLs are localized, cannot store in a text field
return ''
class MaterialConfig(AppConfig):
name = 'tk.material'
def ready(self):
for mn in ['Activity', 'Reading', 'Video', 'Link']:
m = self.get_model(mn)
search.register(m.objects.approved(), MaterialSearchAdapter)
<commit_msg>Change current language only within context when building search indexes<commit_after>
|
from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated titles and descriptions into the search index.
The translated fields are stored as metadata.
"""
@property
def store(self):
return ['title', 'urls', 'brief']
def _join_translations(self, field: LocalizedField) -> str:
return ' '.join([v for v in field.values() if v is not None])
def get_title(self, obj):
return self._join_translations(getattr(obj, 'title'))
def get_description(self, obj):
return self._join_translations(getattr(obj, 'brief'))
def urls(self, obj):
urls = {}
for lang, _ in settings.LANGUAGES:
with translation.override(lang):
urls[lang] = obj.get_absolute_url()
return urls
def get_url(self, obj):
# URLs are localized, cannot store in a text field
return ''
class MaterialConfig(AppConfig):
name = 'tk.material'
def ready(self):
for mn in ['Activity', 'Reading', 'Video', 'Link']:
m = self.get_model(mn)
search.register(m.objects.approved(), MaterialSearchAdapter)
|
from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated titles and descriptions into the search index.
The translated fields are stored as metadata.
"""
@property
def store(self):
return ['title', 'urls', 'brief']
def _join_translations(self, field: LocalizedField) -> str:
return ' '.join([v for v in field.values() if v is not None])
def get_title(self, obj):
return self._join_translations(getattr(obj, 'title'))
def get_description(self, obj):
return self._join_translations(getattr(obj, 'brief'))
def urls(self, obj):
urls = {}
for lang, _ in settings.LANGUAGES:
translation.activate(lang)
urls[lang] = obj.get_absolute_url()
return urls
def get_url(self, obj):
# URLs are localized, cannot store in a text field
return ''
class MaterialConfig(AppConfig):
name = 'tk.material'
def ready(self):
for mn in ['Activity', 'Reading', 'Video', 'Link']:
m = self.get_model(mn)
search.register(m.objects.approved(), MaterialSearchAdapter)
Change current language only within context when building search indexesfrom django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated titles and descriptions into the search index.
The translated fields are stored as metadata.
"""
@property
def store(self):
return ['title', 'urls', 'brief']
def _join_translations(self, field: LocalizedField) -> str:
return ' '.join([v for v in field.values() if v is not None])
def get_title(self, obj):
return self._join_translations(getattr(obj, 'title'))
def get_description(self, obj):
return self._join_translations(getattr(obj, 'brief'))
def urls(self, obj):
urls = {}
for lang, _ in settings.LANGUAGES:
with translation.override(lang):
urls[lang] = obj.get_absolute_url()
return urls
def get_url(self, obj):
# URLs are localized, cannot store in a text field
return ''
class MaterialConfig(AppConfig):
name = 'tk.material'
def ready(self):
for mn in ['Activity', 'Reading', 'Video', 'Link']:
m = self.get_model(mn)
search.register(m.objects.approved(), MaterialSearchAdapter)
|
<commit_before>from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated titles and descriptions into the search index.
The translated fields are stored as metadata.
"""
@property
def store(self):
return ['title', 'urls', 'brief']
def _join_translations(self, field: LocalizedField) -> str:
return ' '.join([v for v in field.values() if v is not None])
def get_title(self, obj):
return self._join_translations(getattr(obj, 'title'))
def get_description(self, obj):
return self._join_translations(getattr(obj, 'brief'))
def urls(self, obj):
urls = {}
for lang, _ in settings.LANGUAGES:
translation.activate(lang)
urls[lang] = obj.get_absolute_url()
return urls
def get_url(self, obj):
# URLs are localized, cannot store in a text field
return ''
class MaterialConfig(AppConfig):
name = 'tk.material'
def ready(self):
for mn in ['Activity', 'Reading', 'Video', 'Link']:
m = self.get_model(mn)
search.register(m.objects.approved(), MaterialSearchAdapter)
<commit_msg>Change current language only within context when building search indexes<commit_after>from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated titles and descriptions into the search index.
The translated fields are stored as metadata.
"""
@property
def store(self):
return ['title', 'urls', 'brief']
def _join_translations(self, field: LocalizedField) -> str:
return ' '.join([v for v in field.values() if v is not None])
def get_title(self, obj):
return self._join_translations(getattr(obj, 'title'))
def get_description(self, obj):
return self._join_translations(getattr(obj, 'brief'))
def urls(self, obj):
urls = {}
for lang, _ in settings.LANGUAGES:
with translation.override(lang):
urls[lang] = obj.get_absolute_url()
return urls
def get_url(self, obj):
# URLs are localized, cannot store in a text field
return ''
class MaterialConfig(AppConfig):
name = 'tk.material'
def ready(self):
for mn in ['Activity', 'Reading', 'Video', 'Link']:
m = self.get_model(mn)
search.register(m.objects.approved(), MaterialSearchAdapter)
|
a6754051ced2763065007b765d5d523fe8c65835
|
src/epiweb/urls.py
|
src/epiweb/urls.py
|
from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
)
|
from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
(r'^profile/', include('epiweb.apps.profile.urls')),
)
|
Add URLs to profile app.
|
Add URLs to profile app.
|
Python
|
agpl-3.0
|
ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website
|
from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
)
Add URLs to profile app.
|
from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
(r'^profile/', include('epiweb.apps.profile.urls')),
)
|
<commit_before>from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
)
<commit_msg>Add URLs to profile app.<commit_after>
|
from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
(r'^profile/', include('epiweb.apps.profile.urls')),
)
|
from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
)
Add URLs to profile app.from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
(r'^profile/', include('epiweb.apps.profile.urls')),
)
|
<commit_before>from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
)
<commit_msg>Add URLs to profile app.<commit_after>from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'homepage.html'}),
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('epiweb.apps.accounts.urls')),
(r'^survey/', include('epiweb.apps.survey.urls')),
(r'^profile/', include('epiweb.apps.profile.urls')),
)
|
d23a2647f9313a49c9c552d90a2d57a26173b232
|
tools/dump_redis.py
|
tools/dump_redis.py
|
#!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
out[key] = conn.get(key)
#print '"%s":%s' % (key, conn.get(key))
print out
return out
def load_redis():
conn = redis.StrictRedis()
from dump import data
for key in data:
if re.search(":[0-9]*$", key) is not None:
conn.sadd(key, data[key])
else:
conn.set(key, data[key])
#dump_redis()
load_redis()
|
#!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
out[key] = conn.get(key)
#print '"%s":%s' % (key, conn.get(key))
# Todo : write dump.py with data = out or use JSON
print out
return out
def load_redis():
conn = redis.StrictRedis()
# dump.py should be generated by a previous dump_redis run
# you have to name the variable data then. data = {...}
from dump import data
for key in data:
if re.search(":[0-9]*$", key) is not None:
conn.sadd(key, data[key])
else:
conn.set(key, data[key])
#dump_redis()
load_redis()
|
Add : Load for redis
|
Add : Load for redis
|
Python
|
agpl-3.0
|
savoirfairelinux/mod-booster-snmp,savoirfairelinux/mod-booster-snmp,savoirfairelinux/mod-booster-snmp
|
#!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
out[key] = conn.get(key)
#print '"%s":%s' % (key, conn.get(key))
print out
return out
def load_redis():
conn = redis.StrictRedis()
from dump import data
for key in data:
if re.search(":[0-9]*$", key) is not None:
conn.sadd(key, data[key])
else:
conn.set(key, data[key])
#dump_redis()
load_redis()
Add : Load for redis
|
#!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
out[key] = conn.get(key)
#print '"%s":%s' % (key, conn.get(key))
# Todo : write dump.py with data = out or use JSON
print out
return out
def load_redis():
conn = redis.StrictRedis()
# dump.py should be generated by a previous dump_redis run
# you have to name the variable data then. data = {...}
from dump import data
for key in data:
if re.search(":[0-9]*$", key) is not None:
conn.sadd(key, data[key])
else:
conn.set(key, data[key])
#dump_redis()
load_redis()
|
<commit_before>#!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
out[key] = conn.get(key)
#print '"%s":%s' % (key, conn.get(key))
print out
return out
def load_redis():
conn = redis.StrictRedis()
from dump import data
for key in data:
if re.search(":[0-9]*$", key) is not None:
conn.sadd(key, data[key])
else:
conn.set(key, data[key])
#dump_redis()
load_redis()
<commit_msg>Add : Load for redis<commit_after>
|
#!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
out[key] = conn.get(key)
#print '"%s":%s' % (key, conn.get(key))
# Todo : write dump.py with data = out or use JSON
print out
return out
def load_redis():
conn = redis.StrictRedis()
# dump.py should be generated by a previous dump_redis run
# you have to name the variable data then. data = {...}
from dump import data
for key in data:
if re.search(":[0-9]*$", key) is not None:
conn.sadd(key, data[key])
else:
conn.set(key, data[key])
#dump_redis()
load_redis()
|
#!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
out[key] = conn.get(key)
#print '"%s":%s' % (key, conn.get(key))
print out
return out
def load_redis():
conn = redis.StrictRedis()
from dump import data
for key in data:
if re.search(":[0-9]*$", key) is not None:
conn.sadd(key, data[key])
else:
conn.set(key, data[key])
#dump_redis()
load_redis()
Add : Load for redis#!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
out[key] = conn.get(key)
#print '"%s":%s' % (key, conn.get(key))
# Todo : write dump.py with data = out or use JSON
print out
return out
def load_redis():
conn = redis.StrictRedis()
# dump.py should be generated by a previous dump_redis run
# you have to name the variable data then. data = {...}
from dump import data
for key in data:
if re.search(":[0-9]*$", key) is not None:
conn.sadd(key, data[key])
else:
conn.set(key, data[key])
#dump_redis()
load_redis()
|
<commit_before>#!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
out[key] = conn.get(key)
#print '"%s":%s' % (key, conn.get(key))
print out
return out
def load_redis():
conn = redis.StrictRedis()
from dump import data
for key in data:
if re.search(":[0-9]*$", key) is not None:
conn.sadd(key, data[key])
else:
conn.set(key, data[key])
#dump_redis()
load_redis()
<commit_msg>Add : Load for redis<commit_after>#!/usr/bin/python
import redis
import re
import ast
def dump_redis():
conn = redis.StrictRedis()
out = {}
for key in conn.keys():
if re.search(":[0-9]*$", key) is not None:
out[key] = conn.smembers(key)
#print '"%s":%s' % (key, conn.smembers(key))
else:
out[key] = conn.get(key)
#print '"%s":%s' % (key, conn.get(key))
# Todo : write dump.py with data = out or use JSON
print out
return out
def load_redis():
conn = redis.StrictRedis()
# dump.py should be generated by a previous dump_redis run
# you have to name the variable data then. data = {...}
from dump import data
for key in data:
if re.search(":[0-9]*$", key) is not None:
conn.sadd(key, data[key])
else:
conn.set(key, data[key])
#dump_redis()
load_redis()
|
7c3cf9e430bee4451e817ccc3d32884ed0c5f8e9
|
bakeit/uploader.py
|
bakeit/uploader.py
|
try:
from urllib.request import urlopen, Request, HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
"""
self.api_key = api_key
def upload(self, body, title="", language=None, duration=None, max_views=0):
"""
Upload the given body with the specified language type.
"""
url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key
if title:
url += "&title=%s" % title
if language:
url += "&language=%s" % language
if duration:
url += "&duration=%s" % duration
if max_views:
url += "&max_views=%s" % max_views
body = bytes(body.encode("utf8"))
req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'})
try:
response = urlopen(req)
except HTTPError as e:
response = json.loads(e.read())
raise RuntimeError(response["error_msg"])
response = json.loads(response.read().decode("utf8"))
return response["url"]
|
try:
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
"""
self.api_key = api_key
def upload(self, body, title="", language=None, duration=None, max_views=0):
"""
Upload the given body with the specified language type.
"""
url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key
if title:
url += "&title=%s" % title
if language:
url += "&language=%s" % language
if duration:
url += "&duration=%s" % duration
if max_views:
url += "&max_views=%s" % max_views
body = bytes(body.encode("utf8"))
req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'})
try:
response = urlopen(req)
except HTTPError as e:
response = json.loads(e.read().decode("utf8"))
raise RuntimeError(response["error_msg"])
response = json.loads(response.read().decode("utf8"))
return response["url"]
|
Fix Python3 error when decoding the response.
|
fix: Fix Python3 error when decoding the response.
|
Python
|
mit
|
skorokithakis/bakeit
|
try:
from urllib.request import urlopen, Request, HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
"""
self.api_key = api_key
def upload(self, body, title="", language=None, duration=None, max_views=0):
"""
Upload the given body with the specified language type.
"""
url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key
if title:
url += "&title=%s" % title
if language:
url += "&language=%s" % language
if duration:
url += "&duration=%s" % duration
if max_views:
url += "&max_views=%s" % max_views
body = bytes(body.encode("utf8"))
req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'})
try:
response = urlopen(req)
except HTTPError as e:
response = json.loads(e.read())
raise RuntimeError(response["error_msg"])
response = json.loads(response.read().decode("utf8"))
return response["url"]
fix: Fix Python3 error when decoding the response.
|
try:
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
"""
self.api_key = api_key
def upload(self, body, title="", language=None, duration=None, max_views=0):
"""
Upload the given body with the specified language type.
"""
url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key
if title:
url += "&title=%s" % title
if language:
url += "&language=%s" % language
if duration:
url += "&duration=%s" % duration
if max_views:
url += "&max_views=%s" % max_views
body = bytes(body.encode("utf8"))
req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'})
try:
response = urlopen(req)
except HTTPError as e:
response = json.loads(e.read().decode("utf8"))
raise RuntimeError(response["error_msg"])
response = json.loads(response.read().decode("utf8"))
return response["url"]
|
<commit_before>try:
from urllib.request import urlopen, Request, HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
"""
self.api_key = api_key
def upload(self, body, title="", language=None, duration=None, max_views=0):
"""
Upload the given body with the specified language type.
"""
url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key
if title:
url += "&title=%s" % title
if language:
url += "&language=%s" % language
if duration:
url += "&duration=%s" % duration
if max_views:
url += "&max_views=%s" % max_views
body = bytes(body.encode("utf8"))
req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'})
try:
response = urlopen(req)
except HTTPError as e:
response = json.loads(e.read())
raise RuntimeError(response["error_msg"])
response = json.loads(response.read().decode("utf8"))
return response["url"]
<commit_msg>fix: Fix Python3 error when decoding the response.<commit_after>
|
try:
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
"""
self.api_key = api_key
def upload(self, body, title="", language=None, duration=None, max_views=0):
"""
Upload the given body with the specified language type.
"""
url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key
if title:
url += "&title=%s" % title
if language:
url += "&language=%s" % language
if duration:
url += "&duration=%s" % duration
if max_views:
url += "&max_views=%s" % max_views
body = bytes(body.encode("utf8"))
req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'})
try:
response = urlopen(req)
except HTTPError as e:
response = json.loads(e.read().decode("utf8"))
raise RuntimeError(response["error_msg"])
response = json.loads(response.read().decode("utf8"))
return response["url"]
|
try:
from urllib.request import urlopen, Request, HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
"""
self.api_key = api_key
def upload(self, body, title="", language=None, duration=None, max_views=0):
"""
Upload the given body with the specified language type.
"""
url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key
if title:
url += "&title=%s" % title
if language:
url += "&language=%s" % language
if duration:
url += "&duration=%s" % duration
if max_views:
url += "&max_views=%s" % max_views
body = bytes(body.encode("utf8"))
req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'})
try:
response = urlopen(req)
except HTTPError as e:
response = json.loads(e.read())
raise RuntimeError(response["error_msg"])
response = json.loads(response.read().decode("utf8"))
return response["url"]
fix: Fix Python3 error when decoding the response.try:
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
"""
self.api_key = api_key
def upload(self, body, title="", language=None, duration=None, max_views=0):
"""
Upload the given body with the specified language type.
"""
url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key
if title:
url += "&title=%s" % title
if language:
url += "&language=%s" % language
if duration:
url += "&duration=%s" % duration
if max_views:
url += "&max_views=%s" % max_views
body = bytes(body.encode("utf8"))
req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'})
try:
response = urlopen(req)
except HTTPError as e:
response = json.loads(e.read().decode("utf8"))
raise RuntimeError(response["error_msg"])
response = json.loads(response.read().decode("utf8"))
return response["url"]
|
<commit_before>try:
from urllib.request import urlopen, Request, HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
"""
self.api_key = api_key
def upload(self, body, title="", language=None, duration=None, max_views=0):
"""
Upload the given body with the specified language type.
"""
url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key
if title:
url += "&title=%s" % title
if language:
url += "&language=%s" % language
if duration:
url += "&duration=%s" % duration
if max_views:
url += "&max_views=%s" % max_views
body = bytes(body.encode("utf8"))
req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'})
try:
response = urlopen(req)
except HTTPError as e:
response = json.loads(e.read())
raise RuntimeError(response["error_msg"])
response = json.loads(response.read().decode("utf8"))
return response["url"]
<commit_msg>fix: Fix Python3 error when decoding the response.<commit_after>try:
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import json
class PasteryUploader():
def __init__(self, api_key):
"""
Initialize an Uploader instance with the given API key.
"""
self.api_key = api_key
def upload(self, body, title="", language=None, duration=None, max_views=0):
"""
Upload the given body with the specified language type.
"""
url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key
if title:
url += "&title=%s" % title
if language:
url += "&language=%s" % language
if duration:
url += "&duration=%s" % duration
if max_views:
url += "&max_views=%s" % max_views
body = bytes(body.encode("utf8"))
req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'})
try:
response = urlopen(req)
except HTTPError as e:
response = json.loads(e.read().decode("utf8"))
raise RuntimeError(response["error_msg"])
response = json.loads(response.read().decode("utf8"))
return response["url"]
|
6e3bd2f5460049c9702bf44b37095c635ad8460b
|
smartfile/errors.py
|
smartfile/errors.py
|
import six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class ResponseError(APIError):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
try:
json = response.json()
except ValueError:
if self.status_code == 404:
self.detail = six.u('Invalid URL, check your API path')
else:
self.detail = six.u('Server error; check response for errors')
else:
if self.status_code == 400 and 'field_errors' in json:
self.detail = json['field_errors']
else:
try:
# A faulty move request returns the below response
self.detail = json['src'][0]
except KeyError:
# A faulty delete request returns the below response
self.detail = json['path'][0]
super(ResponseError, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
import six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class ResponseError(APIError):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
try:
json = response.json()
except ValueError:
if self.status_code == 404:
self.detail = six.u('Invalid URL, check your API path')
else:
self.detail = six.u('Server error; check response for errors')
else:
if self.status_code == 400 and 'field_errors' in json:
self.detail = json['field_errors']
else:
try:
# A faulty move request returns the below response
self.detail = json['src'][0]
except KeyError:
# A faulty delete request returns the below response
try:
self.detail = json['path'][0]
except KeyError:
self.detail = six.u('Error: %s' % response.content)
super(ResponseError, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
Fix error handling to catch if JSON is not returned
|
Fix error handling to catch if JSON is not returned
|
Python
|
mit
|
smartfile/client-python
|
import six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class ResponseError(APIError):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
try:
json = response.json()
except ValueError:
if self.status_code == 404:
self.detail = six.u('Invalid URL, check your API path')
else:
self.detail = six.u('Server error; check response for errors')
else:
if self.status_code == 400 and 'field_errors' in json:
self.detail = json['field_errors']
else:
try:
# A faulty move request returns the below response
self.detail = json['src'][0]
except KeyError:
# A faulty delete request returns the below response
self.detail = json['path'][0]
super(ResponseError, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
Fix error handling to catch if JSON is not returned
|
import six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class ResponseError(APIError):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
try:
json = response.json()
except ValueError:
if self.status_code == 404:
self.detail = six.u('Invalid URL, check your API path')
else:
self.detail = six.u('Server error; check response for errors')
else:
if self.status_code == 400 and 'field_errors' in json:
self.detail = json['field_errors']
else:
try:
# A faulty move request returns the below response
self.detail = json['src'][0]
except KeyError:
# A faulty delete request returns the below response
try:
self.detail = json['path'][0]
except KeyError:
self.detail = six.u('Error: %s' % response.content)
super(ResponseError, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
<commit_before>import six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class ResponseError(APIError):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
try:
json = response.json()
except ValueError:
if self.status_code == 404:
self.detail = six.u('Invalid URL, check your API path')
else:
self.detail = six.u('Server error; check response for errors')
else:
if self.status_code == 400 and 'field_errors' in json:
self.detail = json['field_errors']
else:
try:
# A faulty move request returns the below response
self.detail = json['src'][0]
except KeyError:
# A faulty delete request returns the below response
self.detail = json['path'][0]
super(ResponseError, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
<commit_msg>Fix error handling to catch if JSON is not returned<commit_after>
|
import six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class ResponseError(APIError):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
try:
json = response.json()
except ValueError:
if self.status_code == 404:
self.detail = six.u('Invalid URL, check your API path')
else:
self.detail = six.u('Server error; check response for errors')
else:
if self.status_code == 400 and 'field_errors' in json:
self.detail = json['field_errors']
else:
try:
# A faulty move request returns the below response
self.detail = json['src'][0]
except KeyError:
# A faulty delete request returns the below response
try:
self.detail = json['path'][0]
except KeyError:
self.detail = six.u('Error: %s' % response.content)
super(ResponseError, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
import six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class ResponseError(APIError):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
try:
json = response.json()
except ValueError:
if self.status_code == 404:
self.detail = six.u('Invalid URL, check your API path')
else:
self.detail = six.u('Server error; check response for errors')
else:
if self.status_code == 400 and 'field_errors' in json:
self.detail = json['field_errors']
else:
try:
# A faulty move request returns the below response
self.detail = json['src'][0]
except KeyError:
# A faulty delete request returns the below response
self.detail = json['path'][0]
super(ResponseError, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
Fix error handling to catch if JSON is not returnedimport six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class ResponseError(APIError):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
try:
json = response.json()
except ValueError:
if self.status_code == 404:
self.detail = six.u('Invalid URL, check your API path')
else:
self.detail = six.u('Server error; check response for errors')
else:
if self.status_code == 400 and 'field_errors' in json:
self.detail = json['field_errors']
else:
try:
# A faulty move request returns the below response
self.detail = json['src'][0]
except KeyError:
# A faulty delete request returns the below response
try:
self.detail = json['path'][0]
except KeyError:
self.detail = six.u('Error: %s' % response.content)
super(ResponseError, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
<commit_before>import six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class ResponseError(APIError):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
try:
json = response.json()
except ValueError:
if self.status_code == 404:
self.detail = six.u('Invalid URL, check your API path')
else:
self.detail = six.u('Server error; check response for errors')
else:
if self.status_code == 400 and 'field_errors' in json:
self.detail = json['field_errors']
else:
try:
# A faulty move request returns the below response
self.detail = json['src'][0]
except KeyError:
# A faulty delete request returns the below response
self.detail = json['path'][0]
super(ResponseError, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
<commit_msg>Fix error handling to catch if JSON is not returned<commit_after>import six
class APIError(Exception):
"SmartFile API base Exception."
pass
class RequestError(APIError):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
self.detail = str(exc)
super(RequestError, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class ResponseError(APIError):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
try:
json = response.json()
except ValueError:
if self.status_code == 404:
self.detail = six.u('Invalid URL, check your API path')
else:
self.detail = six.u('Server error; check response for errors')
else:
if self.status_code == 400 and 'field_errors' in json:
self.detail = json['field_errors']
else:
try:
# A faulty move request returns the below response
self.detail = json['src'][0]
except KeyError:
# A faulty delete request returns the below response
try:
self.detail = json['path'][0]
except KeyError:
self.detail = six.u('Error: %s' % response.content)
super(ResponseError, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
e2c53b348a69093cc770ba827a6bdd5191f2a830
|
aldryn_faq/cms_toolbar.py
|
aldryn_faq/cms_toolbar.py
|
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)
|
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _, get_language
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('add', 'question'):
params = ('?_popup&category=%s&language=%s' %
(category.pk, self.request.LANGUAGE_CODE))
menu.add_modal_item(_('Add question'), reverse('admin:aldryn_faq_question_add') + params)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)
|
Add ability to create question from toolbar
|
Add ability to create question from toolbar
|
Python
|
bsd-3-clause
|
czpython/aldryn-faq,mkoistinen/aldryn-faq,czpython/aldryn-faq,czpython/aldryn-faq,czpython/aldryn-faq
|
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)Add ability to create question from toolbar
|
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _, get_language
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('add', 'question'):
params = ('?_popup&category=%s&language=%s' %
(category.pk, self.request.LANGUAGE_CODE))
menu.add_modal_item(_('Add question'), reverse('admin:aldryn_faq_question_add') + params)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)
|
<commit_before># -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)<commit_msg>Add ability to create question from toolbar<commit_after>
|
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _, get_language
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('add', 'question'):
params = ('?_popup&category=%s&language=%s' %
(category.pk, self.request.LANGUAGE_CODE))
menu.add_modal_item(_('Add question'), reverse('admin:aldryn_faq_question_add') + params)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)
|
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)Add ability to create question from toolbar# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _, get_language
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('add', 'question'):
params = ('?_popup&category=%s&language=%s' %
(category.pk, self.request.LANGUAGE_CODE))
menu.add_modal_item(_('Add question'), reverse('admin:aldryn_faq_question_add') + params)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)
|
<commit_before># -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)<commit_msg>Add ability to create question from toolbar<commit_after># -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _, get_language
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('add', 'question'):
params = ('?_popup&category=%s&language=%s' %
(category.pk, self.request.LANGUAGE_CODE))
menu.add_modal_item(_('Add question'), reverse('admin:aldryn_faq_question_add') + params)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)
|
d7ea0514d3b794f2cacde82069699eff6b96cb24
|
wafer/talks/urls.py
|
wafer/talks/urls.py
|
from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'),
url(r'^page/(?P<page>\d+)$', UsersTalks.as_view(),
name='wafer_users_talks_page'),
url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'),
url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'),
url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(),
name='wafer_talk_edit'),
url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(),
name='wafer_talk_delete'),
url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'),
url(r'^api/', include(router.urls)),
)
|
from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'),
url(r'^page/(?P<page>\d+)/$', UsersTalks.as_view(),
name='wafer_users_talks_page'),
url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'),
url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'),
url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(),
name='wafer_talk_edit'),
url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(),
name='wafer_talk_delete'),
url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'),
url(r'^api/', include(router.urls)),
)
|
Add a trailing slash to the paginated talk list
|
Add a trailing slash to the paginated talk list
|
Python
|
isc
|
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
|
from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'),
url(r'^page/(?P<page>\d+)$', UsersTalks.as_view(),
name='wafer_users_talks_page'),
url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'),
url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'),
url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(),
name='wafer_talk_edit'),
url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(),
name='wafer_talk_delete'),
url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'),
url(r'^api/', include(router.urls)),
)
Add a trailing slash to the paginated talk list
|
from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'),
url(r'^page/(?P<page>\d+)/$', UsersTalks.as_view(),
name='wafer_users_talks_page'),
url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'),
url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'),
url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(),
name='wafer_talk_edit'),
url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(),
name='wafer_talk_delete'),
url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'),
url(r'^api/', include(router.urls)),
)
|
<commit_before>from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'),
url(r'^page/(?P<page>\d+)$', UsersTalks.as_view(),
name='wafer_users_talks_page'),
url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'),
url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'),
url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(),
name='wafer_talk_edit'),
url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(),
name='wafer_talk_delete'),
url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'),
url(r'^api/', include(router.urls)),
)
<commit_msg>Add a trailing slash to the paginated talk list<commit_after>
|
from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'),
url(r'^page/(?P<page>\d+)/$', UsersTalks.as_view(),
name='wafer_users_talks_page'),
url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'),
url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'),
url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(),
name='wafer_talk_edit'),
url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(),
name='wafer_talk_delete'),
url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'),
url(r'^api/', include(router.urls)),
)
|
from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'),
url(r'^page/(?P<page>\d+)$', UsersTalks.as_view(),
name='wafer_users_talks_page'),
url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'),
url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'),
url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(),
name='wafer_talk_edit'),
url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(),
name='wafer_talk_delete'),
url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'),
url(r'^api/', include(router.urls)),
)
Add a trailing slash to the paginated talk listfrom django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'),
url(r'^page/(?P<page>\d+)/$', UsersTalks.as_view(),
name='wafer_users_talks_page'),
url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'),
url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'),
url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(),
name='wafer_talk_edit'),
url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(),
name='wafer_talk_delete'),
url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'),
url(r'^api/', include(router.urls)),
)
|
<commit_before>from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'),
url(r'^page/(?P<page>\d+)$', UsersTalks.as_view(),
name='wafer_users_talks_page'),
url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'),
url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'),
url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(),
name='wafer_talk_edit'),
url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(),
name='wafer_talk_delete'),
url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'),
url(r'^api/', include(router.urls)),
)
<commit_msg>Add a trailing slash to the paginated talk list<commit_after>from django.conf.urls import patterns, url, include
from rest_framework import routers
from wafer.talks.views import (
Speakers, TalkCreate, TalkDelete, TalkUpdate, TalkView, UsersTalks,
TalksViewSet)
router = routers.DefaultRouter()
router.register(r'talks', TalksViewSet)
urlpatterns = patterns(
'',
url(r'^$', UsersTalks.as_view(), name='wafer_users_talks'),
url(r'^page/(?P<page>\d+)/$', UsersTalks.as_view(),
name='wafer_users_talks_page'),
url(r'^new/$', TalkCreate.as_view(), name='wafer_talk_submit'),
url(r'^(?P<pk>\d+)/$', TalkView.as_view(), name='wafer_talk'),
url(r'^(?P<pk>\d+)/edit/$', TalkUpdate.as_view(),
name='wafer_talk_edit'),
url(r'^(?P<pk>\d+)/delete/$', TalkDelete.as_view(),
name='wafer_talk_delete'),
url(r'^speakers/$', Speakers.as_view(), name='wafer_talks_speakers'),
url(r'^api/', include(router.urls)),
)
|
65881ca4254460ad6861769288680bd608648e0f
|
adhocracy/tests/lib/test_text.py
|
adhocracy/tests/lib/test_text.py
|
from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u"http://test.test.lan:5000/user/pudo'" in result)
|
from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u'http://test.test.lan:5000/user/pudo"' in result)
|
Adjust test cause user links now use double quotes for attributes
|
Adjust test cause user links now use double quotes for attributes
|
Python
|
agpl-3.0
|
alkadis/vcv,liqd/adhocracy,liqd/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,alkadis/vcv,phihag/adhocracy,phihag/adhocracy,SysTheron/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,SysTheron/adhocracy,SysTheron/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv
|
from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u"http://test.test.lan:5000/user/pudo'" in result)
Adjust test cause user links now use double quotes for attributes
|
from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u'http://test.test.lan:5000/user/pudo"' in result)
|
<commit_before>from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u"http://test.test.lan:5000/user/pudo'" in result)
<commit_msg>Adjust test cause user links now use double quotes for attributes<commit_after>
|
from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u'http://test.test.lan:5000/user/pudo"' in result)
|
from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u"http://test.test.lan:5000/user/pudo'" in result)
Adjust test cause user links now use double quotes for attributesfrom adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u'http://test.test.lan:5000/user/pudo"' in result)
|
<commit_before>from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u"http://test.test.lan:5000/user/pudo'" in result)
<commit_msg>Adjust test cause user links now use double quotes for attributes<commit_after>from adhocracy.tests import TestController
from adhocracy.tests.testtools import tt_make_user
class TestText(TestController):
def test_render(self):
from adhocracy.lib.text import render
source = ('header\n'
'========')
result = render(source)
self.assertEqual(result, u'<h1>header</h1>\n')
def test_render_no_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=False)
self.assertEqual(result, u'<p>@pudo</p>\n')
def test_render_user_substitution(self):
from adhocracy.lib.text import render
tt_make_user('pudo')
source = '@pudo'
result = render(source, substitutions=True)
self.assertTrue(u'http://test.test.lan:5000/user/pudo"' in result)
|
b33fcfe3752caeb61a83eb04c3b8399b7c44c9a4
|
sylvia/__init__.py
|
sylvia/__init__.py
|
from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole import *
from SylviaEpcServer import *
|
import sys
if sys.version_info[0] > 2:
raise Exception( "Sorry, we're still on Python 2. Version 1.0 of Sylvia will finally move to Python 3." )
from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole import *
from SylviaEpcServer import *
|
Add meaningful error for runnign with Python3
|
Add meaningful error for runnign with Python3
If we detect a Python3 interpreter at module init, tell the user to
use Python 2. And be sure to apologize because it's 2019...
|
Python
|
mit
|
bgutter/sylvia
|
from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole import *
from SylviaEpcServer import *
Add meaningful error for runnign with Python3
If we detect a Python3 interpreter at module init, tell the user to
use Python 2. And be sure to apologize because it's 2019...
|
import sys
if sys.version_info[0] > 2:
raise Exception( "Sorry, we're still on Python 2. Version 1.0 of Sylvia will finally move to Python 3." )
from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole import *
from SylviaEpcServer import *
|
<commit_before>from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole import *
from SylviaEpcServer import *
<commit_msg>Add meaningful error for runnign with Python3
If we detect a Python3 interpreter at module init, tell the user to
use Python 2. And be sure to apologize because it's 2019...<commit_after>
|
import sys
if sys.version_info[0] > 2:
raise Exception( "Sorry, we're still on Python 2. Version 1.0 of Sylvia will finally move to Python 3." )
from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole import *
from SylviaEpcServer import *
|
from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole import *
from SylviaEpcServer import *
Add meaningful error for runnign with Python3
If we detect a Python3 interpreter at module init, tell the user to
use Python 2. And be sure to apologize because it's 2019...import sys
if sys.version_info[0] > 2:
raise Exception( "Sorry, we're still on Python 2. Version 1.0 of Sylvia will finally move to Python 3." )
from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole import *
from SylviaEpcServer import *
|
<commit_before>from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole import *
from SylviaEpcServer import *
<commit_msg>Add meaningful error for runnign with Python3
If we detect a Python3 interpreter at module init, tell the user to
use Python 2. And be sure to apologize because it's 2019...<commit_after>import sys
if sys.version_info[0] > 2:
raise Exception( "Sorry, we're still on Python 2. Version 1.0 of Sylvia will finally move to Python 3." )
from PhonemeDetails import *
from LetterDetails import *
from PronunciationInferencer import *
from PhoneticDictionary import *
from Poem import *
from SylviaConsole import *
from SylviaEpcServer import *
|
71de95f9a2ea9e48d30d04897e79b025b8520775
|
bfg9000/shell/__init__.py
|
bfg9000/shell/__init__.py
|
import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(args, shell=False, env=None, quiet=False):
stderr = None
if quiet:
stderr = open(os.devnull, 'wb')
try:
result = subprocess.check_output(
args, universal_newlines=True, shell=shell, env=env, stderr=stderr
)
finally:
if quiet:
stderr.close()
return result
|
import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(args, shell=False, env=None, quiet=False):
stderr = open(os.devnull, 'wb') if quiet else None
try:
return subprocess.check_output(
args, universal_newlines=True, shell=shell, env=env, stderr=stderr
)
finally:
if stderr:
stderr.close()
|
Clean up the shell execute() function
|
Clean up the shell execute() function
|
Python
|
bsd-3-clause
|
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
|
import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(args, shell=False, env=None, quiet=False):
stderr = None
if quiet:
stderr = open(os.devnull, 'wb')
try:
result = subprocess.check_output(
args, universal_newlines=True, shell=shell, env=env, stderr=stderr
)
finally:
if quiet:
stderr.close()
return result
Clean up the shell execute() function
|
import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(args, shell=False, env=None, quiet=False):
stderr = open(os.devnull, 'wb') if quiet else None
try:
return subprocess.check_output(
args, universal_newlines=True, shell=shell, env=env, stderr=stderr
)
finally:
if stderr:
stderr.close()
|
<commit_before>import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(args, shell=False, env=None, quiet=False):
stderr = None
if quiet:
stderr = open(os.devnull, 'wb')
try:
result = subprocess.check_output(
args, universal_newlines=True, shell=shell, env=env, stderr=stderr
)
finally:
if quiet:
stderr.close()
return result
<commit_msg>Clean up the shell execute() function<commit_after>
|
import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(args, shell=False, env=None, quiet=False):
stderr = open(os.devnull, 'wb') if quiet else None
try:
return subprocess.check_output(
args, universal_newlines=True, shell=shell, env=env, stderr=stderr
)
finally:
if stderr:
stderr.close()
|
import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(args, shell=False, env=None, quiet=False):
stderr = None
if quiet:
stderr = open(os.devnull, 'wb')
try:
result = subprocess.check_output(
args, universal_newlines=True, shell=shell, env=env, stderr=stderr
)
finally:
if quiet:
stderr.close()
return result
Clean up the shell execute() functionimport os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(args, shell=False, env=None, quiet=False):
stderr = open(os.devnull, 'wb') if quiet else None
try:
return subprocess.check_output(
args, universal_newlines=True, shell=shell, env=env, stderr=stderr
)
finally:
if stderr:
stderr.close()
|
<commit_before>import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(args, shell=False, env=None, quiet=False):
stderr = None
if quiet:
stderr = open(os.devnull, 'wb')
try:
result = subprocess.check_output(
args, universal_newlines=True, shell=shell, env=env, stderr=stderr
)
finally:
if quiet:
stderr.close()
return result
<commit_msg>Clean up the shell execute() function<commit_after>import os
import subprocess
from ..platform_name import platform_name
if platform_name() == 'windows':
from .windows import *
else:
from .posix import *
class shell_list(list):
"""A special subclass of list used to mark that this command line uses
special shell characters."""
pass
def execute(args, shell=False, env=None, quiet=False):
stderr = open(os.devnull, 'wb') if quiet else None
try:
return subprocess.check_output(
args, universal_newlines=True, shell=shell, env=env, stderr=stderr
)
finally:
if stderr:
stderr.close()
|
5bd4688408fa2267bfb72fcab1ff85ddd134c00c
|
openquake/hazardlib/__init__.py
|
openquake/hazardlib/__init__.py
|
# The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.12.1'
__version__ += general.git_suffix(__file__)
|
# The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.13.0'
__version__ += general.git_suffix(__file__)
|
Upgrade release number to 0.6.0 (oq-engine 1.3.0)
|
Upgrade release number to 0.6.0 (oq-engine 1.3.0)
|
Python
|
agpl-3.0
|
mmpagani/oq-hazardlib,silviacanessa/oq-hazardlib,silviacanessa/oq-hazardlib,silviacanessa/oq-hazardlib,gem/oq-hazardlib,gem/oq-engine,vup1120/oq-hazardlib,vup1120/oq-hazardlib,gem/oq-engine,gem/oq-engine,g-weatherill/oq-hazardlib,vup1120/oq-hazardlib,larsbutler/oq-hazardlib,mmpagani/oq-hazardlib,gem/oq-engine,g-weatherill/oq-hazardlib,larsbutler/oq-hazardlib,g-weatherill/oq-hazardlib,g-weatherill/oq-hazardlib,gem/oq-hazardlib,rcgee/oq-hazardlib,mmpagani/oq-hazardlib,silviacanessa/oq-hazardlib,larsbutler/oq-hazardlib,rcgee/oq-hazardlib,gem/oq-hazardlib,gem/oq-engine
|
# The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.12.1'
__version__ += general.git_suffix(__file__)
Upgrade release number to 0.6.0 (oq-engine 1.3.0)
|
# The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.13.0'
__version__ += general.git_suffix(__file__)
|
<commit_before># The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.12.1'
__version__ += general.git_suffix(__file__)
<commit_msg>Upgrade release number to 0.6.0 (oq-engine 1.3.0)<commit_after>
|
# The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.13.0'
__version__ += general.git_suffix(__file__)
|
# The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.12.1'
__version__ += general.git_suffix(__file__)
Upgrade release number to 0.6.0 (oq-engine 1.3.0)# The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.13.0'
__version__ += general.git_suffix(__file__)
|
<commit_before># The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.12.1'
__version__ += general.git_suffix(__file__)
<commit_msg>Upgrade release number to 0.6.0 (oq-engine 1.3.0)<commit_after># The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.13.0'
__version__ += general.git_suffix(__file__)
|
c8e57ffc08f89111bb628bdfa6114a76672e73b1
|
chmvh_website/gallery/signals.py
|
chmvh_website/gallery/signals.py
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import create_thumbnail, process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def send_notifications(sender, instance, *args, **kwargs):
""" Notify users that a reply has been posted """
process_patient_picture.delay(instance)
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def process_picture(sender, instance, update_fields, *args, **kwargs):
"""
Process a patients picture.
This involves checking for different orientations as well as
generating a thumbnail for the picture.
Args:
sender:
The sender of the save event.
instance:
The Patient instance being saved.
update_fields:
The fields that were updated in the save.
*args:
Additional arguments.
**kwargs:
Additional keyword arguments.
"""
if not update_fields or 'thumbnail' not in update_fields:
process_patient_picture.delay(instance)
|
Fix infinite loop when processing pictures.
|
Fix infinite loop when processing pictures.
|
Python
|
mit
|
cdriehuys/chmvh-website,cdriehuys/chmvh-website,cdriehuys/chmvh-website
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import create_thumbnail, process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def send_notifications(sender, instance, *args, **kwargs):
""" Notify users that a reply has been posted """
process_patient_picture.delay(instance)
Fix infinite loop when processing pictures.
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def process_picture(sender, instance, update_fields, *args, **kwargs):
"""
Process a patients picture.
This involves checking for different orientations as well as
generating a thumbnail for the picture.
Args:
sender:
The sender of the save event.
instance:
The Patient instance being saved.
update_fields:
The fields that were updated in the save.
*args:
Additional arguments.
**kwargs:
Additional keyword arguments.
"""
if not update_fields or 'thumbnail' not in update_fields:
process_patient_picture.delay(instance)
|
<commit_before>from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import create_thumbnail, process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def send_notifications(sender, instance, *args, **kwargs):
""" Notify users that a reply has been posted """
process_patient_picture.delay(instance)
<commit_msg>Fix infinite loop when processing pictures.<commit_after>
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def process_picture(sender, instance, update_fields, *args, **kwargs):
"""
Process a patients picture.
This involves checking for different orientations as well as
generating a thumbnail for the picture.
Args:
sender:
The sender of the save event.
instance:
The Patient instance being saved.
update_fields:
The fields that were updated in the save.
*args:
Additional arguments.
**kwargs:
Additional keyword arguments.
"""
if not update_fields or 'thumbnail' not in update_fields:
process_patient_picture.delay(instance)
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import create_thumbnail, process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def send_notifications(sender, instance, *args, **kwargs):
""" Notify users that a reply has been posted """
process_patient_picture.delay(instance)
Fix infinite loop when processing pictures.from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def process_picture(sender, instance, update_fields, *args, **kwargs):
"""
Process a patients picture.
This involves checking for different orientations as well as
generating a thumbnail for the picture.
Args:
sender:
The sender of the save event.
instance:
The Patient instance being saved.
update_fields:
The fields that were updated in the save.
*args:
Additional arguments.
**kwargs:
Additional keyword arguments.
"""
if not update_fields or 'thumbnail' not in update_fields:
process_patient_picture.delay(instance)
|
<commit_before>from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import create_thumbnail, process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def send_notifications(sender, instance, *args, **kwargs):
""" Notify users that a reply has been posted """
process_patient_picture.delay(instance)
<commit_msg>Fix infinite loop when processing pictures.<commit_after>from django.db.models.signals import post_save
from django.dispatch import receiver
from gallery.tasks import process_patient_picture
@receiver(post_save, sender='gallery.Patient')
def process_picture(sender, instance, update_fields, *args, **kwargs):
"""
Process a patients picture.
This involves checking for different orientations as well as
generating a thumbnail for the picture.
Args:
sender:
The sender of the save event.
instance:
The Patient instance being saved.
update_fields:
The fields that were updated in the save.
*args:
Additional arguments.
**kwargs:
Additional keyword arguments.
"""
if not update_fields or 'thumbnail' not in update_fields:
process_patient_picture.delay(instance)
|
6075ec67951d0fa6cae6db5b37cad3291766dfc4
|
ci/cleanup-binary-tags.py
|
ci/cleanup-binary-tags.py
|
#!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
#!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git fetch --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
Adjust pulling tags in CI
|
Adjust pulling tags in CI
|
Python
|
mit
|
autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim
|
#!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
Adjust pulling tags in CI
|
#!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git fetch --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
<commit_before>#!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
<commit_msg>Adjust pulling tags in CI<commit_after>
|
#!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git fetch --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
#!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
Adjust pulling tags in CI#!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git fetch --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
<commit_before>#!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
<commit_msg>Adjust pulling tags in CI<commit_after>#!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git fetch --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
699279fe19c20e200db91e032c97b3f0b644c2af
|
conllu/__init__.py
|
conllu/__init__.py
|
from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def _iter_sents(in_file):
buf = []
for line in in_file:
if line == "\n":
yield "".join(buf)[:-1]
buf = []
else:
buf.append(line)
if buf:
yield "".join(buf)
def parse_incr(in_file, fields=None):
for sentence in _iter_sents(in_file):
yield TokenList(*parse_token_and_metadata(sentence, fields=fields))
def parse_tree(data):
tokenlists = parse(data)
sentences = []
for tokenlist in tokenlists:
sentences.append(tokenlist.to_tree())
return sentences
def parse_tree_incr(in_file):
for tokenlist in parse_incr(in_file):
yield tokenlist.to_tree()
|
from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def parse_incr(in_file, fields=None):
for sentence in _iter_sents(in_file):
yield TokenList(*parse_token_and_metadata(sentence, fields=fields))
def parse_tree(data):
tokenlists = parse(data)
sentences = []
for tokenlist in tokenlists:
sentences.append(tokenlist.to_tree())
return sentences
def parse_tree_incr(in_file):
for tokenlist in parse_incr(in_file):
yield tokenlist.to_tree()
def _iter_sents(in_file):
buf = []
for line in in_file:
if line == "\n":
yield "".join(buf)[:-1]
buf = []
else:
buf.append(line)
if buf:
yield "".join(buf)
|
Move helper to end of module and remove double spaces.
|
Move helper to end of module and remove double spaces.
|
Python
|
mit
|
EmilStenstrom/conllu
|
from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def _iter_sents(in_file):
buf = []
for line in in_file:
if line == "\n":
yield "".join(buf)[:-1]
buf = []
else:
buf.append(line)
if buf:
yield "".join(buf)
def parse_incr(in_file, fields=None):
for sentence in _iter_sents(in_file):
yield TokenList(*parse_token_and_metadata(sentence, fields=fields))
def parse_tree(data):
tokenlists = parse(data)
sentences = []
for tokenlist in tokenlists:
sentences.append(tokenlist.to_tree())
return sentences
def parse_tree_incr(in_file):
for tokenlist in parse_incr(in_file):
yield tokenlist.to_tree()
Move helper to end of module and remove double spaces.
|
from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def parse_incr(in_file, fields=None):
for sentence in _iter_sents(in_file):
yield TokenList(*parse_token_and_metadata(sentence, fields=fields))
def parse_tree(data):
tokenlists = parse(data)
sentences = []
for tokenlist in tokenlists:
sentences.append(tokenlist.to_tree())
return sentences
def parse_tree_incr(in_file):
for tokenlist in parse_incr(in_file):
yield tokenlist.to_tree()
def _iter_sents(in_file):
buf = []
for line in in_file:
if line == "\n":
yield "".join(buf)[:-1]
buf = []
else:
buf.append(line)
if buf:
yield "".join(buf)
|
<commit_before>from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def _iter_sents(in_file):
buf = []
for line in in_file:
if line == "\n":
yield "".join(buf)[:-1]
buf = []
else:
buf.append(line)
if buf:
yield "".join(buf)
def parse_incr(in_file, fields=None):
for sentence in _iter_sents(in_file):
yield TokenList(*parse_token_and_metadata(sentence, fields=fields))
def parse_tree(data):
tokenlists = parse(data)
sentences = []
for tokenlist in tokenlists:
sentences.append(tokenlist.to_tree())
return sentences
def parse_tree_incr(in_file):
for tokenlist in parse_incr(in_file):
yield tokenlist.to_tree()
<commit_msg>Move helper to end of module and remove double spaces.<commit_after>
|
from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def parse_incr(in_file, fields=None):
for sentence in _iter_sents(in_file):
yield TokenList(*parse_token_and_metadata(sentence, fields=fields))
def parse_tree(data):
tokenlists = parse(data)
sentences = []
for tokenlist in tokenlists:
sentences.append(tokenlist.to_tree())
return sentences
def parse_tree_incr(in_file):
for tokenlist in parse_incr(in_file):
yield tokenlist.to_tree()
def _iter_sents(in_file):
buf = []
for line in in_file:
if line == "\n":
yield "".join(buf)[:-1]
buf = []
else:
buf.append(line)
if buf:
yield "".join(buf)
|
from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def _iter_sents(in_file):
buf = []
for line in in_file:
if line == "\n":
yield "".join(buf)[:-1]
buf = []
else:
buf.append(line)
if buf:
yield "".join(buf)
def parse_incr(in_file, fields=None):
for sentence in _iter_sents(in_file):
yield TokenList(*parse_token_and_metadata(sentence, fields=fields))
def parse_tree(data):
tokenlists = parse(data)
sentences = []
for tokenlist in tokenlists:
sentences.append(tokenlist.to_tree())
return sentences
def parse_tree_incr(in_file):
for tokenlist in parse_incr(in_file):
yield tokenlist.to_tree()
Move helper to end of module and remove double spaces.from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def parse_incr(in_file, fields=None):
for sentence in _iter_sents(in_file):
yield TokenList(*parse_token_and_metadata(sentence, fields=fields))
def parse_tree(data):
tokenlists = parse(data)
sentences = []
for tokenlist in tokenlists:
sentences.append(tokenlist.to_tree())
return sentences
def parse_tree_incr(in_file):
for tokenlist in parse_incr(in_file):
yield tokenlist.to_tree()
def _iter_sents(in_file):
buf = []
for line in in_file:
if line == "\n":
yield "".join(buf)[:-1]
buf = []
else:
buf.append(line)
if buf:
yield "".join(buf)
|
<commit_before>from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def _iter_sents(in_file):
buf = []
for line in in_file:
if line == "\n":
yield "".join(buf)[:-1]
buf = []
else:
buf.append(line)
if buf:
yield "".join(buf)
def parse_incr(in_file, fields=None):
for sentence in _iter_sents(in_file):
yield TokenList(*parse_token_and_metadata(sentence, fields=fields))
def parse_tree(data):
tokenlists = parse(data)
sentences = []
for tokenlist in tokenlists:
sentences.append(tokenlist.to_tree())
return sentences
def parse_tree_incr(in_file):
for tokenlist in parse_incr(in_file):
yield tokenlist.to_tree()
<commit_msg>Move helper to end of module and remove double spaces.<commit_after>from __future__ import unicode_literals
from conllu.models import TokenList
from conllu.parser import parse_token_and_metadata
def parse(data, fields=None):
return [
TokenList(*parse_token_and_metadata(sentence, fields=fields))
for sentence in data.split("\n\n")
if sentence
]
def parse_incr(in_file, fields=None):
for sentence in _iter_sents(in_file):
yield TokenList(*parse_token_and_metadata(sentence, fields=fields))
def parse_tree(data):
tokenlists = parse(data)
sentences = []
for tokenlist in tokenlists:
sentences.append(tokenlist.to_tree())
return sentences
def parse_tree_incr(in_file):
for tokenlist in parse_incr(in_file):
yield tokenlist.to_tree()
def _iter_sents(in_file):
buf = []
for line in in_file:
if line == "\n":
yield "".join(buf)[:-1]
buf = []
else:
buf.append(line)
if buf:
yield "".join(buf)
|
c305632eb916332802fa5229e6f739f4ad74f686
|
ptpython/config.py
|
ptpython/config.py
|
__all__ = ('configure')
def configure(repl):
repl.vi_mode = True
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
|
__all__ = ('configure')
def configure(repl):
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
|
Disable vim mode in ptpython. Works meh
|
Disable vim mode in ptpython. Works meh
|
Python
|
mit
|
mpardalos/dotfiles,mpardalos/dotfiles
|
__all__ = ('configure')
def configure(repl):
repl.vi_mode = True
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
Disable vim mode in ptpython. Works meh
|
__all__ = ('configure')
def configure(repl):
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
|
<commit_before>__all__ = ('configure')
def configure(repl):
repl.vi_mode = True
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
<commit_msg>Disable vim mode in ptpython. Works meh<commit_after>
|
__all__ = ('configure')
def configure(repl):
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
|
__all__ = ('configure')
def configure(repl):
repl.vi_mode = True
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
Disable vim mode in ptpython. Works meh__all__ = ('configure')
def configure(repl):
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
|
<commit_before>__all__ = ('configure')
def configure(repl):
repl.vi_mode = True
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
<commit_msg>Disable vim mode in ptpython. Works meh<commit_after>__all__ = ('configure')
def configure(repl):
repl.show_signature = True
repl.show_meta_enter_message = True
repl.show_line_numbers = True
repl.enable_open_in_editor = True
repl.true_color = True
repl.use_code_colorscheme('monokai')
|
34174b9426fb4579a27771089037202f930faa9d
|
debug_logging/__init__.py
|
debug_logging/__init__.py
|
VERSION = (0, 4, 0, "a", 1) # following PEP 386
DEV_N = 1 # for PyPi releases, set this to None
def get_version(short=False):
version = "%s.%s" % (VERSION[0], VERSION[1])
if short:
return version
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
if DEV_N:
version = "%s.dev%s" % (version, DEV_N)
return version
__version__ = get_version()
|
VERSION = (0, 4, 0, "f", 1) # following PEP 386
DEV_N = None # for PyPi releases, set this to None
def get_version(short=False):
version = "%s.%s" % (VERSION[0], VERSION[1])
if short:
return version
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
if DEV_N:
version = "%s.dev%s" % (version, DEV_N)
return version
__version__ = get_version()
|
Update release number for pypi release
|
Update release number for pypi release
|
Python
|
bsd-3-clause
|
lincolnloop/django-debug-logging,lincolnloop/django-debug-logging
|
VERSION = (0, 4, 0, "a", 1) # following PEP 386
DEV_N = 1 # for PyPi releases, set this to None
def get_version(short=False):
version = "%s.%s" % (VERSION[0], VERSION[1])
if short:
return version
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
if DEV_N:
version = "%s.dev%s" % (version, DEV_N)
return version
__version__ = get_version()
Update release number for pypi release
|
VERSION = (0, 4, 0, "f", 1) # following PEP 386
DEV_N = None # for PyPi releases, set this to None
def get_version(short=False):
version = "%s.%s" % (VERSION[0], VERSION[1])
if short:
return version
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
if DEV_N:
version = "%s.dev%s" % (version, DEV_N)
return version
__version__ = get_version()
|
<commit_before>VERSION = (0, 4, 0, "a", 1) # following PEP 386
DEV_N = 1 # for PyPi releases, set this to None
def get_version(short=False):
version = "%s.%s" % (VERSION[0], VERSION[1])
if short:
return version
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
if DEV_N:
version = "%s.dev%s" % (version, DEV_N)
return version
__version__ = get_version()
<commit_msg>Update release number for pypi release<commit_after>
|
VERSION = (0, 4, 0, "f", 1) # following PEP 386
DEV_N = None # for PyPi releases, set this to None
def get_version(short=False):
version = "%s.%s" % (VERSION[0], VERSION[1])
if short:
return version
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
if DEV_N:
version = "%s.dev%s" % (version, DEV_N)
return version
__version__ = get_version()
|
VERSION = (0, 4, 0, "a", 1) # following PEP 386
DEV_N = 1 # for PyPi releases, set this to None
def get_version(short=False):
version = "%s.%s" % (VERSION[0], VERSION[1])
if short:
return version
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
if DEV_N:
version = "%s.dev%s" % (version, DEV_N)
return version
__version__ = get_version()
Update release number for pypi releaseVERSION = (0, 4, 0, "f", 1) # following PEP 386
DEV_N = None # for PyPi releases, set this to None
def get_version(short=False):
version = "%s.%s" % (VERSION[0], VERSION[1])
if short:
return version
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
if DEV_N:
version = "%s.dev%s" % (version, DEV_N)
return version
__version__ = get_version()
|
<commit_before>VERSION = (0, 4, 0, "a", 1) # following PEP 386
DEV_N = 1 # for PyPi releases, set this to None
def get_version(short=False):
version = "%s.%s" % (VERSION[0], VERSION[1])
if short:
return version
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
if DEV_N:
version = "%s.dev%s" % (version, DEV_N)
return version
__version__ = get_version()
<commit_msg>Update release number for pypi release<commit_after>VERSION = (0, 4, 0, "f", 1) # following PEP 386
DEV_N = None # for PyPi releases, set this to None
def get_version(short=False):
version = "%s.%s" % (VERSION[0], VERSION[1])
if short:
return version
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
if DEV_N:
version = "%s.dev%s" % (version, DEV_N)
return version
__version__ = get_version()
|
48bbdf82606440c2291d5f6255910c20b366cf9e
|
django/contrib/comments/feeds.py
|
django/contrib/comments/feeds.py
|
from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
|
from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
|
Use correct m2m join table name in LatestCommentsFeed
|
Use correct m2m join table name in LatestCommentsFeed
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409089
|
Python
|
bsd-3-clause
|
adieu/django-nonrel,adieu/django-nonrel,adieu/django-nonrel
|
from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
Use correct m2m join table name in LatestCommentsFeed
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409089
|
from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
|
<commit_before>from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
<commit_msg>Use correct m2m join table name in LatestCommentsFeed
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409089<commit_after>
|
from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
|
from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
Use correct m2m join table name in LatestCommentsFeed
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409089from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
|
<commit_before>from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
<commit_msg>Use correct m2m join table name in LatestCommentsFeed
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409089<commit_after>from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"%s comments" % self._site.name
def link(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return "http://%s/" % (self._site.domain)
def description(self):
if not hasattr(self, '_site'):
self._site = Site.objects.get_current()
return u"Latest comments on %s" % self._site.name
def items(self):
qs = comments.get_model().objects.filter(
site__pk = settings.SITE_ID,
is_public = True,
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs.order_by('-submit_date')[:40]
def item_pubdate(self, item):
return item.submit_date
|
13f9a48166aed2f6d09e1a27c60568d2318ceee2
|
src/ocspdash/custom_columns.py
|
src/ocspdash/custom_columns.py
|
# -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise uses
BINARY(16).
Based on http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type
"""
impl = BINARY
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
return dialect.type_descriptor(BINARY)
def process_bind_param(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return str(value)
if isinstance(value, uuid.UUID):
# hex string
return value.bytes
value_uuid = uuid.UUID(value)
return value_uuid.bytes
def process_result_value(self, value, dialect):
if value is None:
return
return uuid.UUID(bytes=value)
|
# -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise uses
BINARY(16).
Based on http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type
"""
impl = BINARY
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
return dialect.type_descriptor(BINARY)
def process_bind_param(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return str(value)
if isinstance(value, uuid.UUID):
# raw UUID bytes
return value.bytes
value_uuid = uuid.UUID(value)
return value_uuid.bytes
def process_result_value(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return uuid.UUID(value)
return uuid.UUID(bytes=value)
|
Change the custom UUID column to work right
|
Change the custom UUID column to work right
|
Python
|
mit
|
scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash
|
# -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise uses
BINARY(16).
Based on http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type
"""
impl = BINARY
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
return dialect.type_descriptor(BINARY)
def process_bind_param(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return str(value)
if isinstance(value, uuid.UUID):
# hex string
return value.bytes
value_uuid = uuid.UUID(value)
return value_uuid.bytes
def process_result_value(self, value, dialect):
if value is None:
return
return uuid.UUID(bytes=value)
Change the custom UUID column to work right
|
# -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise uses
BINARY(16).
Based on http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type
"""
impl = BINARY
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
return dialect.type_descriptor(BINARY)
def process_bind_param(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return str(value)
if isinstance(value, uuid.UUID):
# raw UUID bytes
return value.bytes
value_uuid = uuid.UUID(value)
return value_uuid.bytes
def process_result_value(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return uuid.UUID(value)
return uuid.UUID(bytes=value)
|
<commit_before># -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise uses
BINARY(16).
Based on http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type
"""
impl = BINARY
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
return dialect.type_descriptor(BINARY)
def process_bind_param(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return str(value)
if isinstance(value, uuid.UUID):
# hex string
return value.bytes
value_uuid = uuid.UUID(value)
return value_uuid.bytes
def process_result_value(self, value, dialect):
if value is None:
return
return uuid.UUID(bytes=value)
<commit_msg>Change the custom UUID column to work right<commit_after>
|
# -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise uses
BINARY(16).
Based on http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type
"""
impl = BINARY
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
return dialect.type_descriptor(BINARY)
def process_bind_param(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return str(value)
if isinstance(value, uuid.UUID):
# raw UUID bytes
return value.bytes
value_uuid = uuid.UUID(value)
return value_uuid.bytes
def process_result_value(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return uuid.UUID(value)
return uuid.UUID(bytes=value)
|
# -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise uses
BINARY(16).
Based on http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type
"""
impl = BINARY
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
return dialect.type_descriptor(BINARY)
def process_bind_param(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return str(value)
if isinstance(value, uuid.UUID):
# hex string
return value.bytes
value_uuid = uuid.UUID(value)
return value_uuid.bytes
def process_result_value(self, value, dialect):
if value is None:
return
return uuid.UUID(bytes=value)
Change the custom UUID column to work right# -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise uses
BINARY(16).
Based on http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type
"""
impl = BINARY
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
return dialect.type_descriptor(BINARY)
def process_bind_param(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return str(value)
if isinstance(value, uuid.UUID):
# raw UUID bytes
return value.bytes
value_uuid = uuid.UUID(value)
return value_uuid.bytes
def process_result_value(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return uuid.UUID(value)
return uuid.UUID(bytes=value)
|
<commit_before># -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise uses
BINARY(16).
Based on http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type
"""
impl = BINARY
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
return dialect.type_descriptor(BINARY)
def process_bind_param(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return str(value)
if isinstance(value, uuid.UUID):
# hex string
return value.bytes
value_uuid = uuid.UUID(value)
return value_uuid.bytes
def process_result_value(self, value, dialect):
if value is None:
return
return uuid.UUID(bytes=value)
<commit_msg>Change the custom UUID column to work right<commit_after># -*- coding: utf-8 -*-
"""Implements custom SQLAlchemy TypeDecorators."""
import uuid
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import BINARY, TypeDecorator
__all__ = [
'UUID',
]
class UUID(TypeDecorator):
"""Platform-independent UUID type.
Uses Postgresql's UUID type, otherwise uses
BINARY(16).
Based on http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type
"""
impl = BINARY
def load_dialect_impl(self, dialect):
if dialect.name == 'postgresql':
return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID())
return dialect.type_descriptor(BINARY)
def process_bind_param(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return str(value)
if isinstance(value, uuid.UUID):
# raw UUID bytes
return value.bytes
value_uuid = uuid.UUID(value)
return value_uuid.bytes
def process_result_value(self, value, dialect):
if value is None:
return
if dialect.name == 'postgresql':
return uuid.UUID(value)
return uuid.UUID(bytes=value)
|
053d4599dbb70664cb9f4e9c5b620b39733c254d
|
nova_powervm/conf/__init__.py
|
nova_powervm/conf/__init__.py
|
# Copyright 2016 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import nova.conf
from nova_powervm.conf import powervm
CONF = nova.conf.CONF
# Pull in the imports that nova-powervm uses so they are validated
CONF.import_opt('host', 'nova.netconf')
CONF.import_opt('my_ip', 'nova.netconf')
CONF.import_opt('vif_plugging_is_fatal', 'nova.virt.driver')
CONF.import_opt('vif_plugging_timeout', 'nova.virt.driver')
powervm.register_opts(CONF)
|
# Copyright 2016 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import nova.conf
from nova_powervm.conf import powervm
CONF = nova.conf.CONF
powervm.register_opts(CONF)
|
Support new conf refactor from Nova
|
Support new conf refactor from Nova
The core nova project is consolidating their conf options. This
impacted the PowerVM conf options as a few that we were explicitly
importing were moved.
This change set fixes the issue and allows PowerVM to work properly.
The change actually removes the imports, but they are still imported
properly because the PowerVM driver imports the 'nova.conf' package
(which will background load the parameters).
Change-Id: I93c46e74a09cac332b903adeddbd20e859b4b7f5
Closes-Bug: 1578318
|
Python
|
apache-2.0
|
openstack/nova-powervm,openstack/nova-powervm,stackforge/nova-powervm,stackforge/nova-powervm
|
# Copyright 2016 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import nova.conf
from nova_powervm.conf import powervm
CONF = nova.conf.CONF
# Pull in the imports that nova-powervm uses so they are validated
CONF.import_opt('host', 'nova.netconf')
CONF.import_opt('my_ip', 'nova.netconf')
CONF.import_opt('vif_plugging_is_fatal', 'nova.virt.driver')
CONF.import_opt('vif_plugging_timeout', 'nova.virt.driver')
powervm.register_opts(CONF)
Support new conf refactor from Nova
The core nova project is consolidating their conf options. This
impacted the PowerVM conf options as a few that we were explicitly
importing were moved.
This change set fixes the issue and allows PowerVM to work properly.
The change actually removes the imports, but they are still imported
properly because the PowerVM driver imports the 'nova.conf' package
(which will background load the parameters).
Change-Id: I93c46e74a09cac332b903adeddbd20e859b4b7f5
Closes-Bug: 1578318
|
# Copyright 2016 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import nova.conf
from nova_powervm.conf import powervm
CONF = nova.conf.CONF
powervm.register_opts(CONF)
|
<commit_before># Copyright 2016 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import nova.conf
from nova_powervm.conf import powervm
CONF = nova.conf.CONF
# Pull in the imports that nova-powervm uses so they are validated
CONF.import_opt('host', 'nova.netconf')
CONF.import_opt('my_ip', 'nova.netconf')
CONF.import_opt('vif_plugging_is_fatal', 'nova.virt.driver')
CONF.import_opt('vif_plugging_timeout', 'nova.virt.driver')
powervm.register_opts(CONF)
<commit_msg>Support new conf refactor from Nova
The core nova project is consolidating their conf options. This
impacted the PowerVM conf options as a few that we were explicitly
importing were moved.
This change set fixes the issue and allows PowerVM to work properly.
The change actually removes the imports, but they are still imported
properly because the PowerVM driver imports the 'nova.conf' package
(which will background load the parameters).
Change-Id: I93c46e74a09cac332b903adeddbd20e859b4b7f5
Closes-Bug: 1578318<commit_after>
|
# Copyright 2016 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import nova.conf
from nova_powervm.conf import powervm
CONF = nova.conf.CONF
powervm.register_opts(CONF)
|
# Copyright 2016 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import nova.conf
from nova_powervm.conf import powervm
CONF = nova.conf.CONF
# Pull in the imports that nova-powervm uses so they are validated
CONF.import_opt('host', 'nova.netconf')
CONF.import_opt('my_ip', 'nova.netconf')
CONF.import_opt('vif_plugging_is_fatal', 'nova.virt.driver')
CONF.import_opt('vif_plugging_timeout', 'nova.virt.driver')
powervm.register_opts(CONF)
Support new conf refactor from Nova
The core nova project is consolidating their conf options. This
impacted the PowerVM conf options as a few that we were explicitly
importing were moved.
This change set fixes the issue and allows PowerVM to work properly.
The change actually removes the imports, but they are still imported
properly because the PowerVM driver imports the 'nova.conf' package
(which will background load the parameters).
Change-Id: I93c46e74a09cac332b903adeddbd20e859b4b7f5
Closes-Bug: 1578318# Copyright 2016 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import nova.conf
from nova_powervm.conf import powervm
CONF = nova.conf.CONF
powervm.register_opts(CONF)
|
<commit_before># Copyright 2016 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import nova.conf
from nova_powervm.conf import powervm
CONF = nova.conf.CONF
# Pull in the imports that nova-powervm uses so they are validated
CONF.import_opt('host', 'nova.netconf')
CONF.import_opt('my_ip', 'nova.netconf')
CONF.import_opt('vif_plugging_is_fatal', 'nova.virt.driver')
CONF.import_opt('vif_plugging_timeout', 'nova.virt.driver')
powervm.register_opts(CONF)
<commit_msg>Support new conf refactor from Nova
The core nova project is consolidating their conf options. This
impacted the PowerVM conf options as a few that we were explicitly
importing were moved.
This change set fixes the issue and allows PowerVM to work properly.
The change actually removes the imports, but they are still imported
properly because the PowerVM driver imports the 'nova.conf' package
(which will background load the parameters).
Change-Id: I93c46e74a09cac332b903adeddbd20e859b4b7f5
Closes-Bug: 1578318<commit_after># Copyright 2016 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import nova.conf
from nova_powervm.conf import powervm
CONF = nova.conf.CONF
powervm.register_opts(CONF)
|
0c4e94cf9f6265768178509a4dcd07d1f502f5c8
|
djangoratings/managers.py
|
djangoratings/managers.py
|
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)
|
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
retval = super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
return retval
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)
|
Fix for the return value of delete method
|
Fix for the return value of delete method
|
Python
|
bsd-2-clause
|
bopo/django-ratings,dcramer/django-ratings,kangasbros/django-bitcoin,Elec/django-ratings,yeago/django-ratings,hovel/django-ratings,Eksmo/django-ratings,readevalprint/django-bitcoin
|
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)Fix for the return value of delete method
|
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
retval = super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
return retval
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)
|
<commit_before>from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)<commit_msg>Fix for the return value of delete method<commit_after>
|
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
retval = super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
return retval
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)
|
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)Fix for the return value of delete methodfrom django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
retval = super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
return retval
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)
|
<commit_before>from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)<commit_msg>Fix for the return value of delete method<commit_after>from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
retval = super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
return retval
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)
|
8fafef4c2151d17133c5787847d68ab4b58f40c3
|
stagecraft/libs/views/utils.py
|
stagecraft/libs/views/utils.py
|
import json
from django.utils.cache import patch_response_headers
from functools import wraps
def long_cache(a_view):
@wraps(a_view)
def _wrapped_view(request, *args, **kwargs):
response = a_view(request, *args, **kwargs)
patch_response_headers(response, 86400 * 365)
return response
return _wrapped_view
def to_json(what):
return json.dumps(what, indent=1)
|
import json
from django.utils.cache import patch_response_headers
from functools import wraps
from uuid import UUID
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, UUID):
return '{}'.format(obj)
if hasattr(obj, 'serialize'):
return obj.serialize()
return json.JSONEncoder.default(self, obj)
def long_cache(a_view):
@wraps(a_view)
def _wrapped_view(request, *args, **kwargs):
response = a_view(request, *args, **kwargs)
patch_response_headers(response, 86400 * 365)
return response
return _wrapped_view
def to_json(what):
return json.dumps(what, indent=1, cls=JsonEncoder)
|
Extend JSON serialiser to use serialize() method
|
Extend JSON serialiser to use serialize() method
If an object is a UUID, return a string representation of it.
If the object still can't be serialised, call its serialize() method.
This is useful when nesting Link models inside dashboards, for
example.
|
Python
|
mit
|
alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft
|
import json
from django.utils.cache import patch_response_headers
from functools import wraps
def long_cache(a_view):
@wraps(a_view)
def _wrapped_view(request, *args, **kwargs):
response = a_view(request, *args, **kwargs)
patch_response_headers(response, 86400 * 365)
return response
return _wrapped_view
def to_json(what):
return json.dumps(what, indent=1)
Extend JSON serialiser to use serialize() method
If an object is a UUID, return a string representation of it.
If the object still can't be serialised, call its serialize() method.
This is useful when nesting Link models inside dashboards, for
example.
|
import json
from django.utils.cache import patch_response_headers
from functools import wraps
from uuid import UUID
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, UUID):
return '{}'.format(obj)
if hasattr(obj, 'serialize'):
return obj.serialize()
return json.JSONEncoder.default(self, obj)
def long_cache(a_view):
@wraps(a_view)
def _wrapped_view(request, *args, **kwargs):
response = a_view(request, *args, **kwargs)
patch_response_headers(response, 86400 * 365)
return response
return _wrapped_view
def to_json(what):
return json.dumps(what, indent=1, cls=JsonEncoder)
|
<commit_before>import json
from django.utils.cache import patch_response_headers
from functools import wraps
def long_cache(a_view):
@wraps(a_view)
def _wrapped_view(request, *args, **kwargs):
response = a_view(request, *args, **kwargs)
patch_response_headers(response, 86400 * 365)
return response
return _wrapped_view
def to_json(what):
return json.dumps(what, indent=1)
<commit_msg>Extend JSON serialiser to use serialize() method
If an object is a UUID, return a string representation of it.
If the object still can't be serialised, call its serialize() method.
This is useful when nesting Link models inside dashboards, for
example.<commit_after>
|
import json
from django.utils.cache import patch_response_headers
from functools import wraps
from uuid import UUID
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, UUID):
return '{}'.format(obj)
if hasattr(obj, 'serialize'):
return obj.serialize()
return json.JSONEncoder.default(self, obj)
def long_cache(a_view):
@wraps(a_view)
def _wrapped_view(request, *args, **kwargs):
response = a_view(request, *args, **kwargs)
patch_response_headers(response, 86400 * 365)
return response
return _wrapped_view
def to_json(what):
return json.dumps(what, indent=1, cls=JsonEncoder)
|
import json
from django.utils.cache import patch_response_headers
from functools import wraps
def long_cache(a_view):
@wraps(a_view)
def _wrapped_view(request, *args, **kwargs):
response = a_view(request, *args, **kwargs)
patch_response_headers(response, 86400 * 365)
return response
return _wrapped_view
def to_json(what):
return json.dumps(what, indent=1)
Extend JSON serialiser to use serialize() method
If an object is a UUID, return a string representation of it.
If the object still can't be serialised, call its serialize() method.
This is useful when nesting Link models inside dashboards, for
example.import json
from django.utils.cache import patch_response_headers
from functools import wraps
from uuid import UUID
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, UUID):
return '{}'.format(obj)
if hasattr(obj, 'serialize'):
return obj.serialize()
return json.JSONEncoder.default(self, obj)
def long_cache(a_view):
@wraps(a_view)
def _wrapped_view(request, *args, **kwargs):
response = a_view(request, *args, **kwargs)
patch_response_headers(response, 86400 * 365)
return response
return _wrapped_view
def to_json(what):
return json.dumps(what, indent=1, cls=JsonEncoder)
|
<commit_before>import json
from django.utils.cache import patch_response_headers
from functools import wraps
def long_cache(a_view):
@wraps(a_view)
def _wrapped_view(request, *args, **kwargs):
response = a_view(request, *args, **kwargs)
patch_response_headers(response, 86400 * 365)
return response
return _wrapped_view
def to_json(what):
return json.dumps(what, indent=1)
<commit_msg>Extend JSON serialiser to use serialize() method
If an object is a UUID, return a string representation of it.
If the object still can't be serialised, call its serialize() method.
This is useful when nesting Link models inside dashboards, for
example.<commit_after>import json
from django.utils.cache import patch_response_headers
from functools import wraps
from uuid import UUID
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, UUID):
return '{}'.format(obj)
if hasattr(obj, 'serialize'):
return obj.serialize()
return json.JSONEncoder.default(self, obj)
def long_cache(a_view):
@wraps(a_view)
def _wrapped_view(request, *args, **kwargs):
response = a_view(request, *args, **kwargs)
patch_response_headers(response, 86400 * 365)
return response
return _wrapped_view
def to_json(what):
return json.dumps(what, indent=1, cls=JsonEncoder)
|
be51fddd326975047b7e60227072f5df80eadbad
|
conf_site/accounts/tests/factories.py
|
conf_site/accounts/tests/factories.py
|
# -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class Meta:
model = get_user_model()
|
# -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class Meta:
model = get_user_model()
django_get_or_create = ('username',)
|
Fix race condition involving account usernames.
|
Fix race condition involving account usernames.
Fix race condition causing random test failures by using get_or_create
on generated usernames. See https://factoryboy.readthedocs.io/en/latest/orms.html#factory.django.DjangoOptions.django_get_or_create
|
Python
|
mit
|
pydata/conf_site,pydata/conf_site,pydata/conf_site
|
# -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class Meta:
model = get_user_model()
Fix race condition involving account usernames.
Fix race condition causing random test failures by using get_or_create
on generated usernames. See https://factoryboy.readthedocs.io/en/latest/orms.html#factory.django.DjangoOptions.django_get_or_create
|
# -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class Meta:
model = get_user_model()
django_get_or_create = ('username',)
|
<commit_before># -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class Meta:
model = get_user_model()
<commit_msg>Fix race condition involving account usernames.
Fix race condition causing random test failures by using get_or_create
on generated usernames. See https://factoryboy.readthedocs.io/en/latest/orms.html#factory.django.DjangoOptions.django_get_or_create<commit_after>
|
# -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class Meta:
model = get_user_model()
django_get_or_create = ('username',)
|
# -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class Meta:
model = get_user_model()
Fix race condition involving account usernames.
Fix race condition causing random test failures by using get_or_create
on generated usernames. See https://factoryboy.readthedocs.io/en/latest/orms.html#factory.django.DjangoOptions.django_get_or_create# -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class Meta:
model = get_user_model()
django_get_or_create = ('username',)
|
<commit_before># -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class Meta:
model = get_user_model()
<commit_msg>Fix race condition involving account usernames.
Fix race condition causing random test failures by using get_or_create
on generated usernames. See https://factoryboy.readthedocs.io/en/latest/orms.html#factory.django.DjangoOptions.django_get_or_create<commit_after># -*- coding: utf-8 -*-
import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker("user_name")
email = factory.Faker("email")
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
class Meta:
model = get_user_model()
django_get_or_create = ('username',)
|
d648b7bc1e8f2e891be8a72d78c689b06a7bcdac
|
tests/TestConfigFileLoading.py
|
tests/TestConfigFileLoading.py
|
import unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def TestReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def TestReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def TestLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def TestDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def TestDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
|
import unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def testReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def testReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def testLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def testDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def testDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
|
Make test names lower case prefix
|
Make test names lower case prefix
|
Python
|
bsd-3-clause
|
sky-uk/bslint
|
import unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def TestReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def TestReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def TestLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def TestDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def TestDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
Make test names lower case prefix
|
import unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def testReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def testReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def testLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def testDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def testDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
|
<commit_before>import unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def TestReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def TestReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def TestLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def TestDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def TestDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
<commit_msg>Make test names lower case prefix<commit_after>
|
import unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def testReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def testReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def testLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def testDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def testDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
|
import unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def TestReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def TestReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def TestLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def TestDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def TestDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
Make test names lower case prefiximport unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def testReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def testReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def testLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def testDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def testDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
|
<commit_before>import unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def TestReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def TestReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def TestLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def TestDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def TestDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
<commit_msg>Make test names lower case prefix<commit_after>import unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def testReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def testReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def testLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def testDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def testDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
|
115771e1917bd40989cc70762225fd3c6e0a565b
|
test/test_parser.py
|
test/test_parser.py
|
import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position to start so it can be read
#self.tf.seek(0)
#print self.tf.readline()
self.patcher = mock.patch('apel.db.apeldb.ApelDb')
self.mock_db = self.patcher.start()
def test_parse_empty_file(self):
"""An empty file should be ignored and no errors raised."""
bin.parser.parse_file(None, self.mock_db, self.tf, False)
def tearDown(self):
self.tf.close()
self.patcher.stop()
if __name__ == '__main__':
unittest.main()
|
import bz2
import gzip
import os
import re
import shutil
import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position to start so it can be read
#self.tf.seek(0)
#print self.tf.readline()
self.patcher = mock.patch('apel.db.apeldb.ApelDb')
self.mock_db = self.patcher.start()
self.mock_parser = mock.Mock()
def test_parse_empty_file(self):
"""An empty file should be ignored and no errors raised."""
bin.parser.parse_file(None, self.mock_db, self.tf, False)
def test_scan_dir(self):
"""
Check that scan dir works with bzip, gzip and normal files.
"""
dir_path = tempfile.mkdtemp()
try:
# Create a bzip, gzip and normal file in turn in the temp directory
for method, suffix in ((bz2.BZ2File, '.bzip2'),
(gzip.open, '.gzip'),
(open, '.normal')):
handle, path = tempfile.mkstemp(suffix, dir=dir_path)
os.close(handle)
file_obj = method(path, 'wb')
# Write three lines to the file
file_obj.write("Line one.\nLine two.\nLine three.")
file_obj.close()
records = bin.parser.scan_dir(self.mock_parser, dir_path, False,
re.compile('(.*)'), self.mock_db, [])
for record in records:
# Check that all three lines have been read
self.assertEqual(record.get_field('StopLine'), 3,
"Unable to read %s file"
% record.get_field('FileName').split('.')[1])
finally:
shutil.rmtree(dir_path)
def tearDown(self):
self.tf.close()
self.patcher.stop()
if __name__ == '__main__':
unittest.main()
|
Add test for parsing different file types
|
Add test for parsing different file types
- Add tests for bzip, gzip and normal files to parser tests.
|
Python
|
apache-2.0
|
apel/apel,tofu-rocketry/apel,apel/apel,tofu-rocketry/apel,stfc/apel,stfc/apel
|
import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position to start so it can be read
#self.tf.seek(0)
#print self.tf.readline()
self.patcher = mock.patch('apel.db.apeldb.ApelDb')
self.mock_db = self.patcher.start()
def test_parse_empty_file(self):
"""An empty file should be ignored and no errors raised."""
bin.parser.parse_file(None, self.mock_db, self.tf, False)
def tearDown(self):
self.tf.close()
self.patcher.stop()
if __name__ == '__main__':
unittest.main()
Add test for parsing different file types
- Add tests for bzip, gzip and normal files to parser tests.
|
import bz2
import gzip
import os
import re
import shutil
import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position to start so it can be read
#self.tf.seek(0)
#print self.tf.readline()
self.patcher = mock.patch('apel.db.apeldb.ApelDb')
self.mock_db = self.patcher.start()
self.mock_parser = mock.Mock()
def test_parse_empty_file(self):
"""An empty file should be ignored and no errors raised."""
bin.parser.parse_file(None, self.mock_db, self.tf, False)
def test_scan_dir(self):
"""
Check that scan dir works with bzip, gzip and normal files.
"""
dir_path = tempfile.mkdtemp()
try:
# Create a bzip, gzip and normal file in turn in the temp directory
for method, suffix in ((bz2.BZ2File, '.bzip2'),
(gzip.open, '.gzip'),
(open, '.normal')):
handle, path = tempfile.mkstemp(suffix, dir=dir_path)
os.close(handle)
file_obj = method(path, 'wb')
# Write three lines to the file
file_obj.write("Line one.\nLine two.\nLine three.")
file_obj.close()
records = bin.parser.scan_dir(self.mock_parser, dir_path, False,
re.compile('(.*)'), self.mock_db, [])
for record in records:
# Check that all three lines have been read
self.assertEqual(record.get_field('StopLine'), 3,
"Unable to read %s file"
% record.get_field('FileName').split('.')[1])
finally:
shutil.rmtree(dir_path)
def tearDown(self):
self.tf.close()
self.patcher.stop()
if __name__ == '__main__':
unittest.main()
|
<commit_before>import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position to start so it can be read
#self.tf.seek(0)
#print self.tf.readline()
self.patcher = mock.patch('apel.db.apeldb.ApelDb')
self.mock_db = self.patcher.start()
def test_parse_empty_file(self):
"""An empty file should be ignored and no errors raised."""
bin.parser.parse_file(None, self.mock_db, self.tf, False)
def tearDown(self):
self.tf.close()
self.patcher.stop()
if __name__ == '__main__':
unittest.main()
<commit_msg>Add test for parsing different file types
- Add tests for bzip, gzip and normal files to parser tests.<commit_after>
|
import bz2
import gzip
import os
import re
import shutil
import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position to start so it can be read
#self.tf.seek(0)
#print self.tf.readline()
self.patcher = mock.patch('apel.db.apeldb.ApelDb')
self.mock_db = self.patcher.start()
self.mock_parser = mock.Mock()
def test_parse_empty_file(self):
"""An empty file should be ignored and no errors raised."""
bin.parser.parse_file(None, self.mock_db, self.tf, False)
def test_scan_dir(self):
"""
Check that scan dir works with bzip, gzip and normal files.
"""
dir_path = tempfile.mkdtemp()
try:
# Create a bzip, gzip and normal file in turn in the temp directory
for method, suffix in ((bz2.BZ2File, '.bzip2'),
(gzip.open, '.gzip'),
(open, '.normal')):
handle, path = tempfile.mkstemp(suffix, dir=dir_path)
os.close(handle)
file_obj = method(path, 'wb')
# Write three lines to the file
file_obj.write("Line one.\nLine two.\nLine three.")
file_obj.close()
records = bin.parser.scan_dir(self.mock_parser, dir_path, False,
re.compile('(.*)'), self.mock_db, [])
for record in records:
# Check that all three lines have been read
self.assertEqual(record.get_field('StopLine'), 3,
"Unable to read %s file"
% record.get_field('FileName').split('.')[1])
finally:
shutil.rmtree(dir_path)
def tearDown(self):
self.tf.close()
self.patcher.stop()
if __name__ == '__main__':
unittest.main()
|
import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position to start so it can be read
#self.tf.seek(0)
#print self.tf.readline()
self.patcher = mock.patch('apel.db.apeldb.ApelDb')
self.mock_db = self.patcher.start()
def test_parse_empty_file(self):
"""An empty file should be ignored and no errors raised."""
bin.parser.parse_file(None, self.mock_db, self.tf, False)
def tearDown(self):
self.tf.close()
self.patcher.stop()
if __name__ == '__main__':
unittest.main()
Add test for parsing different file types
- Add tests for bzip, gzip and normal files to parser tests.import bz2
import gzip
import os
import re
import shutil
import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position to start so it can be read
#self.tf.seek(0)
#print self.tf.readline()
self.patcher = mock.patch('apel.db.apeldb.ApelDb')
self.mock_db = self.patcher.start()
self.mock_parser = mock.Mock()
def test_parse_empty_file(self):
"""An empty file should be ignored and no errors raised."""
bin.parser.parse_file(None, self.mock_db, self.tf, False)
def test_scan_dir(self):
"""
Check that scan dir works with bzip, gzip and normal files.
"""
dir_path = tempfile.mkdtemp()
try:
# Create a bzip, gzip and normal file in turn in the temp directory
for method, suffix in ((bz2.BZ2File, '.bzip2'),
(gzip.open, '.gzip'),
(open, '.normal')):
handle, path = tempfile.mkstemp(suffix, dir=dir_path)
os.close(handle)
file_obj = method(path, 'wb')
# Write three lines to the file
file_obj.write("Line one.\nLine two.\nLine three.")
file_obj.close()
records = bin.parser.scan_dir(self.mock_parser, dir_path, False,
re.compile('(.*)'), self.mock_db, [])
for record in records:
# Check that all three lines have been read
self.assertEqual(record.get_field('StopLine'), 3,
"Unable to read %s file"
% record.get_field('FileName').split('.')[1])
finally:
shutil.rmtree(dir_path)
def tearDown(self):
self.tf.close()
self.patcher.stop()
if __name__ == '__main__':
unittest.main()
|
<commit_before>import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position to start so it can be read
#self.tf.seek(0)
#print self.tf.readline()
self.patcher = mock.patch('apel.db.apeldb.ApelDb')
self.mock_db = self.patcher.start()
def test_parse_empty_file(self):
"""An empty file should be ignored and no errors raised."""
bin.parser.parse_file(None, self.mock_db, self.tf, False)
def tearDown(self):
self.tf.close()
self.patcher.stop()
if __name__ == '__main__':
unittest.main()
<commit_msg>Add test for parsing different file types
- Add tests for bzip, gzip and normal files to parser tests.<commit_after>import bz2
import gzip
import os
import re
import shutil
import tempfile
import unittest
import mock
import bin.parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.tf = tempfile.TemporaryFile()
#print self.tf.name
#self.tf.write('Test text.')
## Reset file position to start so it can be read
#self.tf.seek(0)
#print self.tf.readline()
self.patcher = mock.patch('apel.db.apeldb.ApelDb')
self.mock_db = self.patcher.start()
self.mock_parser = mock.Mock()
def test_parse_empty_file(self):
"""An empty file should be ignored and no errors raised."""
bin.parser.parse_file(None, self.mock_db, self.tf, False)
def test_scan_dir(self):
"""
Check that scan dir works with bzip, gzip and normal files.
"""
dir_path = tempfile.mkdtemp()
try:
# Create a bzip, gzip and normal file in turn in the temp directory
for method, suffix in ((bz2.BZ2File, '.bzip2'),
(gzip.open, '.gzip'),
(open, '.normal')):
handle, path = tempfile.mkstemp(suffix, dir=dir_path)
os.close(handle)
file_obj = method(path, 'wb')
# Write three lines to the file
file_obj.write("Line one.\nLine two.\nLine three.")
file_obj.close()
records = bin.parser.scan_dir(self.mock_parser, dir_path, False,
re.compile('(.*)'), self.mock_db, [])
for record in records:
# Check that all three lines have been read
self.assertEqual(record.get_field('StopLine'), 3,
"Unable to read %s file"
% record.get_field('FileName').split('.')[1])
finally:
shutil.rmtree(dir_path)
def tearDown(self):
self.tf.close()
self.patcher.stop()
if __name__ == '__main__':
unittest.main()
|
401d5d3e676bdeeb067977b8506e420262d8be05
|
tests/test_memes.py
|
tests/test_memes.py
|
from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
node = models.Node()
meme = memes.Genome(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
node = models.Node()
meme = memes.Mimeme(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "mimeme"
assert meme.contents is None
|
from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
meme = memes.Genome()
self.add(meme)
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
meme = memes.Mimeme()
self.add(meme)
assert meme.type == "mimeme"
assert meme.contents is None
|
Remove origin from meme model
|
Remove origin from meme model
|
Python
|
mit
|
jcpeterson/Dallinger,suchow/Wallace,suchow/Wallace,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,suchow/Wallace,berkeley-cocosci/Wallace,Dallinger/Dallinger,Dallinger/Dallinger,berkeley-cocosci/Wallace,berkeley-cocosci/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger
|
from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
node = models.Node()
meme = memes.Genome(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
node = models.Node()
meme = memes.Mimeme(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "mimeme"
assert meme.contents is None
Remove origin from meme model
|
from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
meme = memes.Genome()
self.add(meme)
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
meme = memes.Mimeme()
self.add(meme)
assert meme.type == "mimeme"
assert meme.contents is None
|
<commit_before>from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
node = models.Node()
meme = memes.Genome(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
node = models.Node()
meme = memes.Mimeme(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "mimeme"
assert meme.contents is None
<commit_msg>Remove origin from meme model<commit_after>
|
from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
meme = memes.Genome()
self.add(meme)
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
meme = memes.Mimeme()
self.add(meme)
assert meme.type == "mimeme"
assert meme.contents is None
|
from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
node = models.Node()
meme = memes.Genome(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
node = models.Node()
meme = memes.Mimeme(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "mimeme"
assert meme.contents is None
Remove origin from meme modelfrom wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
meme = memes.Genome()
self.add(meme)
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
meme = memes.Mimeme()
self.add(meme)
assert meme.type == "mimeme"
assert meme.contents is None
|
<commit_before>from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
node = models.Node()
meme = memes.Genome(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
node = models.Node()
meme = memes.Mimeme(origin=node)
self.add(node, meme)
assert meme.origin_id == node.id
assert meme.type == "mimeme"
assert meme.contents is None
<commit_msg>Remove origin from meme model<commit_after>from wallace import models, memes, db
class TestMemes(object):
def setup(self):
self.db = db.init_db(drop_all=True)
def teardown(self):
self.db.rollback()
self.db.close()
def add(self, *args):
self.db.add_all(args)
self.db.commit()
def test_create_genome(self):
meme = memes.Genome()
self.add(meme)
assert meme.type == "genome"
assert meme.contents is None
def test_create_mimeme(self):
meme = memes.Mimeme()
self.add(meme)
assert meme.type == "mimeme"
assert meme.contents is None
|
1b103d314e94e3c1dba9d9d08a2655c62f26d18c
|
ibmcnx/doc/DataSources.py
|
ibmcnx/doc/DataSources.py
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = AdminConfig.list( 'DataSource', AdminControl.getCell())
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = '/' + AdminControl.getCell() + '/'
dbs = AdminConfig.list( 'DataSource', cell )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
Create script to save documentation to a file
|
4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4
|
Python
|
apache-2.0
|
stoeps13/ibmcnx2,stoeps13/ibmcnx2
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = AdminConfig.list( 'DataSource', AdminControl.getCell())
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = '/' + AdminControl.getCell() + '/'
dbs = AdminConfig.list( 'DataSource', cell )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
<commit_before>######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = AdminConfig.list( 'DataSource', AdminControl.getCell())
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )<commit_msg>4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4<commit_after>
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = '/' + AdminControl.getCell() + '/'
dbs = AdminConfig.list( 'DataSource', cell )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = AdminConfig.list( 'DataSource', AdminControl.getCell())
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = '/' + AdminControl.getCell() + '/'
dbs = AdminConfig.list( 'DataSource', cell )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
<commit_before>######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = AdminConfig.list( 'DataSource', AdminControl.getCell())
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )<commit_msg>4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4<commit_after>######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = '/' + AdminControl.getCell() + '/'
dbs = AdminConfig.list( 'DataSource', cell )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
291d26c5563307e33f7a4aaee406b75c4b8c591a
|
tulip/tasks_test.py
|
tulip/tasks_test.py
|
"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
res = yield from futures.sleep(dt, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
|
"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
yield from futures.sleep(dt/2)
res = yield from futures.sleep(dt/2, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
|
Test for sleep(dt) without extra arg.
|
Test for sleep(dt) without extra arg.
|
Python
|
apache-2.0
|
gvanrossum/asyncio,gsb-eng/asyncio,gsb-eng/asyncio,manipopopo/asyncio,gvanrossum/asyncio,haypo/trollius,gsb-eng/asyncio,vxgmichel/asyncio,ajdavis/asyncio,fallen/asyncio,jashandeep-sohi/asyncio,haypo/trollius,vxgmichel/asyncio,jashandeep-sohi/asyncio,gvanrossum/asyncio,Martiusweb/asyncio,ajdavis/asyncio,manipopopo/asyncio,vxgmichel/asyncio,ajdavis/asyncio,manipopopo/asyncio,1st1/asyncio,1st1/asyncio,fallen/asyncio,haypo/trollius,jashandeep-sohi/asyncio,Martiusweb/asyncio,fallen/asyncio,1st1/asyncio,Martiusweb/asyncio
|
"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
res = yield from futures.sleep(dt, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
Test for sleep(dt) without extra arg.
|
"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
yield from futures.sleep(dt/2)
res = yield from futures.sleep(dt/2, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
|
<commit_before>"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
res = yield from futures.sleep(dt, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
<commit_msg>Test for sleep(dt) without extra arg.<commit_after>
|
"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
yield from futures.sleep(dt/2)
res = yield from futures.sleep(dt/2, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
|
"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
res = yield from futures.sleep(dt, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
Test for sleep(dt) without extra arg."""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
yield from futures.sleep(dt/2)
res = yield from futures.sleep(dt/2, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
|
<commit_before>"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
res = yield from futures.sleep(dt, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
<commit_msg>Test for sleep(dt) without extra arg.<commit_after>"""Tests for tasks.py."""
import time
import unittest
from . import events
from . import futures
from . import tasks
class TaskTests(unittest.TestCase):
def setUp(self):
self.event_loop = events.new_event_loop()
events.set_event_loop(self.event_loop)
def tearDown(self):
self.event_loop.close()
def testTaskClass(self):
@tasks.coroutine
def notmuch():
yield from []
return 'ok'
t = tasks.Task(notmuch())
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
def testTaskDecorator(self):
@tasks.task
def notmuch():
yield from []
return 'ko'
t = notmuch()
t._event_loop.run()
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ko')
def testSleep(self):
@tasks.coroutine
def sleeper(dt, arg):
yield from futures.sleep(dt/2)
res = yield from futures.sleep(dt/2, arg)
return res
t = tasks.Task(sleeper(0.1, 'yeah'))
t0 = time.monotonic()
t._event_loop.run()
t1 = time.monotonic()
self.assertTrue(t1-t0 >= 0.09)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'yeah')
if __name__ == '__main__':
unittest.main()
|
8832144b3fe0b1e227ebd02b2b3cf8ea5cbcb386
|
introductions/__init__.py
|
introductions/__init__.py
|
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True, 'DB'
except:
return False, 'DB'
SQLAlchemy.health = health
db = SQLAlchemy(app)
Health(app, checks=[db.health])
|
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True, 'DB'
except:
return False, 'DB'
SQLAlchemy.health = health
db = SQLAlchemy(app)
Health(app, checks=[db.health])
|
Add proxy fix as in lr this will run with reverse proxy
|
Add proxy fix as in lr this will run with reverse proxy
|
Python
|
mit
|
LandRegistry/introductions-alpha,LandRegistry/introductions-alpha,LandRegistry/introductions-alpha
|
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True, 'DB'
except:
return False, 'DB'
SQLAlchemy.health = health
db = SQLAlchemy(app)
Health(app, checks=[db.health])
Add proxy fix as in lr this will run with reverse proxy
|
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True, 'DB'
except:
return False, 'DB'
SQLAlchemy.health = health
db = SQLAlchemy(app)
Health(app, checks=[db.health])
|
<commit_before>from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True, 'DB'
except:
return False, 'DB'
SQLAlchemy.health = health
db = SQLAlchemy(app)
Health(app, checks=[db.health])
<commit_msg>Add proxy fix as in lr this will run with reverse proxy<commit_after>
|
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True, 'DB'
except:
return False, 'DB'
SQLAlchemy.health = health
db = SQLAlchemy(app)
Health(app, checks=[db.health])
|
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True, 'DB'
except:
return False, 'DB'
SQLAlchemy.health = health
db = SQLAlchemy(app)
Health(app, checks=[db.health])
Add proxy fix as in lr this will run with reverse proxyfrom flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True, 'DB'
except:
return False, 'DB'
SQLAlchemy.health = health
db = SQLAlchemy(app)
Health(app, checks=[db.health])
|
<commit_before>from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True, 'DB'
except:
return False, 'DB'
SQLAlchemy.health = health
db = SQLAlchemy(app)
Health(app, checks=[db.health])
<commit_msg>Add proxy fix as in lr this will run with reverse proxy<commit_after>from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True, 'DB'
except:
return False, 'DB'
SQLAlchemy.health = health
db = SQLAlchemy(app)
Health(app, checks=[db.health])
|
67be3c3e8ac89f3d8ce36aece39b0bd67fb8fd08
|
src/testers/tls.py
|
src/testers/tls.py
|
# -*- coding: utf-8 -*-
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test):
"""
Check if TLS/SSL is enabled on the server side
"""
if not available(test):
return 3
try:
if 'OpenSSLVersion' in test.tester.info:
return bool(test.tester.info['OpenSSLVersion'])
else:
return test.tester.info['openssl']['running'] != 'disabled'
except KeyError:
return False
def valid(test):
"""
Verify if server certificate is valid
"""
conn = test.tester.conn
if not enabled(test):
return 3
with conn._socket_for_writes() as socket_info:
cert = socket_info.sock.getpeercert()
if not cert:
return [2, 'Your server is presenting a self-signed certificate, which will not '
'protect your connections from man-in-the-middle attacks.']
return True
|
# -*- coding: utf-8 -*-
import ssl
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test):
"""
Check if TLS/SSL is enabled on the server side
"""
if not available(test):
return 3
try:
with test.tester.conn._socket_for_writes() as socket_info:
socket = socket_info.sock
return isinstance(socket, ssl.SSLSocket)
except (KeyError, AttributeError):
return False
def valid(test):
"""
Verify if server certificate is valid
"""
if not enabled(test):
return 3
with test.tester.conn._socket_for_writes() as socket_info:
cert = socket_info.sock.getpeercert()
if not cert:
return [2, 'Your server is presenting a self-signed certificate, which will not '
'protect your connections from man-in-the-middle attacks.']
return True
|
Fix missing parentheses in exception
|
Fix missing parentheses in exception
|
Python
|
mit
|
stampery/mongoaudit
|
# -*- coding: utf-8 -*-
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test):
"""
Check if TLS/SSL is enabled on the server side
"""
if not available(test):
return 3
try:
if 'OpenSSLVersion' in test.tester.info:
return bool(test.tester.info['OpenSSLVersion'])
else:
return test.tester.info['openssl']['running'] != 'disabled'
except KeyError:
return False
def valid(test):
"""
Verify if server certificate is valid
"""
conn = test.tester.conn
if not enabled(test):
return 3
with conn._socket_for_writes() as socket_info:
cert = socket_info.sock.getpeercert()
if not cert:
return [2, 'Your server is presenting a self-signed certificate, which will not '
'protect your connections from man-in-the-middle attacks.']
return True
Fix missing parentheses in exception
|
# -*- coding: utf-8 -*-
import ssl
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test):
"""
Check if TLS/SSL is enabled on the server side
"""
if not available(test):
return 3
try:
with test.tester.conn._socket_for_writes() as socket_info:
socket = socket_info.sock
return isinstance(socket, ssl.SSLSocket)
except (KeyError, AttributeError):
return False
def valid(test):
"""
Verify if server certificate is valid
"""
if not enabled(test):
return 3
with test.tester.conn._socket_for_writes() as socket_info:
cert = socket_info.sock.getpeercert()
if not cert:
return [2, 'Your server is presenting a self-signed certificate, which will not '
'protect your connections from man-in-the-middle attacks.']
return True
|
<commit_before># -*- coding: utf-8 -*-
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test):
"""
Check if TLS/SSL is enabled on the server side
"""
if not available(test):
return 3
try:
if 'OpenSSLVersion' in test.tester.info:
return bool(test.tester.info['OpenSSLVersion'])
else:
return test.tester.info['openssl']['running'] != 'disabled'
except KeyError:
return False
def valid(test):
"""
Verify if server certificate is valid
"""
conn = test.tester.conn
if not enabled(test):
return 3
with conn._socket_for_writes() as socket_info:
cert = socket_info.sock.getpeercert()
if not cert:
return [2, 'Your server is presenting a self-signed certificate, which will not '
'protect your connections from man-in-the-middle attacks.']
return True
<commit_msg>Fix missing parentheses in exception<commit_after>
|
# -*- coding: utf-8 -*-
import ssl
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test):
"""
Check if TLS/SSL is enabled on the server side
"""
if not available(test):
return 3
try:
with test.tester.conn._socket_for_writes() as socket_info:
socket = socket_info.sock
return isinstance(socket, ssl.SSLSocket)
except (KeyError, AttributeError):
return False
def valid(test):
"""
Verify if server certificate is valid
"""
if not enabled(test):
return 3
with test.tester.conn._socket_for_writes() as socket_info:
cert = socket_info.sock.getpeercert()
if not cert:
return [2, 'Your server is presenting a self-signed certificate, which will not '
'protect your connections from man-in-the-middle attacks.']
return True
|
# -*- coding: utf-8 -*-
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test):
"""
Check if TLS/SSL is enabled on the server side
"""
if not available(test):
return 3
try:
if 'OpenSSLVersion' in test.tester.info:
return bool(test.tester.info['OpenSSLVersion'])
else:
return test.tester.info['openssl']['running'] != 'disabled'
except KeyError:
return False
def valid(test):
"""
Verify if server certificate is valid
"""
conn = test.tester.conn
if not enabled(test):
return 3
with conn._socket_for_writes() as socket_info:
cert = socket_info.sock.getpeercert()
if not cert:
return [2, 'Your server is presenting a self-signed certificate, which will not '
'protect your connections from man-in-the-middle attacks.']
return True
Fix missing parentheses in exception# -*- coding: utf-8 -*-
import ssl
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test):
"""
Check if TLS/SSL is enabled on the server side
"""
if not available(test):
return 3
try:
with test.tester.conn._socket_for_writes() as socket_info:
socket = socket_info.sock
return isinstance(socket, ssl.SSLSocket)
except (KeyError, AttributeError):
return False
def valid(test):
"""
Verify if server certificate is valid
"""
if not enabled(test):
return 3
with test.tester.conn._socket_for_writes() as socket_info:
cert = socket_info.sock.getpeercert()
if not cert:
return [2, 'Your server is presenting a self-signed certificate, which will not '
'protect your connections from man-in-the-middle attacks.']
return True
|
<commit_before># -*- coding: utf-8 -*-
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test):
"""
Check if TLS/SSL is enabled on the server side
"""
if not available(test):
return 3
try:
if 'OpenSSLVersion' in test.tester.info:
return bool(test.tester.info['OpenSSLVersion'])
else:
return test.tester.info['openssl']['running'] != 'disabled'
except KeyError:
return False
def valid(test):
"""
Verify if server certificate is valid
"""
conn = test.tester.conn
if not enabled(test):
return 3
with conn._socket_for_writes() as socket_info:
cert = socket_info.sock.getpeercert()
if not cert:
return [2, 'Your server is presenting a self-signed certificate, which will not '
'protect your connections from man-in-the-middle attacks.']
return True
<commit_msg>Fix missing parentheses in exception<commit_after># -*- coding: utf-8 -*-
import ssl
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test):
"""
Check if TLS/SSL is enabled on the server side
"""
if not available(test):
return 3
try:
with test.tester.conn._socket_for_writes() as socket_info:
socket = socket_info.sock
return isinstance(socket, ssl.SSLSocket)
except (KeyError, AttributeError):
return False
def valid(test):
"""
Verify if server certificate is valid
"""
if not enabled(test):
return 3
with test.tester.conn._socket_for_writes() as socket_info:
cert = socket_info.sock.getpeercert()
if not cert:
return [2, 'Your server is presenting a self-signed certificate, which will not '
'protect your connections from man-in-the-middle attacks.']
return True
|
e018f35e51712e4d6a03f5b31e33f61c03365538
|
profiles/views.py
|
profiles/views.py
|
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from comics.models import (
Comic,
Post,
Contributor
)
class ProfileView(DetailView):
template_name="profile.html"
model = User
def dispatch(self, *args, **kwargs):
if kwargs.get('username'):
self.user = get_object_or_404(User, username=kwargs.get('username'))
elif self.request.user:
self.user = self.request.user
else:
raise Http404()
return super(ProfileView, self).dispatch(*args, **kwargs)
def get_object(self):
return self.user
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
contributions = Contributor.objects.filter(contributor=self.user)
comics = Comic.published_comics.filter(post__contributor__in=contributions)
posts = Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post'))
context['posts'] = posts
context['comics'] = comics
return context
|
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from comics.models import (
Comic,
Post,
Contributor
)
class ProfileView(DetailView):
template_name="profile.html"
model = User
def dispatch(self, *args, **kwargs):
if kwargs.get('username'):
self.user = get_object_or_404(User, username=kwargs.get('username'))
elif self.request.user:
self.user = self.request.user
else:
raise Http404()
return super(ProfileView, self).dispatch(*args, **kwargs)
def get_object(self):
return self.user
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
contributions = Contributor.objects.filter(contributor=self.user)
comics = Comic.published_comics.filter(
post__contributor__in=contributions
).order_by('-published')
posts = Post.published_posts.filter(
contributor__in=contributions
).exclude(
id__in=comics.values_list('post')
).order_by('-published')
context['posts'] = posts
context['comics'] = comics
return context
|
Order content on profile by most recent.
|
Order content on profile by most recent.
|
Python
|
mit
|
ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest,ImmaculateObsession/nest
|
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from comics.models import (
Comic,
Post,
Contributor
)
class ProfileView(DetailView):
template_name="profile.html"
model = User
def dispatch(self, *args, **kwargs):
if kwargs.get('username'):
self.user = get_object_or_404(User, username=kwargs.get('username'))
elif self.request.user:
self.user = self.request.user
else:
raise Http404()
return super(ProfileView, self).dispatch(*args, **kwargs)
def get_object(self):
return self.user
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
contributions = Contributor.objects.filter(contributor=self.user)
comics = Comic.published_comics.filter(post__contributor__in=contributions)
posts = Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post'))
context['posts'] = posts
context['comics'] = comics
return contextOrder content on profile by most recent.
|
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from comics.models import (
Comic,
Post,
Contributor
)
class ProfileView(DetailView):
template_name="profile.html"
model = User
def dispatch(self, *args, **kwargs):
if kwargs.get('username'):
self.user = get_object_or_404(User, username=kwargs.get('username'))
elif self.request.user:
self.user = self.request.user
else:
raise Http404()
return super(ProfileView, self).dispatch(*args, **kwargs)
def get_object(self):
return self.user
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
contributions = Contributor.objects.filter(contributor=self.user)
comics = Comic.published_comics.filter(
post__contributor__in=contributions
).order_by('-published')
posts = Post.published_posts.filter(
contributor__in=contributions
).exclude(
id__in=comics.values_list('post')
).order_by('-published')
context['posts'] = posts
context['comics'] = comics
return context
|
<commit_before>from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from comics.models import (
Comic,
Post,
Contributor
)
class ProfileView(DetailView):
template_name="profile.html"
model = User
def dispatch(self, *args, **kwargs):
if kwargs.get('username'):
self.user = get_object_or_404(User, username=kwargs.get('username'))
elif self.request.user:
self.user = self.request.user
else:
raise Http404()
return super(ProfileView, self).dispatch(*args, **kwargs)
def get_object(self):
return self.user
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
contributions = Contributor.objects.filter(contributor=self.user)
comics = Comic.published_comics.filter(post__contributor__in=contributions)
posts = Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post'))
context['posts'] = posts
context['comics'] = comics
return context<commit_msg>Order content on profile by most recent.<commit_after>
|
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from comics.models import (
Comic,
Post,
Contributor
)
class ProfileView(DetailView):
template_name="profile.html"
model = User
def dispatch(self, *args, **kwargs):
if kwargs.get('username'):
self.user = get_object_or_404(User, username=kwargs.get('username'))
elif self.request.user:
self.user = self.request.user
else:
raise Http404()
return super(ProfileView, self).dispatch(*args, **kwargs)
def get_object(self):
return self.user
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
contributions = Contributor.objects.filter(contributor=self.user)
comics = Comic.published_comics.filter(
post__contributor__in=contributions
).order_by('-published')
posts = Post.published_posts.filter(
contributor__in=contributions
).exclude(
id__in=comics.values_list('post')
).order_by('-published')
context['posts'] = posts
context['comics'] = comics
return context
|
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from comics.models import (
Comic,
Post,
Contributor
)
class ProfileView(DetailView):
template_name="profile.html"
model = User
def dispatch(self, *args, **kwargs):
if kwargs.get('username'):
self.user = get_object_or_404(User, username=kwargs.get('username'))
elif self.request.user:
self.user = self.request.user
else:
raise Http404()
return super(ProfileView, self).dispatch(*args, **kwargs)
def get_object(self):
return self.user
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
contributions = Contributor.objects.filter(contributor=self.user)
comics = Comic.published_comics.filter(post__contributor__in=contributions)
posts = Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post'))
context['posts'] = posts
context['comics'] = comics
return contextOrder content on profile by most recent.from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from comics.models import (
Comic,
Post,
Contributor
)
class ProfileView(DetailView):
template_name="profile.html"
model = User
def dispatch(self, *args, **kwargs):
if kwargs.get('username'):
self.user = get_object_or_404(User, username=kwargs.get('username'))
elif self.request.user:
self.user = self.request.user
else:
raise Http404()
return super(ProfileView, self).dispatch(*args, **kwargs)
def get_object(self):
return self.user
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
contributions = Contributor.objects.filter(contributor=self.user)
comics = Comic.published_comics.filter(
post__contributor__in=contributions
).order_by('-published')
posts = Post.published_posts.filter(
contributor__in=contributions
).exclude(
id__in=comics.values_list('post')
).order_by('-published')
context['posts'] = posts
context['comics'] = comics
return context
|
<commit_before>from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from comics.models import (
Comic,
Post,
Contributor
)
class ProfileView(DetailView):
template_name="profile.html"
model = User
def dispatch(self, *args, **kwargs):
if kwargs.get('username'):
self.user = get_object_or_404(User, username=kwargs.get('username'))
elif self.request.user:
self.user = self.request.user
else:
raise Http404()
return super(ProfileView, self).dispatch(*args, **kwargs)
def get_object(self):
return self.user
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
contributions = Contributor.objects.filter(contributor=self.user)
comics = Comic.published_comics.filter(post__contributor__in=contributions)
posts = Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post'))
context['posts'] = posts
context['comics'] = comics
return context<commit_msg>Order content on profile by most recent.<commit_after>from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import Http404
from django.views.generic import DetailView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import get_object_or_404
from comics.models import (
Comic,
Post,
Contributor
)
class ProfileView(DetailView):
template_name="profile.html"
model = User
def dispatch(self, *args, **kwargs):
if kwargs.get('username'):
self.user = get_object_or_404(User, username=kwargs.get('username'))
elif self.request.user:
self.user = self.request.user
else:
raise Http404()
return super(ProfileView, self).dispatch(*args, **kwargs)
def get_object(self):
return self.user
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
contributions = Contributor.objects.filter(contributor=self.user)
comics = Comic.published_comics.filter(
post__contributor__in=contributions
).order_by('-published')
posts = Post.published_posts.filter(
contributor__in=contributions
).exclude(
id__in=comics.values_list('post')
).order_by('-published')
context['posts'] = posts
context['comics'] = comics
return context
|
9d10b74e4ffc5d4f62597ddb6884d35690656172
|
cookiecutter/find.py
|
cookiecutter/find.py
|
# -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {0} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {0}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
|
# -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
|
Remove Python 2.6 compat from format
|
Remove Python 2.6 compat from format
|
Python
|
bsd-3-clause
|
audreyr/cookiecutter,dajose/cookiecutter,hackebrot/cookiecutter,stevepiercy/cookiecutter,michaeljoseph/cookiecutter,dajose/cookiecutter,pjbull/cookiecutter,terryjbates/cookiecutter,luzfcb/cookiecutter,audreyr/cookiecutter,pjbull/cookiecutter,luzfcb/cookiecutter,michaeljoseph/cookiecutter,terryjbates/cookiecutter,stevepiercy/cookiecutter,hackebrot/cookiecutter
|
# -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {0} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {0}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
Remove Python 2.6 compat from format
|
# -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
|
<commit_before># -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {0} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {0}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
<commit_msg>Remove Python 2.6 compat from format<commit_after>
|
# -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
|
# -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {0} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {0}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
Remove Python 2.6 compat from format# -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
|
<commit_before># -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {0} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {0}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
<commit_msg>Remove Python 2.6 compat from format<commit_after># -*- coding: utf-8 -*-
"""Functions for finding Cookiecutter templates and other components."""
import logging
import os
from .exceptions import NonTemplatedInputDirException
logger = logging.getLogger(__name__)
def find_template(repo_dir):
"""Determine which child directory of `repo_dir` is the project template.
:param repo_dir: Local directory of newly cloned repo.
:returns project_template: Relative path to project template.
"""
logger.debug('Searching {} for the project template.'.format(repo_dir))
repo_dir_contents = os.listdir(repo_dir)
project_template = None
for item in repo_dir_contents:
if 'cookiecutter' in item and '{{' in item and '}}' in item:
project_template = item
break
if project_template:
project_template = os.path.join(repo_dir, project_template)
logger.debug(
'The project template appears to be {}'.format(project_template)
)
return project_template
else:
raise NonTemplatedInputDirException
|
9b8a223dc45f133851fac2df564c2c058aafdf91
|
scripts/index.py
|
scripts/index.py
|
from collections import defaultdict
from pathlib import Path
import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
segments = path.split('/')
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
from collections import defaultdict
from pathlib import Path
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
segments = src.parts[1:-1]
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
Use pathlib for path segmentation
|
Use pathlib for path segmentation
|
Python
|
mit
|
yeonghoey/notes,yeonghoey/yeonghoey,yeonghoey/yeonghoey,yeonghoey/yeonghoey,yeonghoey/yeonghoey
|
from collections import defaultdict
from pathlib import Path
import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
segments = path.split('/')
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
Use pathlib for path segmentation
|
from collections import defaultdict
from pathlib import Path
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
segments = src.parts[1:-1]
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
<commit_before>from collections import defaultdict
from pathlib import Path
import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
segments = path.split('/')
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
<commit_msg>Use pathlib for path segmentation<commit_after>
|
from collections import defaultdict
from pathlib import Path
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
segments = src.parts[1:-1]
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
from collections import defaultdict
from pathlib import Path
import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
segments = path.split('/')
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
Use pathlib for path segmentationfrom collections import defaultdict
from pathlib import Path
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
segments = src.parts[1:-1]
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
<commit_before>from collections import defaultdict
from pathlib import Path
import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
segments = path.split('/')
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
<commit_msg>Use pathlib for path segmentation<commit_after>from collections import defaultdict
from pathlib import Path
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
segments = src.parts[1:-1]
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
f2e410492aaaad59fca83d313ec673c1fb411e44
|
astral/api/tests/test_node.py
|
astral/api/tests/test_node.py
|
from nose.tools import eq_
from tornado.httpclient import HTTPRequest
import uuid
from astral.api.tests import BaseTest
from astral.models.node import Node
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = Node(uuid=uuid.getnode())
self.http_client.fetch(HTTPRequest(
self.get_url(node.absolute_url()), 'DELETE'), self.stop)
response = self.wait()
eq_(response.code, 200)
eq_(Node.get_by(uuid=node.uuid), None)
|
from nose.tools import eq_
from tornado.httpclient import HTTPRequest
from astral.api.tests import BaseTest
from astral.models import Node
from astral.models.tests.factories import NodeFactory
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = NodeFactory()
self.http_client.fetch(HTTPRequest(
self.get_url(node.absolute_url()), 'DELETE'), self.stop)
response = self.wait()
eq_(response.code, 200)
eq_(Node.get_by(uuid=node.uuid), None)
|
Build proper Node in tests after refactoring constructor.
|
Build proper Node in tests after refactoring constructor.
|
Python
|
mit
|
peplin/astral
|
from nose.tools import eq_
from tornado.httpclient import HTTPRequest
import uuid
from astral.api.tests import BaseTest
from astral.models.node import Node
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = Node(uuid=uuid.getnode())
self.http_client.fetch(HTTPRequest(
self.get_url(node.absolute_url()), 'DELETE'), self.stop)
response = self.wait()
eq_(response.code, 200)
eq_(Node.get_by(uuid=node.uuid), None)
Build proper Node in tests after refactoring constructor.
|
from nose.tools import eq_
from tornado.httpclient import HTTPRequest
from astral.api.tests import BaseTest
from astral.models import Node
from astral.models.tests.factories import NodeFactory
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = NodeFactory()
self.http_client.fetch(HTTPRequest(
self.get_url(node.absolute_url()), 'DELETE'), self.stop)
response = self.wait()
eq_(response.code, 200)
eq_(Node.get_by(uuid=node.uuid), None)
|
<commit_before>from nose.tools import eq_
from tornado.httpclient import HTTPRequest
import uuid
from astral.api.tests import BaseTest
from astral.models.node import Node
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = Node(uuid=uuid.getnode())
self.http_client.fetch(HTTPRequest(
self.get_url(node.absolute_url()), 'DELETE'), self.stop)
response = self.wait()
eq_(response.code, 200)
eq_(Node.get_by(uuid=node.uuid), None)
<commit_msg>Build proper Node in tests after refactoring constructor.<commit_after>
|
from nose.tools import eq_
from tornado.httpclient import HTTPRequest
from astral.api.tests import BaseTest
from astral.models import Node
from astral.models.tests.factories import NodeFactory
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = NodeFactory()
self.http_client.fetch(HTTPRequest(
self.get_url(node.absolute_url()), 'DELETE'), self.stop)
response = self.wait()
eq_(response.code, 200)
eq_(Node.get_by(uuid=node.uuid), None)
|
from nose.tools import eq_
from tornado.httpclient import HTTPRequest
import uuid
from astral.api.tests import BaseTest
from astral.models.node import Node
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = Node(uuid=uuid.getnode())
self.http_client.fetch(HTTPRequest(
self.get_url(node.absolute_url()), 'DELETE'), self.stop)
response = self.wait()
eq_(response.code, 200)
eq_(Node.get_by(uuid=node.uuid), None)
Build proper Node in tests after refactoring constructor.from nose.tools import eq_
from tornado.httpclient import HTTPRequest
from astral.api.tests import BaseTest
from astral.models import Node
from astral.models.tests.factories import NodeFactory
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = NodeFactory()
self.http_client.fetch(HTTPRequest(
self.get_url(node.absolute_url()), 'DELETE'), self.stop)
response = self.wait()
eq_(response.code, 200)
eq_(Node.get_by(uuid=node.uuid), None)
|
<commit_before>from nose.tools import eq_
from tornado.httpclient import HTTPRequest
import uuid
from astral.api.tests import BaseTest
from astral.models.node import Node
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = Node(uuid=uuid.getnode())
self.http_client.fetch(HTTPRequest(
self.get_url(node.absolute_url()), 'DELETE'), self.stop)
response = self.wait()
eq_(response.code, 200)
eq_(Node.get_by(uuid=node.uuid), None)
<commit_msg>Build proper Node in tests after refactoring constructor.<commit_after>from nose.tools import eq_
from tornado.httpclient import HTTPRequest
from astral.api.tests import BaseTest
from astral.models import Node
from astral.models.tests.factories import NodeFactory
class NodeHandlerTest(BaseTest):
def test_delete_node(self):
node = NodeFactory()
self.http_client.fetch(HTTPRequest(
self.get_url(node.absolute_url()), 'DELETE'), self.stop)
response = self.wait()
eq_(response.code, 200)
eq_(Node.get_by(uuid=node.uuid), None)
|
da98272c3b19828dabbbb339f025c9d3dd4a949e
|
relay_api/core/relay.py
|
relay_api/core/relay.py
|
import RPi.GPIO as GPIO
class relay():
def __init__(self, gpio_num):
self.gpio = gpio_num
GPIO.setmode(GPIO.BCM)
try:
GPIO.input(self.gpio)
raise LookupError("Relay is already in use!")
except RuntimeError:
GPIO.setup(self.gpio, GPIO.OUT)
except ValueError:
raise LookupError("Relay number invalid!")
self.off()
def on(self):
GPIO.output(self.gpio, GPIO.HIGH)
self.state = True
def off(self):
GPIO.output(self.gpio, GPIO.LOW)
self.state = False
def get_state(self):
return self.state
def cleanup(self):
GPIO.cleanup(self.gpio)
|
import RPi.GPIO as GPIO
MAX_RELAY_GPIO = 27
class relay():
def __init__(self, gpio_num):
if gpio_num not in range(MAX_RELAY_GPIO + 1):
raise LookupError("Relay GPIO invalid! Use one between 0 - " +
str(MAX_RELAY_GPIO))
self.gpio = gpio_num
GPIO.setmode(GPIO.BCM)
try:
GPIO.input(self.gpio)
raise LookupError("Relay GPIO is already in use!")
except RuntimeError:
GPIO.setup(self.gpio, GPIO.OUT)
self.off()
def on(self):
GPIO.output(self.gpio, GPIO.HIGH)
self.state = True
def off(self):
GPIO.output(self.gpio, GPIO.LOW)
self.state = False
def get_state(self):
return self.state
def cleanup(self):
GPIO.cleanup(self.gpio)
|
Change the way that GPIO is verified
|
Change the way that GPIO is verified
|
Python
|
mit
|
pahumadad/raspi-relay-api
|
import RPi.GPIO as GPIO
class relay():
def __init__(self, gpio_num):
self.gpio = gpio_num
GPIO.setmode(GPIO.BCM)
try:
GPIO.input(self.gpio)
raise LookupError("Relay is already in use!")
except RuntimeError:
GPIO.setup(self.gpio, GPIO.OUT)
except ValueError:
raise LookupError("Relay number invalid!")
self.off()
def on(self):
GPIO.output(self.gpio, GPIO.HIGH)
self.state = True
def off(self):
GPIO.output(self.gpio, GPIO.LOW)
self.state = False
def get_state(self):
return self.state
def cleanup(self):
GPIO.cleanup(self.gpio)
Change the way that GPIO is verified
|
import RPi.GPIO as GPIO
MAX_RELAY_GPIO = 27
class relay():
def __init__(self, gpio_num):
if gpio_num not in range(MAX_RELAY_GPIO + 1):
raise LookupError("Relay GPIO invalid! Use one between 0 - " +
str(MAX_RELAY_GPIO))
self.gpio = gpio_num
GPIO.setmode(GPIO.BCM)
try:
GPIO.input(self.gpio)
raise LookupError("Relay GPIO is already in use!")
except RuntimeError:
GPIO.setup(self.gpio, GPIO.OUT)
self.off()
def on(self):
GPIO.output(self.gpio, GPIO.HIGH)
self.state = True
def off(self):
GPIO.output(self.gpio, GPIO.LOW)
self.state = False
def get_state(self):
return self.state
def cleanup(self):
GPIO.cleanup(self.gpio)
|
<commit_before>import RPi.GPIO as GPIO
class relay():
def __init__(self, gpio_num):
self.gpio = gpio_num
GPIO.setmode(GPIO.BCM)
try:
GPIO.input(self.gpio)
raise LookupError("Relay is already in use!")
except RuntimeError:
GPIO.setup(self.gpio, GPIO.OUT)
except ValueError:
raise LookupError("Relay number invalid!")
self.off()
def on(self):
GPIO.output(self.gpio, GPIO.HIGH)
self.state = True
def off(self):
GPIO.output(self.gpio, GPIO.LOW)
self.state = False
def get_state(self):
return self.state
def cleanup(self):
GPIO.cleanup(self.gpio)
<commit_msg>Change the way that GPIO is verified<commit_after>
|
import RPi.GPIO as GPIO
MAX_RELAY_GPIO = 27
class relay():
def __init__(self, gpio_num):
if gpio_num not in range(MAX_RELAY_GPIO + 1):
raise LookupError("Relay GPIO invalid! Use one between 0 - " +
str(MAX_RELAY_GPIO))
self.gpio = gpio_num
GPIO.setmode(GPIO.BCM)
try:
GPIO.input(self.gpio)
raise LookupError("Relay GPIO is already in use!")
except RuntimeError:
GPIO.setup(self.gpio, GPIO.OUT)
self.off()
def on(self):
GPIO.output(self.gpio, GPIO.HIGH)
self.state = True
def off(self):
GPIO.output(self.gpio, GPIO.LOW)
self.state = False
def get_state(self):
return self.state
def cleanup(self):
GPIO.cleanup(self.gpio)
|
import RPi.GPIO as GPIO
class relay():
def __init__(self, gpio_num):
self.gpio = gpio_num
GPIO.setmode(GPIO.BCM)
try:
GPIO.input(self.gpio)
raise LookupError("Relay is already in use!")
except RuntimeError:
GPIO.setup(self.gpio, GPIO.OUT)
except ValueError:
raise LookupError("Relay number invalid!")
self.off()
def on(self):
GPIO.output(self.gpio, GPIO.HIGH)
self.state = True
def off(self):
GPIO.output(self.gpio, GPIO.LOW)
self.state = False
def get_state(self):
return self.state
def cleanup(self):
GPIO.cleanup(self.gpio)
Change the way that GPIO is verifiedimport RPi.GPIO as GPIO
MAX_RELAY_GPIO = 27
class relay():
def __init__(self, gpio_num):
if gpio_num not in range(MAX_RELAY_GPIO + 1):
raise LookupError("Relay GPIO invalid! Use one between 0 - " +
str(MAX_RELAY_GPIO))
self.gpio = gpio_num
GPIO.setmode(GPIO.BCM)
try:
GPIO.input(self.gpio)
raise LookupError("Relay GPIO is already in use!")
except RuntimeError:
GPIO.setup(self.gpio, GPIO.OUT)
self.off()
def on(self):
GPIO.output(self.gpio, GPIO.HIGH)
self.state = True
def off(self):
GPIO.output(self.gpio, GPIO.LOW)
self.state = False
def get_state(self):
return self.state
def cleanup(self):
GPIO.cleanup(self.gpio)
|
<commit_before>import RPi.GPIO as GPIO
class relay():
def __init__(self, gpio_num):
self.gpio = gpio_num
GPIO.setmode(GPIO.BCM)
try:
GPIO.input(self.gpio)
raise LookupError("Relay is already in use!")
except RuntimeError:
GPIO.setup(self.gpio, GPIO.OUT)
except ValueError:
raise LookupError("Relay number invalid!")
self.off()
def on(self):
GPIO.output(self.gpio, GPIO.HIGH)
self.state = True
def off(self):
GPIO.output(self.gpio, GPIO.LOW)
self.state = False
def get_state(self):
return self.state
def cleanup(self):
GPIO.cleanup(self.gpio)
<commit_msg>Change the way that GPIO is verified<commit_after>import RPi.GPIO as GPIO
MAX_RELAY_GPIO = 27
class relay():
def __init__(self, gpio_num):
if gpio_num not in range(MAX_RELAY_GPIO + 1):
raise LookupError("Relay GPIO invalid! Use one between 0 - " +
str(MAX_RELAY_GPIO))
self.gpio = gpio_num
GPIO.setmode(GPIO.BCM)
try:
GPIO.input(self.gpio)
raise LookupError("Relay GPIO is already in use!")
except RuntimeError:
GPIO.setup(self.gpio, GPIO.OUT)
self.off()
def on(self):
GPIO.output(self.gpio, GPIO.HIGH)
self.state = True
def off(self):
GPIO.output(self.gpio, GPIO.LOW)
self.state = False
def get_state(self):
return self.state
def cleanup(self):
GPIO.cleanup(self.gpio)
|
66137ab7cc8a0736bbf52a6ded49fd5661ddb68b
|
test/test_files.py
|
test/test_files.py
|
import pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb https://apt.dockerproject.org/repo"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/usr/local/bin/docker-clean.sh", "root", "root", "0755", "/usr/bin/docker"),
])
def test_files(host, name, user, group, mode, contains):
file = host.file(name)
assert file.exists
assert file.user == user
assert file.group == group
assert oct(file.mode) == mode
if file.is_directory is not True:
assert file.contains(contains)
else:
assert file.is_directory
|
import pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb \[arch=amd64\] https://download.docker.com/linux/ubuntu"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/usr/local/bin/docker-clean.sh", "root", "root", "0755", "/usr/bin/docker"),
])
def test_files(host, name, user, group, mode, contains):
file = host.file(name)
assert file.exists
assert file.user == user
assert file.group == group
assert oct(file.mode) == mode
if file.is_directory is not True:
assert file.contains(contains)
else:
assert file.is_directory
|
Update for new docker install
|
Update for new docker install
|
Python
|
mit
|
wicksy/CV,wicksy/CV,wicksy/CV
|
import pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb https://apt.dockerproject.org/repo"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/usr/local/bin/docker-clean.sh", "root", "root", "0755", "/usr/bin/docker"),
])
def test_files(host, name, user, group, mode, contains):
file = host.file(name)
assert file.exists
assert file.user == user
assert file.group == group
assert oct(file.mode) == mode
if file.is_directory is not True:
assert file.contains(contains)
else:
assert file.is_directoryUpdate for new docker install
|
import pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb \[arch=amd64\] https://download.docker.com/linux/ubuntu"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/usr/local/bin/docker-clean.sh", "root", "root", "0755", "/usr/bin/docker"),
])
def test_files(host, name, user, group, mode, contains):
file = host.file(name)
assert file.exists
assert file.user == user
assert file.group == group
assert oct(file.mode) == mode
if file.is_directory is not True:
assert file.contains(contains)
else:
assert file.is_directory
|
<commit_before>import pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb https://apt.dockerproject.org/repo"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/usr/local/bin/docker-clean.sh", "root", "root", "0755", "/usr/bin/docker"),
])
def test_files(host, name, user, group, mode, contains):
file = host.file(name)
assert file.exists
assert file.user == user
assert file.group == group
assert oct(file.mode) == mode
if file.is_directory is not True:
assert file.contains(contains)
else:
assert file.is_directory<commit_msg>Update for new docker install<commit_after>
|
import pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb \[arch=amd64\] https://download.docker.com/linux/ubuntu"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/usr/local/bin/docker-clean.sh", "root", "root", "0755", "/usr/bin/docker"),
])
def test_files(host, name, user, group, mode, contains):
file = host.file(name)
assert file.exists
assert file.user == user
assert file.group == group
assert oct(file.mode) == mode
if file.is_directory is not True:
assert file.contains(contains)
else:
assert file.is_directory
|
import pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb https://apt.dockerproject.org/repo"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/usr/local/bin/docker-clean.sh", "root", "root", "0755", "/usr/bin/docker"),
])
def test_files(host, name, user, group, mode, contains):
file = host.file(name)
assert file.exists
assert file.user == user
assert file.group == group
assert oct(file.mode) == mode
if file.is_directory is not True:
assert file.contains(contains)
else:
assert file.is_directoryUpdate for new docker installimport pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb \[arch=amd64\] https://download.docker.com/linux/ubuntu"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/usr/local/bin/docker-clean.sh", "root", "root", "0755", "/usr/bin/docker"),
])
def test_files(host, name, user, group, mode, contains):
file = host.file(name)
assert file.exists
assert file.user == user
assert file.group == group
assert oct(file.mode) == mode
if file.is_directory is not True:
assert file.contains(contains)
else:
assert file.is_directory
|
<commit_before>import pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb https://apt.dockerproject.org/repo"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/usr/local/bin/docker-clean.sh", "root", "root", "0755", "/usr/bin/docker"),
])
def test_files(host, name, user, group, mode, contains):
file = host.file(name)
assert file.exists
assert file.user == user
assert file.group == group
assert oct(file.mode) == mode
if file.is_directory is not True:
assert file.contains(contains)
else:
assert file.is_directory<commit_msg>Update for new docker install<commit_after>import pytest
@pytest.mark.parametrize("name, user, group, mode, contains", [
("/etc/apt/sources.list.d/docker.list", "root", "root", "0644", "deb \[arch=amd64\] https://download.docker.com/linux/ubuntu"),
("/tmp/docker-lab/", "root", "root", "0755", "null"),
("/tmp/CV/", "root", "root", "0755", "null"),
("/usr/local/bin/docker-clean.sh", "root", "root", "0755", "/usr/bin/docker"),
])
def test_files(host, name, user, group, mode, contains):
file = host.file(name)
assert file.exists
assert file.user == user
assert file.group == group
assert oct(file.mode) == mode
if file.is_directory is not True:
assert file.contains(contains)
else:
assert file.is_directory
|
2c62c7f063af02f6872edd2801c6700bfffeebd4
|
cloud_browser/cloud/config.py
|
cloud_browser/cloud/config.py
|
"""Cloud configuration."""
from cloud_browser.cloud.rackspace import RackspaceConnection
class Config(object):
"""Cloud configuration helper."""
conn_cls = RackspaceConnection
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@classmethod
def from_settings(cls):
"""Create configuration from Django settings or environment."""
from cloud_browser.app_settings import settings
from django.core.exceptions import ImproperlyConfigured
account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
if not (account and secret_key):
raise ImproperlyConfigured("No suitable credentials found.")
conn = cls.conn_cls(account, secret_key, servicenet)
return cls(conn)
@classmethod
def singleton(cls):
"""Get singleton object."""
if cls.__singleton is None:
cls.__singleton = cls.from_settings()
return cls.__singleton
|
"""Cloud configuration."""
class Config(object):
"""Cloud configuration helper."""
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@classmethod
def from_settings(cls):
"""Create configuration from Django settings or environment."""
from cloud_browser.app_settings import settings
from django.core.exceptions import ImproperlyConfigured
conn = None
if conn is None:
# Try Rackspace
account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
if (account and secret_key):
from cloud_browser.cloud.rackspace import RackspaceConnection
conn = RackspaceConnection(account, secret_key, servicenet)
if not conn:
raise ImproperlyConfigured("No suitable credentials found.")
return cls(conn)
@classmethod
def singleton(cls):
"""Get singleton object."""
if cls.__singleton is None:
cls.__singleton = cls.from_settings()
return cls.__singleton
|
Refactor to allow different connection class bindings.
|
Config: Refactor to allow different connection class bindings.
|
Python
|
mit
|
ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser,UrbanDaddy/django-cloud-browser,UrbanDaddy/django-cloud-browser
|
"""Cloud configuration."""
from cloud_browser.cloud.rackspace import RackspaceConnection
class Config(object):
"""Cloud configuration helper."""
conn_cls = RackspaceConnection
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@classmethod
def from_settings(cls):
"""Create configuration from Django settings or environment."""
from cloud_browser.app_settings import settings
from django.core.exceptions import ImproperlyConfigured
account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
if not (account and secret_key):
raise ImproperlyConfigured("No suitable credentials found.")
conn = cls.conn_cls(account, secret_key, servicenet)
return cls(conn)
@classmethod
def singleton(cls):
"""Get singleton object."""
if cls.__singleton is None:
cls.__singleton = cls.from_settings()
return cls.__singleton
Config: Refactor to allow different connection class bindings.
|
"""Cloud configuration."""
class Config(object):
"""Cloud configuration helper."""
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@classmethod
def from_settings(cls):
"""Create configuration from Django settings or environment."""
from cloud_browser.app_settings import settings
from django.core.exceptions import ImproperlyConfigured
conn = None
if conn is None:
# Try Rackspace
account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
if (account and secret_key):
from cloud_browser.cloud.rackspace import RackspaceConnection
conn = RackspaceConnection(account, secret_key, servicenet)
if not conn:
raise ImproperlyConfigured("No suitable credentials found.")
return cls(conn)
@classmethod
def singleton(cls):
"""Get singleton object."""
if cls.__singleton is None:
cls.__singleton = cls.from_settings()
return cls.__singleton
|
<commit_before>"""Cloud configuration."""
from cloud_browser.cloud.rackspace import RackspaceConnection
class Config(object):
"""Cloud configuration helper."""
conn_cls = RackspaceConnection
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@classmethod
def from_settings(cls):
"""Create configuration from Django settings or environment."""
from cloud_browser.app_settings import settings
from django.core.exceptions import ImproperlyConfigured
account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
if not (account and secret_key):
raise ImproperlyConfigured("No suitable credentials found.")
conn = cls.conn_cls(account, secret_key, servicenet)
return cls(conn)
@classmethod
def singleton(cls):
"""Get singleton object."""
if cls.__singleton is None:
cls.__singleton = cls.from_settings()
return cls.__singleton
<commit_msg>Config: Refactor to allow different connection class bindings.<commit_after>
|
"""Cloud configuration."""
class Config(object):
"""Cloud configuration helper."""
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@classmethod
def from_settings(cls):
"""Create configuration from Django settings or environment."""
from cloud_browser.app_settings import settings
from django.core.exceptions import ImproperlyConfigured
conn = None
if conn is None:
# Try Rackspace
account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
if (account and secret_key):
from cloud_browser.cloud.rackspace import RackspaceConnection
conn = RackspaceConnection(account, secret_key, servicenet)
if not conn:
raise ImproperlyConfigured("No suitable credentials found.")
return cls(conn)
@classmethod
def singleton(cls):
"""Get singleton object."""
if cls.__singleton is None:
cls.__singleton = cls.from_settings()
return cls.__singleton
|
"""Cloud configuration."""
from cloud_browser.cloud.rackspace import RackspaceConnection
class Config(object):
"""Cloud configuration helper."""
conn_cls = RackspaceConnection
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@classmethod
def from_settings(cls):
"""Create configuration from Django settings or environment."""
from cloud_browser.app_settings import settings
from django.core.exceptions import ImproperlyConfigured
account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
if not (account and secret_key):
raise ImproperlyConfigured("No suitable credentials found.")
conn = cls.conn_cls(account, secret_key, servicenet)
return cls(conn)
@classmethod
def singleton(cls):
"""Get singleton object."""
if cls.__singleton is None:
cls.__singleton = cls.from_settings()
return cls.__singleton
Config: Refactor to allow different connection class bindings."""Cloud configuration."""
class Config(object):
"""Cloud configuration helper."""
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@classmethod
def from_settings(cls):
"""Create configuration from Django settings or environment."""
from cloud_browser.app_settings import settings
from django.core.exceptions import ImproperlyConfigured
conn = None
if conn is None:
# Try Rackspace
account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
if (account and secret_key):
from cloud_browser.cloud.rackspace import RackspaceConnection
conn = RackspaceConnection(account, secret_key, servicenet)
if not conn:
raise ImproperlyConfigured("No suitable credentials found.")
return cls(conn)
@classmethod
def singleton(cls):
"""Get singleton object."""
if cls.__singleton is None:
cls.__singleton = cls.from_settings()
return cls.__singleton
|
<commit_before>"""Cloud configuration."""
from cloud_browser.cloud.rackspace import RackspaceConnection
class Config(object):
"""Cloud configuration helper."""
conn_cls = RackspaceConnection
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@classmethod
def from_settings(cls):
"""Create configuration from Django settings or environment."""
from cloud_browser.app_settings import settings
from django.core.exceptions import ImproperlyConfigured
account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
if not (account and secret_key):
raise ImproperlyConfigured("No suitable credentials found.")
conn = cls.conn_cls(account, secret_key, servicenet)
return cls(conn)
@classmethod
def singleton(cls):
"""Get singleton object."""
if cls.__singleton is None:
cls.__singleton = cls.from_settings()
return cls.__singleton
<commit_msg>Config: Refactor to allow different connection class bindings.<commit_after>"""Cloud configuration."""
class Config(object):
"""Cloud configuration helper."""
__singleton = None
def __init__(self, connection):
"""Initializer."""
self.connection = connection
@classmethod
def from_settings(cls):
"""Create configuration from Django settings or environment."""
from cloud_browser.app_settings import settings
from django.core.exceptions import ImproperlyConfigured
conn = None
if conn is None:
# Try Rackspace
account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
if (account and secret_key):
from cloud_browser.cloud.rackspace import RackspaceConnection
conn = RackspaceConnection(account, secret_key, servicenet)
if not conn:
raise ImproperlyConfigured("No suitable credentials found.")
return cls(conn)
@classmethod
def singleton(cls):
"""Get singleton object."""
if cls.__singleton is None:
cls.__singleton = cls.from_settings()
return cls.__singleton
|
3be2d3031f878232f38f692b186ea5699b1586ef
|
tm/tmux_wrapper.py
|
tm/tmux_wrapper.py
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
out, err = command("kill-session -t {}".format(session))
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
out, err = command("ls")
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
out, err = command("new -s {}".format(session))
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
out, err = command("attach-session -t {}".format(session))
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
class CommandResponse(object):
def __init__(self, process):
self.process = process
self.out, self.err = process.communicate()
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return CommandResponse(p)
def kill(session):
r = command("kill-session -t {}".format(session))
if "session not found" in r.err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in r.err:
raise ServerConnectionError()
def list():
r = command("ls")
if "failed to connect to server" in r.err:
raise ServerConnectionError()
return r.out
def create(session):
r = command("new -s {}".format(session))
if "duplicate session" in r.err:
raise SessionExists(session)
def attach(session):
r = command("attach-session -t {}".format(session))
if "no sessions" in r.err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
Add CommandResponse class to use instead of (out, err) tuple
|
Add CommandResponse class to use instead of (out, err) tuple
|
Python
|
mit
|
ethanal/tm
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
out, err = command("kill-session -t {}".format(session))
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
out, err = command("ls")
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
out, err = command("new -s {}".format(session))
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
out, err = command("attach-session -t {}".format(session))
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
Add CommandResponse class to use instead of (out, err) tuple
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
class CommandResponse(object):
def __init__(self, process):
self.process = process
self.out, self.err = process.communicate()
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return CommandResponse(p)
def kill(session):
r = command("kill-session -t {}".format(session))
if "session not found" in r.err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in r.err:
raise ServerConnectionError()
def list():
r = command("ls")
if "failed to connect to server" in r.err:
raise ServerConnectionError()
return r.out
def create(session):
r = command("new -s {}".format(session))
if "duplicate session" in r.err:
raise SessionExists(session)
def attach(session):
r = command("attach-session -t {}".format(session))
if "no sessions" in r.err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
<commit_before># -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
out, err = command("kill-session -t {}".format(session))
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
out, err = command("ls")
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
out, err = command("new -s {}".format(session))
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
out, err = command("attach-session -t {}".format(session))
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
<commit_msg>Add CommandResponse class to use instead of (out, err) tuple<commit_after>
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
class CommandResponse(object):
def __init__(self, process):
self.process = process
self.out, self.err = process.communicate()
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return CommandResponse(p)
def kill(session):
r = command("kill-session -t {}".format(session))
if "session not found" in r.err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in r.err:
raise ServerConnectionError()
def list():
r = command("ls")
if "failed to connect to server" in r.err:
raise ServerConnectionError()
return r.out
def create(session):
r = command("new -s {}".format(session))
if "duplicate session" in r.err:
raise SessionExists(session)
def attach(session):
r = command("attach-session -t {}".format(session))
if "no sessions" in r.err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
out, err = command("kill-session -t {}".format(session))
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
out, err = command("ls")
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
out, err = command("new -s {}".format(session))
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
out, err = command("attach-session -t {}".format(session))
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
Add CommandResponse class to use instead of (out, err) tuple# -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
class CommandResponse(object):
def __init__(self, process):
self.process = process
self.out, self.err = process.communicate()
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return CommandResponse(p)
def kill(session):
r = command("kill-session -t {}".format(session))
if "session not found" in r.err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in r.err:
raise ServerConnectionError()
def list():
r = command("ls")
if "failed to connect to server" in r.err:
raise ServerConnectionError()
return r.out
def create(session):
r = command("new -s {}".format(session))
if "duplicate session" in r.err:
raise SessionExists(session)
def attach(session):
r = command("attach-session -t {}".format(session))
if "no sessions" in r.err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
<commit_before># -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
out, err = command("kill-session -t {}".format(session))
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
out, err = command("ls")
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
out, err = command("new -s {}".format(session))
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
out, err = command("attach-session -t {}".format(session))
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
<commit_msg>Add CommandResponse class to use instead of (out, err) tuple<commit_after># -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
class CommandResponse(object):
def __init__(self, process):
self.process = process
self.out, self.err = process.communicate()
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return CommandResponse(p)
def kill(session):
r = command("kill-session -t {}".format(session))
if "session not found" in r.err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in r.err:
raise ServerConnectionError()
def list():
r = command("ls")
if "failed to connect to server" in r.err:
raise ServerConnectionError()
return r.out
def create(session):
r = command("new -s {}".format(session))
if "duplicate session" in r.err:
raise SessionExists(session)
def attach(session):
r = command("attach-session -t {}".format(session))
if "no sessions" in r.err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
3040c42aab5eb09e3e91095ac53b1f3e6b9d7610
|
setup.py
|
setup.py
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except Exception:
return ""
setup(
name="todoist-python",
version="8.1.1",
packages=["todoist", "todoist.managers"],
author="Doist Team",
author_email="info@todoist.com",
license="BSD",
description="todoist-python - The official Todoist Python API library",
long_description=read("README.md"),
install_requires=["requests", "typing"],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except Exception:
return ""
setup(
name="todoist-python",
version="8.1.2",
packages=["todoist", "todoist.managers"],
author="Doist Team",
author_email="info@todoist.com",
license="BSD",
description="todoist-python - The official Todoist Python API library",
long_description=read("README.md"),
install_requires=["requests", "typing"],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
),
)
|
Update the PyPI version to 8.1.2.
|
Update the PyPI version to 8.1.2.
|
Python
|
mit
|
Doist/todoist-python
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except Exception:
return ""
setup(
name="todoist-python",
version="8.1.1",
packages=["todoist", "todoist.managers"],
author="Doist Team",
author_email="info@todoist.com",
license="BSD",
description="todoist-python - The official Todoist Python API library",
long_description=read("README.md"),
install_requires=["requests", "typing"],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
),
)
Update the PyPI version to 8.1.2.
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except Exception:
return ""
setup(
name="todoist-python",
version="8.1.2",
packages=["todoist", "todoist.managers"],
author="Doist Team",
author_email="info@todoist.com",
license="BSD",
description="todoist-python - The official Todoist Python API library",
long_description=read("README.md"),
install_requires=["requests", "typing"],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
),
)
|
<commit_before># -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except Exception:
return ""
setup(
name="todoist-python",
version="8.1.1",
packages=["todoist", "todoist.managers"],
author="Doist Team",
author_email="info@todoist.com",
license="BSD",
description="todoist-python - The official Todoist Python API library",
long_description=read("README.md"),
install_requires=["requests", "typing"],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
),
)
<commit_msg>Update the PyPI version to 8.1.2.<commit_after>
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except Exception:
return ""
setup(
name="todoist-python",
version="8.1.2",
packages=["todoist", "todoist.managers"],
author="Doist Team",
author_email="info@todoist.com",
license="BSD",
description="todoist-python - The official Todoist Python API library",
long_description=read("README.md"),
install_requires=["requests", "typing"],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except Exception:
return ""
setup(
name="todoist-python",
version="8.1.1",
packages=["todoist", "todoist.managers"],
author="Doist Team",
author_email="info@todoist.com",
license="BSD",
description="todoist-python - The official Todoist Python API library",
long_description=read("README.md"),
install_requires=["requests", "typing"],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
),
)
Update the PyPI version to 8.1.2.# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except Exception:
return ""
setup(
name="todoist-python",
version="8.1.2",
packages=["todoist", "todoist.managers"],
author="Doist Team",
author_email="info@todoist.com",
license="BSD",
description="todoist-python - The official Todoist Python API library",
long_description=read("README.md"),
install_requires=["requests", "typing"],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
),
)
|
<commit_before># -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except Exception:
return ""
setup(
name="todoist-python",
version="8.1.1",
packages=["todoist", "todoist.managers"],
author="Doist Team",
author_email="info@todoist.com",
license="BSD",
description="todoist-python - The official Todoist Python API library",
long_description=read("README.md"),
install_requires=["requests", "typing"],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
),
)
<commit_msg>Update the PyPI version to 8.1.2.<commit_after># -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except Exception:
return ""
setup(
name="todoist-python",
version="8.1.2",
packages=["todoist", "todoist.managers"],
author="Doist Team",
author_email="info@todoist.com",
license="BSD",
description="todoist-python - The official Todoist Python API library",
long_description=read("README.md"),
install_requires=["requests", "typing"],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
),
)
|
3277de26d239d5c0420df575b36cb065c033e4ed
|
massa/container.py
|
massa/container.py
|
# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setLevel(c('LOGGER_LEVEL', logging.INFO))
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.addHandler(handler)
return app.logger
return c
|
# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.setLevel(c('LOGGER_LEVEL', logging.INFO))
app.logger.addHandler(handler)
return app.logger
return c
|
Define the log level of the logger instead of the handler.
|
Define the log level of the logger instead of the handler.
|
Python
|
mit
|
jaapverloop/massa
|
# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setLevel(c('LOGGER_LEVEL', logging.INFO))
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.addHandler(handler)
return app.logger
return c
Define the log level of the logger instead of the handler.
|
# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.setLevel(c('LOGGER_LEVEL', logging.INFO))
app.logger.addHandler(handler)
return app.logger
return c
|
<commit_before># -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setLevel(c('LOGGER_LEVEL', logging.INFO))
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.addHandler(handler)
return app.logger
return c
<commit_msg>Define the log level of the logger instead of the handler.<commit_after>
|
# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.setLevel(c('LOGGER_LEVEL', logging.INFO))
app.logger.addHandler(handler)
return app.logger
return c
|
# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setLevel(c('LOGGER_LEVEL', logging.INFO))
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.addHandler(handler)
return app.logger
return c
Define the log level of the logger instead of the handler.# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.setLevel(c('LOGGER_LEVEL', logging.INFO))
app.logger.addHandler(handler)
return app.logger
return c
|
<commit_before># -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setLevel(c('LOGGER_LEVEL', logging.INFO))
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.addHandler(handler)
return app.logger
return c
<commit_msg>Define the log level of the logger instead of the handler.<commit_after># -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
from knot import Container
from sqlalchemy import create_engine
from .domain import Db, MeasurementService
def build(app):
c = Container(app.config)
@c.factory(cache=True)
def db(c):
return Db(create_engine(
c['SQLALCHEMY_DATABASE_URI'],
echo=c['SQLALCHEMY_ECHO']
))
@c.factory(cache=True)
def measurement_service(c):
return MeasurementService(c('db').measurement)
@c.factory(cache=True)
def logger(c):
handler = RotatingFileHandler(
c('LOGGER_FILENAME', '{}.log'.format(app.name)),
maxBytes=c('LOGGER_MAX_BYTES', 1024*1024),
backupCount=c('LOGGER_BACKUP_COUNT', 3)
)
handler.setFormatter(logging.Formatter(
c('LOGGER_FORMAT', "%(asctime)s %(levelname)s: %(message)s")
))
app.logger.setLevel(c('LOGGER_LEVEL', logging.INFO))
app.logger.addHandler(handler)
return app.logger
return c
|
50c4fe78a108ae3ee393777d2f3437c1773cf23f
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha'
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha',
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
Fix for accidental string continuation.
|
Fix for accidental string continuation.
|
Python
|
mit
|
mayfield/cellulario
|
#!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha'
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
Fix for accidental string continuation.
|
#!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha',
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
<commit_before>#!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha'
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
<commit_msg>Fix for accidental string continuation.<commit_after>
|
#!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha',
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha'
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
Fix for accidental string continuation.#!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha',
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
<commit_before>#!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha'
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
<commit_msg>Fix for accidental string continuation.<commit_after>#!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha',
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
6f80fd10cbbc863df3217d2ff903b43bff8f6250
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.2',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
|
#!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.3',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
|
Prepare for release of 0.0.3
|
Prepare for release of 0.0.3
|
Python
|
apache-2.0
|
onedox/tap-awin
|
#!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.2',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
Prepare for release of 0.0.3
|
#!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.3',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
|
<commit_before>#!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.2',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
<commit_msg>Prepare for release of 0.0.3<commit_after>
|
#!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.3',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
|
#!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.2',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
Prepare for release of 0.0.3#!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.3',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
|
<commit_before>#!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.2',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
<commit_msg>Prepare for release of 0.0.3<commit_after>#!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.3',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
|
f80ca8d5bb332d3435eb2c50eb2ad41e287af58e
|
setup.py
|
setup.py
|
import os
from setuptools import setup
NAME = 'sleuth'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
|
import os
from setuptools import setup
NAME = 'sleuth-mock'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
|
Rename package so it doesn't clash
|
Rename package so it doesn't clash
|
Python
|
unlicense
|
Kazade/sleuth
|
import os
from setuptools import setup
NAME = 'sleuth'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
Rename package so it doesn't clash
|
import os
from setuptools import setup
NAME = 'sleuth-mock'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
|
<commit_before>import os
from setuptools import setup
NAME = 'sleuth'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
<commit_msg>Rename package so it doesn't clash<commit_after>
|
import os
from setuptools import setup
NAME = 'sleuth-mock'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
|
import os
from setuptools import setup
NAME = 'sleuth'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
Rename package so it doesn't clashimport os
from setuptools import setup
NAME = 'sleuth-mock'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
|
<commit_before>import os
from setuptools import setup
NAME = 'sleuth'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
<commit_msg>Rename package so it doesn't clash<commit_after>import os
from setuptools import setup
NAME = 'sleuth-mock'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
|
8bdc451dc6ec4b38feb02be25151d9104b90ca65
|
allergies/example.py
|
allergies/example.py
|
class Allergies:
_allergies = [
"eggs",
"peanuts",
"shellfish",
"strawberries",
"tomatoes",
"chocolate",
"pollen",
"cats"
]
def __init__(self, score):
self.score = score
def is_allergic_to(self, allergy):
return self.score & 1 << self._allergies.index(allergy)
@property
def list(self):
return [allergy for allergy in self._allergies
if self.is_allergic_to(allergy)]
|
class Allergies:
_allergies = [
"eggs",
"peanuts",
"shellfish",
"strawberries",
"tomatoes",
"chocolate",
"pollen",
"cats"
]
def __init__(self, score):
self.score = score
def is_allergic_to(self, allergy):
return self.score & 1 << self._allergies.index(allergy)
@property
def lst(self):
return [allergy for allergy in self._allergies
if self.is_allergic_to(allergy)]
|
Rename 'list' to the more pythonic 'lst'
|
allergies: Rename 'list' to the more pythonic 'lst'
|
Python
|
mit
|
Peque/xpython,wobh/xpython,exercism/python,oalbe/xpython,pheanex/xpython,pheanex/xpython,de2Zotjes/xpython,exercism/python,behrtam/xpython,pombredanne/xpython,orozcoadrian/xpython,outkaj/xpython,exercism/xpython,exercism/xpython,jmluy/xpython,rootulp/xpython,pombredanne/xpython,orozcoadrian/xpython,de2Zotjes/xpython,smalley/python,behrtam/xpython,N-Parsons/exercism-python,oalbe/xpython,rootulp/xpython,jmluy/xpython,mweb/python,N-Parsons/exercism-python,outkaj/xpython,smalley/python,mweb/python,wobh/xpython,Peque/xpython
|
class Allergies:
_allergies = [
"eggs",
"peanuts",
"shellfish",
"strawberries",
"tomatoes",
"chocolate",
"pollen",
"cats"
]
def __init__(self, score):
self.score = score
def is_allergic_to(self, allergy):
return self.score & 1 << self._allergies.index(allergy)
@property
def list(self):
return [allergy for allergy in self._allergies
if self.is_allergic_to(allergy)]
allergies: Rename 'list' to the more pythonic 'lst'
|
class Allergies:
_allergies = [
"eggs",
"peanuts",
"shellfish",
"strawberries",
"tomatoes",
"chocolate",
"pollen",
"cats"
]
def __init__(self, score):
self.score = score
def is_allergic_to(self, allergy):
return self.score & 1 << self._allergies.index(allergy)
@property
def lst(self):
return [allergy for allergy in self._allergies
if self.is_allergic_to(allergy)]
|
<commit_before>class Allergies:
_allergies = [
"eggs",
"peanuts",
"shellfish",
"strawberries",
"tomatoes",
"chocolate",
"pollen",
"cats"
]
def __init__(self, score):
self.score = score
def is_allergic_to(self, allergy):
return self.score & 1 << self._allergies.index(allergy)
@property
def list(self):
return [allergy for allergy in self._allergies
if self.is_allergic_to(allergy)]
<commit_msg>allergies: Rename 'list' to the more pythonic 'lst'<commit_after>
|
class Allergies:
_allergies = [
"eggs",
"peanuts",
"shellfish",
"strawberries",
"tomatoes",
"chocolate",
"pollen",
"cats"
]
def __init__(self, score):
self.score = score
def is_allergic_to(self, allergy):
return self.score & 1 << self._allergies.index(allergy)
@property
def lst(self):
return [allergy for allergy in self._allergies
if self.is_allergic_to(allergy)]
|
class Allergies:
_allergies = [
"eggs",
"peanuts",
"shellfish",
"strawberries",
"tomatoes",
"chocolate",
"pollen",
"cats"
]
def __init__(self, score):
self.score = score
def is_allergic_to(self, allergy):
return self.score & 1 << self._allergies.index(allergy)
@property
def list(self):
return [allergy for allergy in self._allergies
if self.is_allergic_to(allergy)]
allergies: Rename 'list' to the more pythonic 'lst'class Allergies:
_allergies = [
"eggs",
"peanuts",
"shellfish",
"strawberries",
"tomatoes",
"chocolate",
"pollen",
"cats"
]
def __init__(self, score):
self.score = score
def is_allergic_to(self, allergy):
return self.score & 1 << self._allergies.index(allergy)
@property
def lst(self):
return [allergy for allergy in self._allergies
if self.is_allergic_to(allergy)]
|
<commit_before>class Allergies:
_allergies = [
"eggs",
"peanuts",
"shellfish",
"strawberries",
"tomatoes",
"chocolate",
"pollen",
"cats"
]
def __init__(self, score):
self.score = score
def is_allergic_to(self, allergy):
return self.score & 1 << self._allergies.index(allergy)
@property
def list(self):
return [allergy for allergy in self._allergies
if self.is_allergic_to(allergy)]
<commit_msg>allergies: Rename 'list' to the more pythonic 'lst'<commit_after>class Allergies:
_allergies = [
"eggs",
"peanuts",
"shellfish",
"strawberries",
"tomatoes",
"chocolate",
"pollen",
"cats"
]
def __init__(self, score):
self.score = score
def is_allergic_to(self, allergy):
return self.score & 1 << self._allergies.index(allergy)
@property
def lst(self):
return [allergy for allergy in self._allergies
if self.is_allergic_to(allergy)]
|
f54324c13a21eeee1b90781efb7c132eeba16d44
|
tweepy/__init__.py
|
tweepy/__init__.py
|
# Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE
"""
Tweepy Twitter API library
"""
__version__ = '1.0'
from . models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, models
from . error import TweepError
from . api import API
from . cache import Cache, MemoryCache, FileCache, MemCache
from . auth import BasicAuthHandler, OAuthHandler
from . streaming import Stream, StreamListener
# Global, unauthenticated instance of API
api = API()
|
# Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE
"""
Tweepy Twitter API library
"""
__version__ = '1.0.1'
from . models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, models
from . error import TweepError
from . api import API
from . cache import Cache, MemoryCache, FileCache, MemCache
from . auth import BasicAuthHandler, OAuthHandler
from . streaming import Stream, StreamListener
# Global, unauthenticated instance of API
api = API()
|
Increment tweepy version to 1.0.1
|
Increment tweepy version to 1.0.1
|
Python
|
mit
|
damchilly/tweepy,ze-phyr-us/tweepy,yared-bezum/tweepy,Choko256/tweepy,xrg/tweepy,truekonrads/tweepy,takeshineshiro/tweepy,vivek8943/tweepy,thelostscientist/tweepy,atomicjets/tweepy,elijah513/tweepy,kcompher/tweepy,srimanthd/tweepy,nickmalleson/tweepy,wjt/tweepy,tsablic/tweepy,cogniteev/tweepy,awangga/tweepy,alexhanna/tweepy,xrg/tweepy,mlinsey/tweepy,arunxarun/tweepy,kskk02/tweepy,cinemapub/bright-response,techieshark/tweepy,aganzha/tweepy,kylemanna/tweepy,IsaacHaze/tweepy,hackebrot/tweepy,tweepy/tweepy,conversocial/tweepy,sidewire/tweepy,nickmalleson/tweepy,robbiewoods05/tweepy,abhishekgahlot/tweepy,vikasgorur/tweepy,abhishekgahlot/tweepy,ze-phyr-us/tweepy,nickmalleson/tweepy,iamjakob/tweepy,raymondethan/tweepy,cinemapub/bright-response,arpithparikh/tweepy,aleczadikian/tweepy,jperecharla/tweepy,markunsworth/tweepy,markunsworth/tweepy,alexhanna/tweepy,sa8/tweepy,LikeABird/tweepy,bconnelly/tweepy,vishnugonela/tweepy,obskyr/tweepy,svven/tweepy,zhenv5/tweepy,nickmalleson/tweepy,tuxos/tweepy,rudraksh125/tweepy,edsu/tweepy
|
# Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE
"""
Tweepy Twitter API library
"""
__version__ = '1.0'
from . models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, models
from . error import TweepError
from . api import API
from . cache import Cache, MemoryCache, FileCache, MemCache
from . auth import BasicAuthHandler, OAuthHandler
from . streaming import Stream, StreamListener
# Global, unauthenticated instance of API
api = API()
Increment tweepy version to 1.0.1
|
# Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE
"""
Tweepy Twitter API library
"""
__version__ = '1.0.1'
from . models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, models
from . error import TweepError
from . api import API
from . cache import Cache, MemoryCache, FileCache, MemCache
from . auth import BasicAuthHandler, OAuthHandler
from . streaming import Stream, StreamListener
# Global, unauthenticated instance of API
api = API()
|
<commit_before># Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE
"""
Tweepy Twitter API library
"""
__version__ = '1.0'
from . models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, models
from . error import TweepError
from . api import API
from . cache import Cache, MemoryCache, FileCache, MemCache
from . auth import BasicAuthHandler, OAuthHandler
from . streaming import Stream, StreamListener
# Global, unauthenticated instance of API
api = API()
<commit_msg>Increment tweepy version to 1.0.1<commit_after>
|
# Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE
"""
Tweepy Twitter API library
"""
__version__ = '1.0.1'
from . models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, models
from . error import TweepError
from . api import API
from . cache import Cache, MemoryCache, FileCache, MemCache
from . auth import BasicAuthHandler, OAuthHandler
from . streaming import Stream, StreamListener
# Global, unauthenticated instance of API
api = API()
|
# Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE
"""
Tweepy Twitter API library
"""
__version__ = '1.0'
from . models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, models
from . error import TweepError
from . api import API
from . cache import Cache, MemoryCache, FileCache, MemCache
from . auth import BasicAuthHandler, OAuthHandler
from . streaming import Stream, StreamListener
# Global, unauthenticated instance of API
api = API()
Increment tweepy version to 1.0.1# Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE
"""
Tweepy Twitter API library
"""
__version__ = '1.0.1'
from . models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, models
from . error import TweepError
from . api import API
from . cache import Cache, MemoryCache, FileCache, MemCache
from . auth import BasicAuthHandler, OAuthHandler
from . streaming import Stream, StreamListener
# Global, unauthenticated instance of API
api = API()
|
<commit_before># Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE
"""
Tweepy Twitter API library
"""
__version__ = '1.0'
from . models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, models
from . error import TweepError
from . api import API
from . cache import Cache, MemoryCache, FileCache, MemCache
from . auth import BasicAuthHandler, OAuthHandler
from . streaming import Stream, StreamListener
# Global, unauthenticated instance of API
api = API()
<commit_msg>Increment tweepy version to 1.0.1<commit_after># Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE
"""
Tweepy Twitter API library
"""
__version__ = '1.0.1'
from . models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResult, models
from . error import TweepError
from . api import API
from . cache import Cache, MemoryCache, FileCache, MemCache
from . auth import BasicAuthHandler, OAuthHandler
from . streaming import Stream, StreamListener
# Global, unauthenticated instance of API
api = API()
|
08ecc9aaf3398a0dd69bf27fc65c8ca744f98e4b
|
Orange/tests/test_naive_bayes.py
|
Orange/tests/test_naive_bayes.py
|
import unittest
import numpy as np
from Orange import data
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 5, (nrows, ncols))
x[:, 0] = np.ones(nrows) * 3
y = x[:, ncols / 2].reshape(nrows, 1)
table = data.Table(x, y)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.5)
|
import unittest
import numpy as np
import Orange
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = Orange.data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 4, (nrows, ncols))
x[:, 0] = 3
y = x[:, ncols // 2].reshape(nrows, 1)
continuous_table = Orange.data.Table(x, y)
table = Orange.data.discretization.DiscretizeTable(continuous_table)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.6)
|
Improve naive bayes unit test.
|
Improve naive bayes unit test.
|
Python
|
bsd-2-clause
|
cheral/orange3,qusp/orange3,qPCR4vir/orange3,cheral/orange3,qusp/orange3,qusp/orange3,cheral/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,marinkaz/orange3,kwikadi/orange3,qPCR4vir/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,qPCR4vir/orange3,marinkaz/orange3,kwikadi/orange3,marinkaz/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,qusp/orange3,kwikadi/orange3,kwikadi/orange3,marinkaz/orange3,cheral/orange3
|
import unittest
import numpy as np
from Orange import data
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 5, (nrows, ncols))
x[:, 0] = np.ones(nrows) * 3
y = x[:, ncols / 2].reshape(nrows, 1)
table = data.Table(x, y)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.5)
Improve naive bayes unit test.
|
import unittest
import numpy as np
import Orange
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = Orange.data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 4, (nrows, ncols))
x[:, 0] = 3
y = x[:, ncols // 2].reshape(nrows, 1)
continuous_table = Orange.data.Table(x, y)
table = Orange.data.discretization.DiscretizeTable(continuous_table)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.6)
|
<commit_before>import unittest
import numpy as np
from Orange import data
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 5, (nrows, ncols))
x[:, 0] = np.ones(nrows) * 3
y = x[:, ncols / 2].reshape(nrows, 1)
table = data.Table(x, y)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.5)
<commit_msg>Improve naive bayes unit test.<commit_after>
|
import unittest
import numpy as np
import Orange
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = Orange.data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 4, (nrows, ncols))
x[:, 0] = 3
y = x[:, ncols // 2].reshape(nrows, 1)
continuous_table = Orange.data.Table(x, y)
table = Orange.data.discretization.DiscretizeTable(continuous_table)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.6)
|
import unittest
import numpy as np
from Orange import data
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 5, (nrows, ncols))
x[:, 0] = np.ones(nrows) * 3
y = x[:, ncols / 2].reshape(nrows, 1)
table = data.Table(x, y)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.5)
Improve naive bayes unit test.import unittest
import numpy as np
import Orange
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = Orange.data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 4, (nrows, ncols))
x[:, 0] = 3
y = x[:, ncols // 2].reshape(nrows, 1)
continuous_table = Orange.data.Table(x, y)
table = Orange.data.discretization.DiscretizeTable(continuous_table)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.6)
|
<commit_before>import unittest
import numpy as np
from Orange import data
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 5, (nrows, ncols))
x[:, 0] = np.ones(nrows) * 3
y = x[:, ncols / 2].reshape(nrows, 1)
table = data.Table(x, y)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.5)
<commit_msg>Improve naive bayes unit test.<commit_after>import unittest
import numpy as np
import Orange
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = Orange.data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 4, (nrows, ncols))
x[:, 0] = 3
y = x[:, ncols // 2].reshape(nrows, 1)
continuous_table = Orange.data.Table(x, y)
table = Orange.data.discretization.DiscretizeTable(continuous_table)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.6)
|
9704602f26b4a9aab15caf00795d283c5f6e4ae4
|
src/fiona/tool.py
|
src/fiona/tool.py
|
# The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='store_true',
help='View pretty printed description information only')
parser.add_argument('-j', '--json',
action='store_true',
help='Output description as indented JSON')
parser.add_argument('filename', help="data file name")
args = parser.parse_args()
with fiona.open(args.filename, 'r') as col:
if args.info:
if args.json:
meta = col.meta.copy()
meta.update(name=args.filename)
print(json.dumps(meta, indent=2))
else:
print("\nDescription of: %r" % col)
print("\nCoordinate reference system (col.crs):")
pprint.pprint(meta['crs'])
print("\nFormat driver (col.driver):")
pprint.pprint(meta['driver'])
print("\nData description (col.schema):")
pprint.pprint(meta['schema'])
else:
print(json.dumps(list(col), indent=2))
|
# The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='store_true',
help='View pretty printed description information only')
parser.add_argument('-j', '--json',
action='store_true',
help='Output description as indented JSON')
parser.add_argument('filename', help="data file name")
args = parser.parse_args()
with fiona.open(args.filename, 'r') as col:
if args.info:
if args.json:
meta = col.meta.copy()
meta.update(name=args.filename)
print(json.dumps(meta, indent=2))
else:
print("\nDescription of: %r" % col)
print("\nCoordinate reference system (col.crs):")
pprint.pprint(meta['crs'])
print("\nFormat driver (col.driver):")
pprint.pprint(meta['driver'])
print("\nData description (col.schema):")
pprint.pprint(meta['schema'])
else:
collection = {'type': 'FeatureCollection'}
collection['features'] = list(col)
print(json.dumps(collection, indent=2))
|
Change record output to strict GeoJSON.
|
Change record output to strict GeoJSON.
Meaning features in a FeatureCollection.
|
Python
|
bsd-3-clause
|
rbuffat/Fiona,Toblerity/Fiona,sgillies/Fiona,johanvdw/Fiona,perrygeo/Fiona,Toblerity/Fiona,perrygeo/Fiona,rbuffat/Fiona
|
# The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='store_true',
help='View pretty printed description information only')
parser.add_argument('-j', '--json',
action='store_true',
help='Output description as indented JSON')
parser.add_argument('filename', help="data file name")
args = parser.parse_args()
with fiona.open(args.filename, 'r') as col:
if args.info:
if args.json:
meta = col.meta.copy()
meta.update(name=args.filename)
print(json.dumps(meta, indent=2))
else:
print("\nDescription of: %r" % col)
print("\nCoordinate reference system (col.crs):")
pprint.pprint(meta['crs'])
print("\nFormat driver (col.driver):")
pprint.pprint(meta['driver'])
print("\nData description (col.schema):")
pprint.pprint(meta['schema'])
else:
print(json.dumps(list(col), indent=2))
Change record output to strict GeoJSON.
Meaning features in a FeatureCollection.
|
# The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='store_true',
help='View pretty printed description information only')
parser.add_argument('-j', '--json',
action='store_true',
help='Output description as indented JSON')
parser.add_argument('filename', help="data file name")
args = parser.parse_args()
with fiona.open(args.filename, 'r') as col:
if args.info:
if args.json:
meta = col.meta.copy()
meta.update(name=args.filename)
print(json.dumps(meta, indent=2))
else:
print("\nDescription of: %r" % col)
print("\nCoordinate reference system (col.crs):")
pprint.pprint(meta['crs'])
print("\nFormat driver (col.driver):")
pprint.pprint(meta['driver'])
print("\nData description (col.schema):")
pprint.pprint(meta['schema'])
else:
collection = {'type': 'FeatureCollection'}
collection['features'] = list(col)
print(json.dumps(collection, indent=2))
|
<commit_before># The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='store_true',
help='View pretty printed description information only')
parser.add_argument('-j', '--json',
action='store_true',
help='Output description as indented JSON')
parser.add_argument('filename', help="data file name")
args = parser.parse_args()
with fiona.open(args.filename, 'r') as col:
if args.info:
if args.json:
meta = col.meta.copy()
meta.update(name=args.filename)
print(json.dumps(meta, indent=2))
else:
print("\nDescription of: %r" % col)
print("\nCoordinate reference system (col.crs):")
pprint.pprint(meta['crs'])
print("\nFormat driver (col.driver):")
pprint.pprint(meta['driver'])
print("\nData description (col.schema):")
pprint.pprint(meta['schema'])
else:
print(json.dumps(list(col), indent=2))
<commit_msg>Change record output to strict GeoJSON.
Meaning features in a FeatureCollection.<commit_after>
|
# The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='store_true',
help='View pretty printed description information only')
parser.add_argument('-j', '--json',
action='store_true',
help='Output description as indented JSON')
parser.add_argument('filename', help="data file name")
args = parser.parse_args()
with fiona.open(args.filename, 'r') as col:
if args.info:
if args.json:
meta = col.meta.copy()
meta.update(name=args.filename)
print(json.dumps(meta, indent=2))
else:
print("\nDescription of: %r" % col)
print("\nCoordinate reference system (col.crs):")
pprint.pprint(meta['crs'])
print("\nFormat driver (col.driver):")
pprint.pprint(meta['driver'])
print("\nData description (col.schema):")
pprint.pprint(meta['schema'])
else:
collection = {'type': 'FeatureCollection'}
collection['features'] = list(col)
print(json.dumps(collection, indent=2))
|
# The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='store_true',
help='View pretty printed description information only')
parser.add_argument('-j', '--json',
action='store_true',
help='Output description as indented JSON')
parser.add_argument('filename', help="data file name")
args = parser.parse_args()
with fiona.open(args.filename, 'r') as col:
if args.info:
if args.json:
meta = col.meta.copy()
meta.update(name=args.filename)
print(json.dumps(meta, indent=2))
else:
print("\nDescription of: %r" % col)
print("\nCoordinate reference system (col.crs):")
pprint.pprint(meta['crs'])
print("\nFormat driver (col.driver):")
pprint.pprint(meta['driver'])
print("\nData description (col.schema):")
pprint.pprint(meta['schema'])
else:
print(json.dumps(list(col), indent=2))
Change record output to strict GeoJSON.
Meaning features in a FeatureCollection.# The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='store_true',
help='View pretty printed description information only')
parser.add_argument('-j', '--json',
action='store_true',
help='Output description as indented JSON')
parser.add_argument('filename', help="data file name")
args = parser.parse_args()
with fiona.open(args.filename, 'r') as col:
if args.info:
if args.json:
meta = col.meta.copy()
meta.update(name=args.filename)
print(json.dumps(meta, indent=2))
else:
print("\nDescription of: %r" % col)
print("\nCoordinate reference system (col.crs):")
pprint.pprint(meta['crs'])
print("\nFormat driver (col.driver):")
pprint.pprint(meta['driver'])
print("\nData description (col.schema):")
pprint.pprint(meta['schema'])
else:
collection = {'type': 'FeatureCollection'}
collection['features'] = list(col)
print(json.dumps(collection, indent=2))
|
<commit_before># The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='store_true',
help='View pretty printed description information only')
parser.add_argument('-j', '--json',
action='store_true',
help='Output description as indented JSON')
parser.add_argument('filename', help="data file name")
args = parser.parse_args()
with fiona.open(args.filename, 'r') as col:
if args.info:
if args.json:
meta = col.meta.copy()
meta.update(name=args.filename)
print(json.dumps(meta, indent=2))
else:
print("\nDescription of: %r" % col)
print("\nCoordinate reference system (col.crs):")
pprint.pprint(meta['crs'])
print("\nFormat driver (col.driver):")
pprint.pprint(meta['driver'])
print("\nData description (col.schema):")
pprint.pprint(meta['schema'])
else:
print(json.dumps(list(col), indent=2))
<commit_msg>Change record output to strict GeoJSON.
Meaning features in a FeatureCollection.<commit_after># The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='store_true',
help='View pretty printed description information only')
parser.add_argument('-j', '--json',
action='store_true',
help='Output description as indented JSON')
parser.add_argument('filename', help="data file name")
args = parser.parse_args()
with fiona.open(args.filename, 'r') as col:
if args.info:
if args.json:
meta = col.meta.copy()
meta.update(name=args.filename)
print(json.dumps(meta, indent=2))
else:
print("\nDescription of: %r" % col)
print("\nCoordinate reference system (col.crs):")
pprint.pprint(meta['crs'])
print("\nFormat driver (col.driver):")
pprint.pprint(meta['driver'])
print("\nData description (col.schema):")
pprint.pprint(meta['schema'])
else:
collection = {'type': 'FeatureCollection'}
collection['features'] = list(col)
print(json.dumps(collection, indent=2))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.