commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
b9b7fb6f4a7c334f56a9a6cd34c50124008adb26
apps/homepage/model.py
apps/homepage/model.py
from django.utils.timezone import now from apps.banners.models import Slide from apps.campaigns.models import Campaign from apps.fundraisers.models import FundRaiser from apps.projects.models import Project from apps.quotes.models import Quote from apps.statistics.models import Statistic # Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object class HomePage(object): def get(self, language): self.id = 1 self.quotes= Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) stats = Statistic.objects.order_by('-creation_date').all() if len(stats) > 0: self.stats = stats[0] else: self.stats = None projects = Project.objects.filter(phase='campaign').order_by('?') if len(projects) > 4: self.projects = projects[0:4] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: self.projects = None try: self.campaign = Campaign.objects.get(start__lte=now(), end__gte=now()) # NOTE: MultipleObjectsReturned is not caught yet! self.fundraisers = FundRaiser.objects.filter(project__is_campaign=True).order_by('?') except Campaign.DoesNotExist: self.campaign, self.fundraisers = None, None return self
from django.utils.timezone import now from apps.banners.models import Slide from apps.campaigns.models import Campaign from apps.fundraisers.models import FundRaiser from apps.projects.models import Project from apps.quotes.models import Quote from apps.statistics.models import Statistic # Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object class HomePage(object): def get(self, language): self.id = 1 self.quotes= Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) stats = Statistic.objects.order_by('-creation_date').all() if len(stats) > 0: self.stats = stats[0] else: self.stats = None projects = Project.objects.filter(phase='campaign').order_by('?') if len(projects) > 4: self.projects = projects[0:4] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: self.projects = None try: self.campaign = Campaign.objects.get(start__lte=now(), end__gte=now()) # NOTE: MultipleObjectsReturned is not caught yet! self.fundraisers = FundRaiser.objects.filter(project__is_campaign=True).order_by('-created') except Campaign.DoesNotExist: self.campaign, self.fundraisers = None, None return self
Sort fundraiser on newest on hp
Sort fundraiser on newest on hp
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
--- +++ @@ -32,7 +32,7 @@ try: self.campaign = Campaign.objects.get(start__lte=now(), end__gte=now()) # NOTE: MultipleObjectsReturned is not caught yet! - self.fundraisers = FundRaiser.objects.filter(project__is_campaign=True).order_by('?') + self.fundraisers = FundRaiser.objects.filter(project__is_campaign=True).order_by('-created') except Campaign.DoesNotExist: self.campaign, self.fundraisers = None, None
8bd47ec3983981d0a2ac8d9f9c17f4c1c9c8fbd3
apps/profiles/tests.py
apps/profiles/tests.py
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.core.urlresolvers import reverse from django.test import TestCase from django_dynamic_fixture import G from rest_framework import status from apps.authentication.models import OnlineUser as User class ProfilesURLTestCase(TestCase): def test_user_search(self): user = G(User) url = reverse('profiles_user_search') self.client.force_login(user) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK)
from django.core.urlresolvers import reverse from django.test import TestCase from django_dynamic_fixture import G from rest_framework import status from apps.authentication.models import OnlineUser as User from apps.profiles.forms import ProfileForm class ProfilesURLTestCase(TestCase): def test_user_search(self): user = G(User) url = reverse('profiles_user_search') self.client.force_login(user) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) class ProfileViewEditTestCase(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls._url = reverse('profile_edit') cls._user = G(User) def setUp(self): self.client.force_login(self._user) def test_profile_retrieve(self): response = self.client.get(self._url) self.assertEqual(200, response.status_code) def test_profile_save(self): response = self.client.post(self._url) self.assertEqual(200, response.status_code) def test_profile_save_valid_zip(self): data = { 'zip_code': 7030 } response = self.client.post(self._url, data) self.assertEqual(200, response.status_code) class ProfileEditFormTestCase(TestCase): def test_profile_form_valid_zip(self): data = { 'gender': 'male', 'zip_code': 7030 } form = ProfileForm(data=data) self.assertTrue(form.is_valid()) def test_profile_form_invalid_zip(self): data = { 'gender': 'male', 'zip_code': 123 } form = ProfileForm(data=data) self.assertFalse(form.is_valid())
Test that saving ProfileForm works
Test that saving ProfileForm works
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
--- +++ @@ -1,15 +1,10 @@ -""" -This file demonstrates writing tests using the unittest module. These will pass -when you run "manage.py test". - -Replace this with more appropriate tests for your application. -""" from django.core.urlresolvers import reverse from django.test import TestCase from django_dynamic_fixture import G from rest_framework import status from apps.authentication.models import OnlineUser as User +from apps.profiles.forms import ProfileForm class ProfilesURLTestCase(TestCase): @@ -22,3 +17,53 @@ response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class ProfileViewEditTestCase(TestCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls._url = reverse('profile_edit') + cls._user = G(User) + + def setUp(self): + self.client.force_login(self._user) + + def test_profile_retrieve(self): + response = self.client.get(self._url) + + self.assertEqual(200, response.status_code) + + def test_profile_save(self): + response = self.client.post(self._url) + + self.assertEqual(200, response.status_code) + + def test_profile_save_valid_zip(self): + data = { + 'zip_code': 7030 + } + + response = self.client.post(self._url, data) + + self.assertEqual(200, response.status_code) + + +class ProfileEditFormTestCase(TestCase): + def test_profile_form_valid_zip(self): + data = { + 'gender': 'male', + 'zip_code': 7030 + } + form = ProfileForm(data=data) + + self.assertTrue(form.is_valid()) + + def test_profile_form_invalid_zip(self): + data = { + 'gender': 'male', + 'zip_code': 123 + } + form = ProfileForm(data=data) + + self.assertFalse(form.is_valid())
308cbf1f62e254643a0ad47db8ad55eb63e1c888
argonauts/testutils.py
argonauts/testutils.py
import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset or settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestCase(TestCase): client_class = JsonTestClient
import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset or settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestMixin(object): client_class = JsonTestClient class JsonTestCase(JsonTestMixin, TestCase): pass
Make the TestCase a mixin
Make the TestCase a mixin
Python
bsd-2-clause
fusionbox/django-argonauts
--- +++ @@ -4,7 +4,7 @@ from django.conf import settings from django.test import Client, TestCase -__all__ = ['JsonTestClient', 'JsonTestCase'] +__all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): @@ -34,5 +34,8 @@ return super(JsonTestClient, self).__getattribute__(attr) -class JsonTestCase(TestCase): +class JsonTestMixin(object): client_class = JsonTestClient + +class JsonTestCase(JsonTestMixin, TestCase): + pass
456e5a63333e683b7167bf151b97a49a5cf5c5fe
app/models/job.py
app/models/job.py
# Copyright (C) 2014 Linaro Ltd. # # 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/>. from base import BaseDocument JOB_COLLECTION = 'job' class JobDocument(BaseDocument): JOB_ID_FORMAT = '%s-%s' def __init__(self, name): super(JobDocument, self).__init__(name) @property def collection(self): return JOB_COLLECTION
# Copyright (C) 2014 Linaro Ltd. # # 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/>. from base import BaseDocument JOB_COLLECTION = 'job' class JobDocument(BaseDocument): JOB_ID_FORMAT = '%s-%s' def __init__(self, name, job=None, kernel=None): super(JobDocument, self).__init__(name) self._private = False self._job = job self._kernel = kernel self._created = None @property def collection(self): return JOB_COLLECTION @property def private(self): return self._private @private.setter def private(self, value): self._private = value @property def job(self): return self._job @job.setter def job(self, value): self._job = value @property def kernel(self): return self._kernel @kernel.setter def kernel(self, value): self._kernel = value @property def created(self): return self._created @created.setter def created(self, value): self._created = value def to_dict(self): job_dict = super(JobDocument, self).to_dict() job_dict['private'] = self._private job_dict['job'] = self._job job_dict['kernel'] = self._kernel job_dict['created'] = str(self._created) return job_dict
Rework the jod document model.
Rework the jod document model. * Add the created field that will store a datetime object. * Add reference to the kernel and the job inside the document, without relying on the Jod document name itself. Since we use the dash as a separator, and other job names can have dash in them, we cannot separate job from kernel easily.
Python
agpl-3.0
joyxu/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend,kernelci/kernelci-backend,joyxu/kernelci-backend
--- +++ @@ -22,9 +22,54 @@ JOB_ID_FORMAT = '%s-%s' - def __init__(self, name): + def __init__(self, name, job=None, kernel=None): super(JobDocument, self).__init__(name) + + self._private = False + self._job = job + self._kernel = kernel + self._created = None @property def collection(self): return JOB_COLLECTION + + @property + def private(self): + return self._private + + @private.setter + def private(self, value): + self._private = value + + @property + def job(self): + return self._job + + @job.setter + def job(self, value): + self._job = value + + @property + def kernel(self): + return self._kernel + + @kernel.setter + def kernel(self, value): + self._kernel = value + + @property + def created(self): + return self._created + + @created.setter + def created(self, value): + self._created = value + + def to_dict(self): + job_dict = super(JobDocument, self).to_dict() + job_dict['private'] = self._private + job_dict['job'] = self._job + job_dict['kernel'] = self._kernel + job_dict['created'] = str(self._created) + return job_dict
4b7713a1891aa86c0f16fafdea8770495070bfcb
html_snapshots/utils.py
html_snapshots/utils.py
import os import rmc.shared.constants as c import rmc.models as m FILE_DIR = os.path.dirname(os.path.realpath(__file__)) HTML_DIR = os.path.join(c.SHARED_DATA_DIR, 'html_snapshots') def write(file_path, content): ensure_dir(file_path) with open(file_path, 'w') as f: f.write(content) def ensure_dir(file_path): d = os.path.dirname(file_path) if not os.path.exists(d): os.makedirs(d) def generate_urls(): urls = [] # Home page urls.append('') # Course pages for course in m.Course.objects: course_id = course.id urls.append('course/' + course_id) return urls
import os import mongoengine as me import rmc.shared.constants as c import rmc.models as m FILE_DIR = os.path.dirname(os.path.realpath(__file__)) HTML_DIR = os.path.join(c.SHARED_DATA_DIR, 'html_snapshots') me.connect(c.MONGO_DB_RMC, host=c.MONGO_HOST, port=c.MONGO_PORT) def write(file_path, content): ensure_dir(file_path) with open(file_path, 'w') as f: f.write(content) def ensure_dir(file_path): d = os.path.dirname(file_path) if not os.path.exists(d): os.makedirs(d) def generate_urls(): urls = [] # Home page urls.append('') # Course pages for course in m.Course.objects: course_id = course.id urls.append('course/' + course_id) return urls
Create mongoengine connection when taking phantom snapshots
Create mongoengine connection when taking phantom snapshots
Python
mit
ccqi/rmc,JGulbronson/rmc,JGulbronson/rmc,UWFlow/rmc,shakilkanji/rmc,ccqi/rmc,UWFlow/rmc,sachdevs/rmc,sachdevs/rmc,MichalKononenko/rmc,UWFlow/rmc,MichalKononenko/rmc,sachdevs/rmc,duaayousif/rmc,MichalKononenko/rmc,MichalKononenko/rmc,JGulbronson/rmc,ccqi/rmc,JGulbronson/rmc,sachdevs/rmc,UWFlow/rmc,UWFlow/rmc,duaayousif/rmc,ccqi/rmc,shakilkanji/rmc,ccqi/rmc,rageandqq/rmc,JGulbronson/rmc,rageandqq/rmc,rageandqq/rmc,MichalKononenko/rmc,shakilkanji/rmc,duaayousif/rmc,shakilkanji/rmc,duaayousif/rmc,rageandqq/rmc,rageandqq/rmc,sachdevs/rmc,duaayousif/rmc,shakilkanji/rmc
--- +++ @@ -1,10 +1,14 @@ import os + +import mongoengine as me import rmc.shared.constants as c import rmc.models as m FILE_DIR = os.path.dirname(os.path.realpath(__file__)) HTML_DIR = os.path.join(c.SHARED_DATA_DIR, 'html_snapshots') + +me.connect(c.MONGO_DB_RMC, host=c.MONGO_HOST, port=c.MONGO_PORT) def write(file_path, content):
e3dcbe5fb142b7ce564a90cf127de418d0a62db3
src/sentry/runner/hacks.py
src/sentry/runner/hacks.py
""" sentry.runner.hacks ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function from sentry.http import get_server_hostname class AllowedHosts(object): # HACK: This is a fake stub for settings.ALLOWED_HOSTS # This is needing since ALLOWED_HOSTS is engrained # in Django internals, so we want this "tuple" to respond # to runtime changes based on our system.url-prefix Option def __iter__(self): yield get_server_hostname() or '*'
""" sentry.runner.hacks ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function from sentry.http import get_server_hostname class AllowedHosts(object): # HACK: This is a fake stub for settings.ALLOWED_HOSTS # This is needing since ALLOWED_HOSTS is engrained # in Django internals, so we want this "tuple" to respond # to runtime changes based on our system.url-prefix Option def __iter__(self): yield get_server_hostname() or '*' def __repr__(self): return repr(tuple(self))
Add a nice repr for AllowedHosts object so the admin makes sense
Add a nice repr for AllowedHosts object so the admin makes sense
Python
bsd-3-clause
fotinakis/sentry,daevaorn/sentry,beeftornado/sentry,daevaorn/sentry,ifduyue/sentry,alexm92/sentry,ifduyue/sentry,JamesMura/sentry,JamesMura/sentry,alexm92/sentry,jean/sentry,BuildingLink/sentry,JackDanger/sentry,gencer/sentry,nicholasserra/sentry,jean/sentry,ifduyue/sentry,mvaled/sentry,ifduyue/sentry,zenefits/sentry,zenefits/sentry,fotinakis/sentry,JamesMura/sentry,gencer/sentry,nicholasserra/sentry,gencer/sentry,mvaled/sentry,looker/sentry,looker/sentry,BuildingLink/sentry,mvaled/sentry,jean/sentry,beeftornado/sentry,mvaled/sentry,JackDanger/sentry,fotinakis/sentry,JamesMura/sentry,mitsuhiko/sentry,looker/sentry,daevaorn/sentry,JamesMura/sentry,mvaled/sentry,mitsuhiko/sentry,ifduyue/sentry,daevaorn/sentry,jean/sentry,nicholasserra/sentry,BuildingLink/sentry,zenefits/sentry,jean/sentry,zenefits/sentry,BuildingLink/sentry,zenefits/sentry,gencer/sentry,looker/sentry,fotinakis/sentry,mvaled/sentry,looker/sentry,JackDanger/sentry,BuildingLink/sentry,gencer/sentry,beeftornado/sentry,alexm92/sentry
--- +++ @@ -17,3 +17,6 @@ # to runtime changes based on our system.url-prefix Option def __iter__(self): yield get_server_hostname() or '*' + + def __repr__(self): + return repr(tuple(self))
1ef9c5c76e1c1110803d83833fc69ba201d33582
pavement.py
pavement.py
# -*- coding: utf-8 -*- from paver.easy import task, sh, needs, path from paver.setuputils import setup setup(name='ldapom', version='0.9.4', description='A simple ldap object mapper for python', author='Florian Richter', author_email='mail@f1ori.de', url='https://github.com/HaDiNet/ldapom', license='MIT', keywords = "ldap object mapper", long_description=path('README').text(), py_modules=['ldapom'], ) @task def docs(options): sh('doxygen') @task def test(options): sh('python tests.py') @task def coverage(options): sh('coverage run --source ldapom.py ./tests.py') sh('coverage xml')
# -*- coding: utf-8 -*- from paver.easy import * @task def test(options): info("Running tests for Python 2") sh('python2 tests.py') info("Running tests for Python 3") sh('python3 tests.py') @task def coverage(options): info("Running coverage for Python 2") sh('coverage2 run --source ldapom.py ./tests.py') sh('coverage2 report') info("Running coverage for Python 3") sh('coverage3 run --source ldapom.py ./tests.py') sh('coverage3 report')
Update paver to test and report coverage for both Python 2 and 3
Update paver to test and report coverage for both Python 2 and 3
Python
mit
HaDiNet/ldapom
--- +++ @@ -1,29 +1,19 @@ # -*- coding: utf-8 -*- -from paver.easy import task, sh, needs, path -from paver.setuputils import setup - -setup(name='ldapom', - version='0.9.4', - description='A simple ldap object mapper for python', - author='Florian Richter', - author_email='mail@f1ori.de', - url='https://github.com/HaDiNet/ldapom', - license='MIT', - keywords = "ldap object mapper", - long_description=path('README').text(), - py_modules=['ldapom'], - ) - -@task -def docs(options): - sh('doxygen') +from paver.easy import * @task def test(options): - sh('python tests.py') + info("Running tests for Python 2") + sh('python2 tests.py') + info("Running tests for Python 3") + sh('python3 tests.py') @task def coverage(options): - sh('coverage run --source ldapom.py ./tests.py') - sh('coverage xml') + info("Running coverage for Python 2") + sh('coverage2 run --source ldapom.py ./tests.py') + sh('coverage2 report') + info("Running coverage for Python 3") + sh('coverage3 run --source ldapom.py ./tests.py') + sh('coverage3 report')
05742ef5fb1f163750679ae56ab5ea97f7050811
tests/test_apps_up.py
tests/test_apps_up.py
import os import pytest import requests REGISTER_TITLE_URL = os.environ['DIGITAL_REGISTER_URL'] USERNAME = os.environ['SMOKE_USERNAME'] PASSWORD = os.environ['SMOKE_PASSWORD'] TITLE_NUMBER = os.environ['SMOKE_TITLE_NUMBER'] PARTIAL_ADDRESS = os.environ['SMOKE_PARTIAL_ADDRESS'] POSTCODE = os.environ['SMOKE_POSTCODE'] def test_frontend_up(): # login stuff response = requests.post('{}/login?next=titles'.format(REGISTER_TITLE_URL), data={'username': USERNAME, 'password': PASSWORD}, follow_redirects=False) import pdb; pdb.set_trace()
import os import pytest import requests REGISTER_TITLE_URL = os.environ['DIGITAL_REGISTER_URL'] USERNAME = os.environ['SMOKE_USERNAME'] PASSWORD = os.environ['SMOKE_PASSWORD'] TITLE_NUMBER = os.environ['SMOKE_TITLE_NUMBER'] PARTIAL_ADDRESS = os.environ['SMOKE_PARTIAL_ADDRESS'] POSTCODE = os.environ['SMOKE_POSTCODE'] def test_frontend_up(): # login stuff response = requests.post('{}/login?next=titles'.format(REGISTER_TITLE_URL), data={'username': USERNAME, 'password': PASSWORD}, allow_redirects=False) import pdb; pdb.set_trace()
Use correct kwarg for requests.post()
Use correct kwarg for requests.post()
Python
mit
LandRegistry/digital-register-smoke-tests,LandRegistry/digital-register-smoke-tests
--- +++ @@ -15,5 +15,5 @@ # login stuff response = requests.post('{}/login?next=titles'.format(REGISTER_TITLE_URL), data={'username': USERNAME, 'password': PASSWORD}, - follow_redirects=False) + allow_redirects=False) import pdb; pdb.set_trace()
abe744c5a099fd988ff3fe5eb1d50cca7a633d74
var/spack/repos/builtin/packages/parallel-netcdf/package.py
var/spack/repos/builtin/packages/parallel-netcdf/package.py
from spack import * class ParallelNetcdf(Package): """Parallel netCDF (PnetCDF) is a library providing high-performance parallel I/O while still maintaining file-format compatibility with Unidata's NetCDF.""" homepage = "https://trac.mcs.anl.gov/projects/parallel-netcdf" url = "http://cucis.ece.northwestern.edu/projects/PnetCDF/Release/parallel-netcdf-1.6.1.tar.gz" version('1.6.1', '62a094eb952f9d1e15f07d56e535052604f1ac34') depends_on("m4") depends_on("mpi") def install(self, spec, prefix): configure("--prefix=%s" % prefix, "--with-mpi=%s" % spec['mpi'].prefix) make() make("install")
from spack import * class ParallelNetcdf(Package): """Parallel netCDF (PnetCDF) is a library providing high-performance parallel I/O while still maintaining file-format compatibility with Unidata's NetCDF.""" homepage = "https://trac.mcs.anl.gov/projects/parallel-netcdf" url = "http://cucis.ece.northwestern.edu/projects/PnetCDF/Release/parallel-netcdf-1.6.1.tar.gz" version('1.7.0', '267eab7b6f9dc78c4d0e6def2def3aea4bc7c9f0') version('1.6.1', '62a094eb952f9d1e15f07d56e535052604f1ac34') depends_on("m4") depends_on("mpi") def install(self, spec, prefix): configure("--prefix=%s" % prefix, "--with-mpi=%s" % spec['mpi'].prefix) make() make("install")
Add latest version of PnetCDF
Add latest version of PnetCDF
Python
lgpl-2.1
mfherbst/spack,EmreAtes/spack,lgarren/spack,tmerrick1/spack,matthiasdiener/spack,skosukhin/spack,tmerrick1/spack,iulian787/spack,skosukhin/spack,LLNL/spack,matthiasdiener/spack,iulian787/spack,krafczyk/spack,TheTimmy/spack,mfherbst/spack,LLNL/spack,mfherbst/spack,EmreAtes/spack,tmerrick1/spack,mfherbst/spack,TheTimmy/spack,krafczyk/spack,EmreAtes/spack,iulian787/spack,iulian787/spack,lgarren/spack,LLNL/spack,lgarren/spack,lgarren/spack,matthiasdiener/spack,iulian787/spack,skosukhin/spack,mfherbst/spack,lgarren/spack,matthiasdiener/spack,tmerrick1/spack,matthiasdiener/spack,LLNL/spack,skosukhin/spack,krafczyk/spack,EmreAtes/spack,LLNL/spack,TheTimmy/spack,TheTimmy/spack,skosukhin/spack,EmreAtes/spack,tmerrick1/spack,krafczyk/spack,TheTimmy/spack,krafczyk/spack
--- +++ @@ -8,6 +8,7 @@ homepage = "https://trac.mcs.anl.gov/projects/parallel-netcdf" url = "http://cucis.ece.northwestern.edu/projects/PnetCDF/Release/parallel-netcdf-1.6.1.tar.gz" + version('1.7.0', '267eab7b6f9dc78c4d0e6def2def3aea4bc7c9f0') version('1.6.1', '62a094eb952f9d1e15f07d56e535052604f1ac34') depends_on("m4")
8297d4a8650b94bee6aa2c9a83b699f443596ce6
stagecraft/tools/txex-migration.py
stagecraft/tools/txex-migration.py
#!/usr/bin/env python import os import sys try: username = os.environ['GOOGLE_USERNAME'] password = os.environ['GOOGLE_PASSWORD'] except KeyError: print("Please supply username (GOOGLE_USERNAME)" "and password (GOOGLE_PASSWORD) as environment variables") sys.exit(1) column_positions = { 'names_name': 7, 'names_slug': 8, 'names_service_name': 5, 'names_service_slug': 6, 'names_tx_id_column': 17 } from spreadsheets import SpreadsheetMunger munger = SpreadsheetMunger(column_positions) print munger.load(username, password)
#!/usr/bin/env python import os import sys try: username = os.environ['GOOGLE_USERNAME'] password = os.environ['GOOGLE_PASSWORD'] except KeyError: print("Please supply username (GOOGLE_USERNAME)" "and password (GOOGLE_PASSWORD) as environment variables") sys.exit(1) column_positions = { 'names_name': 8, 'names_slug': 9, 'names_service_name': 6, 'names_service_slug': 7, 'names_tx_id_column': 18 } from spreadsheets import SpreadsheetMunger munger = SpreadsheetMunger(column_positions) print munger.load(username, password)
Fix column positions to reflect current spreadsheet.
Fix column positions to reflect current spreadsheet.
Python
mit
alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft
--- +++ @@ -12,11 +12,11 @@ sys.exit(1) column_positions = { - 'names_name': 7, - 'names_slug': 8, - 'names_service_name': 5, - 'names_service_slug': 6, - 'names_tx_id_column': 17 + 'names_name': 8, + 'names_slug': 9, + 'names_service_name': 6, + 'names_service_slug': 7, + 'names_tx_id_column': 18 } from spreadsheets import SpreadsheetMunger
b9bfabe2648dbc7604488b7bda5c53e460155072
glharvest/tests/test_void.py
glharvest/tests/test_void.py
"""test_void.py Test the parsing of VoID dump files. """ try: import RDF except ImportError: import sys sys.path.append('/usr/lib/python2.7/dist-packages/') import RDF from glharvest import util, void def test_returns_none_if_the_registry_file_is_not_found(): m = util.load_file_into_model("nonexistantvoidfile.ttl") assert m is None def test_can_load_a_simple_void_file(): m = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle') p = void.parse_void_model(m) assert p == { 'http://lod.dataone.org/test': { 'dataDump': 'http://lod.dataone.org/test.ttl', 'features': [ 'http://lod.dataone.org/fulldump' ] } }
"""test_void.py Test the parsing of VoID dump files. """ try: import RDF except ImportError: import sys sys.path.append('/usr/lib/python2.7/dist-packages/') import RDF from glharvest import util, void def test_returns_none_if_the_registry_file_is_not_found(): m = util.load_file_into_model("nonexistantvoidfile.ttl") assert m is None def test_can_load_a_simple_void_file(): m = util.load_file_into_model('tests/data/simple-void.ttl', 'turtle') p = void.parse_void_model(m) assert p == { 'http://lod.dataone.org/test': { 'dumps': ['http://lod.dataone.org/test.ttl'], 'features': [ 'http://lod.dataone.org/fulldump' ] } }
Update void test to reflect the new void model structure
Update void test to reflect the new void model structure The first version I coded up only allowed for a single dump in each dataset. The most current version expects an array of dumps so I needed to update the test.
Python
apache-2.0
ec-geolink/glharvest,ec-geolink/glharvest,ec-geolink/glharvest
--- +++ @@ -26,7 +26,7 @@ p = void.parse_void_model(m) assert p == { 'http://lod.dataone.org/test': { - 'dataDump': 'http://lod.dataone.org/test.ttl', + 'dumps': ['http://lod.dataone.org/test.ttl'], 'features': [ 'http://lod.dataone.org/fulldump' ]
cdc5627cfad3b4fb413bed86d76dbe083e6727a7
hnotebook/notebooks/admin.py
hnotebook/notebooks/admin.py
from django.contrib import admin # Register your models here.
from django.contrib import admin from .models import Notebook class NotebookAdmin(admin.ModelAdmin): model = Notebook admin.site.register(Notebook, NotebookAdmin)
Add Admin for Notebook model
Add Admin for Notebook model
Python
mit
marcwebbie/hnotebook
--- +++ @@ -1,3 +1,8 @@ from django.contrib import admin -# Register your models here. +from .models import Notebook + +class NotebookAdmin(admin.ModelAdmin): + model = Notebook + +admin.site.register(Notebook, NotebookAdmin)
f09208c047de7c31b9a76d903aa996bf74a3159c
bin/targetselection.py
bin/targetselection.py
import numpy from desitarget.io import read_tractor, write_targets from desitarget.cuts import LRG, ELG, BGS, QSO from desitarget import targetmask from argparse import ArgumentParser ap = ArgumentParser() ap.add_argument("--type", choices=["tractor"], default="tractor", help="Assume a type for src files") ap.add_argument("src", help="File that stores Candidates/Objects") ap.add_argument("dest", help="File that stores targets") TYPES = { 'LRG': LRG, 'ELG': ELG, 'BGS': BGS, 'QSO': QSO, } def main(): ns = ap.parse_args() candidates = read_tractor(ns.src) # FIXME: fits doesn't like u8; there must be a workaround # but lets stick with i8 for now. tsbits = numpy.zeros(len(candidates), dtype='i8') for t in TYPES.keys(): cut = TYPES[t] bitfield = targetmask.mask(t) with numpy.errstate(all='ignore'): mask = cut.apply(candidates) tsbits[mask] |= bitfield assert ((tsbits & bitfield) != 0).sum() == mask.sum() print (t, 'selected', mask.sum()) write_targets(ns.dest, candidates, tsbits) print ('written to', ns.dest) if __name__ == "__main__": main()
from __future__ import print_function import numpy from desitarget.io import read_tractor, write_targets from desitarget.cuts import LRG, ELG, BGS, QSO from desitarget import targetmask from argparse import ArgumentParser ap = ArgumentParser() ap.add_argument("--type", choices=["tractor"], default="tractor", help="Assume a type for src files") ap.add_argument("src", help="File that stores Candidates/Objects") ap.add_argument("dest", help="File that stores targets") TYPES = { 'LRG': LRG, 'ELG': ELG, 'BGS': BGS, 'QSO': QSO, } def main(): ns = ap.parse_args() candidates = read_tractor(ns.src) # FIXME: fits doesn't like u8; there must be a workaround # but lets stick with i8 for now. tsbits = numpy.zeros(len(candidates), dtype='i8') for t in TYPES.keys(): cut = TYPES[t] bitfield = targetmask.mask(t) with numpy.errstate(all='ignore'): mask = cut.apply(candidates) tsbits[mask] |= bitfield assert ((tsbits & bitfield) != 0).sum() == mask.sum() print (t, 'selected', mask.sum()) write_targets(ns.dest, candidates, tsbits) print ('written to', ns.dest) if __name__ == "__main__": main()
Use print_function in toplevel script.
Use print_function in toplevel script. (Avoid logging hassle for now)
Python
bsd-3-clause
desihub/desitarget,desihub/desitarget
--- +++ @@ -1,3 +1,4 @@ +from __future__ import print_function import numpy from desitarget.io import read_tractor, write_targets from desitarget.cuts import LRG, ELG, BGS, QSO
75a59409410a8f264e7d56ddd853002ffbb28600
corehq/tests/noseplugins/patches.py
corehq/tests/noseplugins/patches.py
from nose.plugins import Plugin from corehq.form_processor.tests.utils import patch_testcase_databases from corehq.util.es.testing import patch_es_user_signals from corehq.util.test_utils import patch_foreign_value_caches class PatchesPlugin(Plugin): """Patches various things before tests are run""" name = "patches" enabled = True def options(self, parser, env): """Do not call super (always enabled)""" def begin(self): patch_assertItemsEqual() patch_testcase_databases() fix_freezegun_bugs() patch_es_user_signals() patch_foreign_value_caches() def patch_assertItemsEqual(): import unittest unittest.TestCase.assertItemsEqual = unittest.TestCase.assertCountEqual GLOBAL_FREEZEGUN_IGNORE_LIST = ["kafka."] def fix_freezegun_bugs(): """Fix error in freezegun.api.freeze_time This error occurs in a background thread that is either triggered by a test using freezegun or becomes active while freezegun patches are in place. More complete error details: ``` Exception in thread cchq-producer-network-thread: Traceback (most recent call last): ... freezegun/api.py", line 151, in _should_use_real_time if not ignore_lists[-1]: IndexError: list index out of range ``` """ import freezegun.api as api def freeze_time(*args, **kw): kw["ignore"] = kw.get("ignore", []) + GLOBAL_FREEZEGUN_IGNORE_LIST return real_freeze_time(*args, **kw) # add base ignore list to avoid index error assert not api.ignore_lists, f"expected empty list, got {api.ignore_lists}" api.ignore_lists.append(tuple(GLOBAL_FREEZEGUN_IGNORE_LIST)) # patch freeze_time so it always ignores kafka real_freeze_time = api.freeze_time api.freeze_time = freeze_time
from nose.plugins import Plugin from corehq.form_processor.tests.utils import patch_testcase_databases from corehq.util.es.testing import patch_es_user_signals from corehq.util.test_utils import patch_foreign_value_caches class PatchesPlugin(Plugin): """Patches various things before tests are run""" name = "patches" enabled = True def options(self, parser, env): """Do not call super (always enabled)""" def begin(self): patch_assertItemsEqual() patch_testcase_databases() extend_freezegun_ignore_list() patch_es_user_signals() patch_foreign_value_caches() def patch_assertItemsEqual(): import unittest unittest.TestCase.assertItemsEqual = unittest.TestCase.assertCountEqual GLOBAL_FREEZEGUN_IGNORE_LIST = ["kafka."] def extend_freezegun_ignore_list(): """Extend the freezegun ignore list""" import freezegun freezegun.configure(extend_ignore_list=GLOBAL_FREEZEGUN_IGNORE_LIST)
Update freezegun ignore list patch
Update freezegun ignore list patch As of v1.1.0, freezegun supports configuring the ignore list.
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -16,7 +16,7 @@ def begin(self): patch_assertItemsEqual() patch_testcase_databases() - fix_freezegun_bugs() + extend_freezegun_ignore_list() patch_es_user_signals() patch_foreign_value_caches() @@ -29,33 +29,8 @@ GLOBAL_FREEZEGUN_IGNORE_LIST = ["kafka."] -def fix_freezegun_bugs(): - """Fix error in freezegun.api.freeze_time +def extend_freezegun_ignore_list(): + """Extend the freezegun ignore list""" + import freezegun - This error occurs in a background thread that is either triggered by - a test using freezegun or becomes active while freezegun patches are - in place. - - More complete error details: - ``` - Exception in thread cchq-producer-network-thread: - Traceback (most recent call last): - ... - freezegun/api.py", line 151, in _should_use_real_time - if not ignore_lists[-1]: - IndexError: list index out of range - ``` - """ - import freezegun.api as api - - def freeze_time(*args, **kw): - kw["ignore"] = kw.get("ignore", []) + GLOBAL_FREEZEGUN_IGNORE_LIST - return real_freeze_time(*args, **kw) - - # add base ignore list to avoid index error - assert not api.ignore_lists, f"expected empty list, got {api.ignore_lists}" - api.ignore_lists.append(tuple(GLOBAL_FREEZEGUN_IGNORE_LIST)) - - # patch freeze_time so it always ignores kafka - real_freeze_time = api.freeze_time - api.freeze_time = freeze_time + freezegun.configure(extend_ignore_list=GLOBAL_FREEZEGUN_IGNORE_LIST)
9f3cf22575d9d71136bea0282ac0e0420211d9c9
test/test_util/test_StopWatch.py
test/test_util/test_StopWatch.py
# -*- encoding: utf-8 -*- """Created on Dec 16, 2014. @author: Katharina Eggensperger @projekt: AutoML2015 """ from __future__ import print_function import time import unittest from autosklearn.util import StopWatch class Test(unittest.TestCase): _multiprocess_can_split_ = True def test_stopwatch_overhead(self): # CPU overhead start = time.clock() watch = StopWatch() for i in range(1, 100000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.clock() dur = stop - start cpu_overhead = dur - watch.cpu_sum() self.assertLess(cpu_overhead, 1.5) # Wall Overhead start = time.time() watch = StopWatch() for i in range(1, 100000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.time() dur = stop - start wall_overhead = dur - watch.wall_sum() self.assertLess(wall_overhead, 2) self.assertLess(cpu_overhead, 2*wall_overhead) if __name__ == '__main__': # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
# -*- encoding: utf-8 -*- """Created on Dec 16, 2014. @author: Katharina Eggensperger @projekt: AutoML2015 """ from __future__ import print_function import time import unittest from autosklearn.util import StopWatch class Test(unittest.TestCase): _multiprocess_can_split_ = True def test_stopwatch_overhead(self): # CPU overhead start = time.clock() watch = StopWatch() for i in range(1, 1000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.clock() dur = stop - start cpu_overhead = dur - watch.cpu_sum() self.assertLess(cpu_overhead, 1.5) # Wall Overhead start = time.time() watch = StopWatch() for i in range(1, 1000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.time() dur = stop - start wall_overhead = dur - watch.wall_sum() self.assertLess(wall_overhead, 2) self.assertLess(cpu_overhead, 2*wall_overhead) if __name__ == '__main__': # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
TEST reduce number of iterations for stopwatch test
TEST reduce number of iterations for stopwatch test
Python
bsd-3-clause
automl/auto-sklearn,automl/auto-sklearn
--- +++ @@ -20,7 +20,7 @@ # CPU overhead start = time.clock() watch = StopWatch() - for i in range(1, 100000): + for i in range(1, 1000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.clock() @@ -31,7 +31,7 @@ # Wall Overhead start = time.time() watch = StopWatch() - for i in range(1, 100000): + for i in range(1, 1000): watch.start_task('task_%d' % i) watch.stop_task('task_%d' % i) stop = time.time()
29f8aacde96007976b0aa0cde6d6d37b37e517a9
app/status/views.py
app/status/views.py
from flask import jsonify, current_app from . import status from . import utils from ..main.helpers.service import ServiceLoader from ..main import main @status.route('/_status') def status(): # ServiceLoader is the only thing that actually connects to the API service_loader = ServiceLoader( main.config['API_URL'], main.config['API_AUTH_TOKEN'] ) api_response = utils.return_response_from_api_status_call( service_loader.status ) apis_wot_got_errors = [] if api_response is None or api_response.status_code is not 200: apis_wot_got_errors.append("(Data) API") # if no errors found, return everything if not apis_wot_got_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), ) message = "Error connecting to the " \ + (" and the ".join(apis_wot_got_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), message=message, ), 500
from flask import jsonify, current_app from . import status from . import utils from ..main.helpers.service import ServiceLoader from ..main import main @status.route('/_status') def status(): # ServiceLoader is the only thing that actually connects to the API service_loader = ServiceLoader( main.config['API_URL'], main.config['API_AUTH_TOKEN'] ) api_response = utils.return_response_from_api_status_call( service_loader.status ) apis_with_errors = [] if api_response is None or api_response.status_code != 200: apis_with_errors.append("(Data) API") # if no errors found, return everything if not apis_with_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), ) message = "Error connecting to the " \ + (" and the ".join(apis_with_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), message=message, ), 500
Change variable name & int comparison.
Change variable name & int comparison.
Python
mit
mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend
--- +++ @@ -19,13 +19,13 @@ service_loader.status ) - apis_wot_got_errors = [] + apis_with_errors = [] - if api_response is None or api_response.status_code is not 200: - apis_wot_got_errors.append("(Data) API") + if api_response is None or api_response.status_code != 200: + apis_with_errors.append("(Data) API") # if no errors found, return everything - if not apis_wot_got_errors: + if not apis_with_errors: return jsonify( status="ok", version=utils.get_version_label(), @@ -33,7 +33,7 @@ ) message = "Error connecting to the " \ - + (" and the ".join(apis_wot_got_errors)) \ + + (" and the ".join(apis_with_errors)) \ + "." current_app.logger.error(message)
637f6c09bf3ac558e6e30d748dfb0838e4a3720f
classes/person.py
classes/person.py
class Person(object): def __init__(self, iden, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation self.iden = iden def full_name(self): self.full_name = self.person_name + " " + self.person_surname return self.full_name
class Person(object): def __init__(self, iden, person_type, person_name, person_surname="", wants_accommodation="N"): self.person_name = person_name self.person_surname = person_surname self.person_type = person_type self.wants_accommodation = wants_accommodation self.iden = iden
Remove redundant full name method
Remove redundant full name method
Python
mit
peterpaints/room-allocator
--- +++ @@ -5,7 +5,3 @@ self.person_type = person_type self.wants_accommodation = wants_accommodation self.iden = iden - - def full_name(self): - self.full_name = self.person_name + " " + self.person_surname - return self.full_name
53f967cf2cb1159e75b4bac267e163cd5a3ba156
wsgi/openshift/urls.py
wsgi/openshift/urls.py
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'openshift.views.home', name='home'), # url(r'^openshift/', include('openshift.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'openshift.views.home', name='home'), # url(r'^openshift/', include('openshift.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), )
Revert "Change to get Django 1.5 to work."
Revert "Change to get Django 1.5 to work." This reverts commit 92b9b557eef77f7ea4c05c74c1c229a2b508e640. It didn't resolve all the problems, and I'm out of time.
Python
agpl-3.0
esplinr/foodcheck,esplinr/foodcheck,esplinr/foodcheck,esplinr/foodcheck
--- +++ @@ -1,4 +1,4 @@ -from django.conf.urls import patterns, include, url +from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin
aa360309f387f19f6566d08325cd1aa1131768da
bulbs/utils/filters.py
bulbs/utils/filters.py
from rest_framework import filters class CaseInsensitiveBooleanFilter(filters.BaseFilterBackend): """Set a boolean_fields tuple on the viewset and set this class as a filter_backend to filter listed fields through a case-insensitive transformation to be used for filtering. i.e. query params such as 'true' become boolean True, and params with a value 'false' become boolean False.""" def filter_queryset(self, request, queryset, view): boolean_fields = getattr(view, 'boolean_fields', None) if not boolean_fields: return queryset boolean_filters = {} for field in boolean_fields: if field in request.QUERY_PARAMS: val = request.QUERY_PARAMS[field] if val in ['true', 'True']: boolean_filters[field] = True elif val in ['false', 'False']: boolean_filters[field] = False if len(boolean_filters) > 0: return queryset.filter(**boolean_filters) return queryset
from rest_framework import filters class CaseInsensitiveBooleanFilter(filters.BaseFilterBackend): """Set a boolean_fields tuple on the viewset and set this class as a filter_backend to filter listed fields through a case-insensitive transformation to be used for filtering. i.e. query params such as 'true' become boolean True, and params with a value 'false' become boolean False.""" def filter_queryset(self, request, queryset, view): boolean_fields = getattr(view, 'boolean_fields', None) if not boolean_fields: return queryset boolean_filters = {} for field in boolean_fields: if field in request.QUERY_PARAMS: val = request.QUERY_PARAMS[field].lower() if val == 'true': boolean_filters[field] = True elif val == 'false': boolean_filters[field] = False if len(boolean_filters) > 0: return queryset.filter(**boolean_filters) return queryset
Cover every case for CaseInsensitiveBooleanFilter
Cover every case for CaseInsensitiveBooleanFilter
Python
mit
pombredanne/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,pombredanne/django-bulbs
--- +++ @@ -17,10 +17,10 @@ boolean_filters = {} for field in boolean_fields: if field in request.QUERY_PARAMS: - val = request.QUERY_PARAMS[field] - if val in ['true', 'True']: + val = request.QUERY_PARAMS[field].lower() + if val == 'true': boolean_filters[field] = True - elif val in ['false', 'False']: + elif val == 'false': boolean_filters[field] = False if len(boolean_filters) > 0:
74f915946c346238b6badb7c494cefa356cf6f84
busineme/core/views.py
busineme/core/views.py
"""Busine-me API Universidade de Brasilia - FGA Técnicas de Programação, 2/2015 @file views.py Views (on classic MVC, controllers) with methods that control the requisitions for the user authentication and manipulation. """ from django.views.generic import View from core.serializers import serialize_objects from .models import Busline from django.http import JsonResponse STATUS_OK = 200 STATUS_NOT_FOUND = 404 STATUS_CREATED = 201 STATUS_SERVER_ERROR = 500 class BuslineSearchResultView(View): http_method_names = [u'get', u'post'] def get(self, request): """Returns all users.""" json_data = serialize_objects(Busline.objects.all()) return JsonResponse(json_data, content_type='application/json') def getbusline(self, line_number): busline = Busline.api_filter_startswith(line_number) json_data = serialize_objects(busline) return JsonResponse(json_data, content_type='application/json')
"""Busine-me API Universidade de Brasilia - FGA Técnicas de Programação, 2/2015 @file views.py Views (on classic MVC, controllers) with methods that control the requisitions for the user authentication and manipulation. """ from django.views.generic import View from core.serializers import serialize_objects from .models import Busline from django.http import JsonResponse STATUS_OK = 200 STATUS_NOT_FOUND = 404 STATUS_CREATED = 201 STATUS_SERVER_ERROR = 500 class BuslineSearchResultView(View): http_method_names = [u'get', u'post'] def get(self, request): """Returns all users.""" json_data = serialize_objects(Busline.objects.all()) return JsonResponse(json_data, content_type='application/json') def get_busline(self, line_number): busline = Busline.api_filter_startswith(line_number) json_data = serialize_objects(busline) return JsonResponse(json_data, content_type='application/json')
Change name getbusline name method
Change name getbusline name method
Python
agpl-3.0
aldarionsevero/busine.meAPI,aldarionsevero/busine.meAPI
--- +++ @@ -25,7 +25,7 @@ json_data = serialize_objects(Busline.objects.all()) return JsonResponse(json_data, content_type='application/json') - def getbusline(self, line_number): + def get_busline(self, line_number): busline = Busline.api_filter_startswith(line_number) json_data = serialize_objects(busline)
72bbd1a5e356b57842b07aa3a58d1e314228091d
tests/pytests/unit/pillar/test_pillar.py
tests/pytests/unit/pillar/test_pillar.py
import pytest import salt.loader import salt.pillar from salt.utils.odict import OrderedDict @pytest.mark.parametrize( "envs", ( ["a", "b", "c"], ["c", "b", "a"], ["b", "a", "c"], ), ) def test_pillar_envs_order(envs, temp_salt_minion, tmp_path): opts = temp_salt_minion.config.copy() # Stop using OrderedDict once we drop Py3.5 support opts["pillar_roots"] = OrderedDict() for envname in envs: opts["pillar_roots"][envname] = [str(tmp_path / envname)] grains = salt.loader.grains(opts) pillar = salt.pillar.Pillar( opts, grains, temp_salt_minion.id, "base", ) # The base environment is always present and as the first environment name assert pillar._get_envs() == ["base"] + envs
import pytest import salt.loader import salt.pillar from salt.utils.odict import OrderedDict @pytest.mark.parametrize( "envs", ( ["a", "b", "c"], ["c", "b", "a"], ["b", "a", "c"], ), ) def test_pillar_envs_order(envs, temp_salt_minion, tmp_path): opts = temp_salt_minion.config.copy() # Stop using OrderedDict once we drop Py3.5 support opts["pillar_roots"] = OrderedDict() for envname in envs: opts["pillar_roots"][envname] = [str(tmp_path / envname)] grains = salt.loader.grains(opts) pillar = salt.pillar.Pillar( opts, grains, temp_salt_minion.id, "base", ) # The base environment is always present and as the first environment name assert pillar._get_envs() == ["base"] + envs def test_pillar_get_tops_should_not_error_when_merging_strategy_is_none_and_no_pillarenv( temp_salt_minion, ): opts = temp_salt_minion.config.copy() opts["pillarenv"] = None opts["pillar_source_merging_strategy"] = "none" pillar = salt.pillar.Pillar( opts=opts, grains=salt.loader.grains(opts), minion_id=temp_salt_minion.id, saltenv="base", ) tops, errors = pillar.get_tops() assert not errors
Add testcase written by @waynew
Add testcase written by @waynew
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -27,3 +27,19 @@ ) # The base environment is always present and as the first environment name assert pillar._get_envs() == ["base"] + envs + + +def test_pillar_get_tops_should_not_error_when_merging_strategy_is_none_and_no_pillarenv( + temp_salt_minion, +): + opts = temp_salt_minion.config.copy() + opts["pillarenv"] = None + opts["pillar_source_merging_strategy"] = "none" + pillar = salt.pillar.Pillar( + opts=opts, + grains=salt.loader.grains(opts), + minion_id=temp_salt_minion.id, + saltenv="base", + ) + tops, errors = pillar.get_tops() + assert not errors
1f0195c1d1695119287e3693360ec44564ed0a09
app/main/views/sub_navigation_dictionaries.py
app/main/views/sub_navigation_dictionaries.py
def features_nav(): return [ { "name": "Features", "link": "main.features", "sub_navigation_items": [ { "name": "Emails", "link": "main.features_email", }, { "name": "Text messages", "link": "main.features_sms", }, { "name": "Letters", "link": "main.features_letters", }, ] }, { "name": "Roadmap", "link": "main.roadmap", }, { "name": "Trial mode", "link": "main.trial_mode_new", }, { "name": "Message status", "link": "main.message_status", }, { "name": "Security", "link": "main.security", }, { "name": "Terms of use", "link": "main.terms", }, { "name": "Using Notify", "link": "main.using_notify", }, ]
def features_nav(): return [ { "name": "Features", "link": "main.features", "sub_navigation_items": [ { "name": "Emails", "link": "main.features_email", }, { "name": "Text messages", "link": "main.features_sms", }, { "name": "Letters", "link": "main.features_letters", }, ] }, { "name": "Roadmap", "link": "main.roadmap", }, { "name": "Trial mode", "link": "main.trial_mode_new", }, { "name": "Message status", "link": "main.message_status", }, { "name": "Security", "link": "main.security", }, { "name": "Terms of use", "link": "main.terms", }, ]
Remove ‘using notify’ from nav (it’s a redirect now)
Remove ‘using notify’ from nav (it’s a redirect now)
Python
mit
alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
--- +++ @@ -38,8 +38,4 @@ "name": "Terms of use", "link": "main.terms", }, - { - "name": "Using Notify", - "link": "main.using_notify", - }, ]
d06d65cea4ae9efa547af43a551e24a459e0627e
tbmodels/_legacy_decode.py
tbmodels/_legacy_decode.py
from ._tb_model import Model def _decode(hf): if 'tb_model' in hf or 'hop' in hf: return _decode_model(hf) elif 'val' in hf: return _decode_val(hf) elif '0' in hf: return _decode_iterable(hf) else: raise ValueError('File structure not understood.') def _decode_iterable(hf): return [_decode(hf[key]) for key in sorted(hf, key=int)] def _decode_model(hf): return Model.from_hdf5(hf) def _decode_val(hf): return hf['val'].value
""" Defines decoding for the legacy (pre fsc.hdf5-io) HDF5 format. """ from ._tb_model import Model def _decode(hdf5_handle): """ Decode the object at the given HDF5 node. """ if 'tb_model' in hdf5_handle or 'hop' in hdf5_handle: return _decode_model(hdf5_handle) elif 'val' in hdf5_handle: return _decode_val(hdf5_handle) elif '0' in hdf5_handle: return _decode_iterable(hdf5_handle) else: raise ValueError('File structure not understood.') def _decode_iterable(hdf5_handle): return [_decode(hdf5_handle[key]) for key in sorted(hdf5_handle, key=int)] def _decode_model(hdf5_handle): return Model.from_hdf5(hdf5_handle) def _decode_val(hdf5_handle): return hdf5_handle['val'].value
Fix pylint issues in legacy_decode.
Fix pylint issues in legacy_decode.
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
--- +++ @@ -1,24 +1,31 @@ +""" +Defines decoding for the legacy (pre fsc.hdf5-io) HDF5 format. +""" + from ._tb_model import Model -def _decode(hf): - if 'tb_model' in hf or 'hop' in hf: - return _decode_model(hf) - elif 'val' in hf: - return _decode_val(hf) - elif '0' in hf: - return _decode_iterable(hf) +def _decode(hdf5_handle): + """ + Decode the object at the given HDF5 node. + """ + if 'tb_model' in hdf5_handle or 'hop' in hdf5_handle: + return _decode_model(hdf5_handle) + elif 'val' in hdf5_handle: + return _decode_val(hdf5_handle) + elif '0' in hdf5_handle: + return _decode_iterable(hdf5_handle) else: raise ValueError('File structure not understood.') -def _decode_iterable(hf): - return [_decode(hf[key]) for key in sorted(hf, key=int)] +def _decode_iterable(hdf5_handle): + return [_decode(hdf5_handle[key]) for key in sorted(hdf5_handle, key=int)] -def _decode_model(hf): - return Model.from_hdf5(hf) +def _decode_model(hdf5_handle): + return Model.from_hdf5(hdf5_handle) -def _decode_val(hf): - return hf['val'].value +def _decode_val(hdf5_handle): + return hdf5_handle['val'].value
3a312dc4134d28d8c8fb0020444a1bbf1277a4cb
lib/automatic_timestamps/models.py
lib/automatic_timestamps/models.py
from django.db import models import datetime class TimestampModel(models.Model): """ Extend the default Django model to add timestamps to all objects. """ class Meta: abstract = True # Timestamps! created_at = models.DateTimeField() updated_at = models.DateTimeField() def save(self): """ Override the save method to automatically set the created_at and updated_at fields with current date info. """ if self.created_at == None: self.created_at = datetime.datetime.now() self.updated_at = datetime.datetime.now() super(TimestampModel, self).save()
from django.db import models import datetime class TimestampModel(models.Model): """ Extend the default Django model to add timestamps to all objects. """ class Meta: abstract = True # Timestamps! created_at = models.DateTimeField() updated_at = models.DateTimeField() def save(self, *args, **kwargs): """ Override the save method to automatically set the created_at and updated_at fields with current date info. """ if self.created_at == None: self.created_at = datetime.datetime.now() self.updated_at = datetime.datetime.now() super(TimestampModel, self).save()
Add *args/**kwargs to save() as per the Django docs
Add *args/**kwargs to save() as per the Django docs
Python
mit
tofumatt/quotes,tofumatt/quotes
--- +++ @@ -15,7 +15,7 @@ created_at = models.DateTimeField() updated_at = models.DateTimeField() - def save(self): + def save(self, *args, **kwargs): """ Override the save method to automatically set the created_at and updated_at fields with current date info.
4db2d879cb8ee7d8ddd1543e6aed50f40e44ca66
src/pi/scanning_proxy.py
src/pi/scanning_proxy.py
"""Philips hue proxy code.""" import abc import logging import sys import threading from pi import proxy class ScanningProxy(proxy.Proxy): """A proxy object with a background scan thread.""" __metaclass__ = abc.ABCMeta def __init__(self, refresh_period): self._refresh_period = refresh_period self._exiting = False self._scan_thread_condition = threading.Condition() self._scan_thread = threading.Thread(target=self._scan) self._scan_thread.daemon = True self._scan_thread.start() @proxy.command def scan(self): with self._scan_thread_condition: self._scan_thread_condition.notify() def _scan(self): """Loop thread for scanning.""" while not self._exiting: # We always do a scan on start up. try: self._scan_once() except: logging.error('Error during %s scan', self.__class__.__name__, exc_info=sys.exc_info()) with self._scan_thread_condition: self._scan_thread_condition.wait(self._refresh_period) if self._exiting: break logging.info('Exiting %s scan thread', self.__class__.__name__) @abc.abstractmethod def _scan_once(self): pass def stop(self): self._exiting = True self.scan() self._scan_thread.join()
"""Philips hue proxy code.""" import abc import logging import sys import threading from pi import proxy class ScanningProxy(proxy.Proxy): """A proxy object with a background scan thread.""" __metaclass__ = abc.ABCMeta def __init__(self, refresh_period): self._refresh_period = refresh_period self._exiting = False self._scan_thread_condition = threading.Condition() self._scan_thread = threading.Thread(target=self._scan) self._scan_thread.daemon = True self._scan_thread.start() @proxy.command def scan(self): with self._scan_thread_condition: self._scan_thread_condition.notify() def _scan(self): """Loop thread for scanning.""" while not self._exiting: # We always do a scan on start up. try: self._scan_once() except: logging.error('Error during %s scan', self.__class__.__name__, exc_info=sys.exc_info()) with self._scan_thread_condition: if not self._exiting: self._scan_thread_condition.wait(self._refresh_period) if self._exiting: break logging.info('Exiting %s scan thread', self.__class__.__name__) @abc.abstractmethod def _scan_once(self): pass def stop(self): with self._scan_thread_condition: self._exiting = True self._scan_thread_condition.notify() self._scan_thread.join()
Fix race on exit in scanning proxy.
Fix race on exit in scanning proxy.
Python
mit
tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation
--- +++ @@ -38,9 +38,12 @@ exc_info=sys.exc_info()) with self._scan_thread_condition: - self._scan_thread_condition.wait(self._refresh_period) + if not self._exiting: + self._scan_thread_condition.wait(self._refresh_period) + if self._exiting: break + logging.info('Exiting %s scan thread', self.__class__.__name__) @abc.abstractmethod @@ -48,6 +51,7 @@ pass def stop(self): - self._exiting = True - self.scan() + with self._scan_thread_condition: + self._exiting = True + self._scan_thread_condition.notify() self._scan_thread.join()
058a3e918cccde7dcace79df2b257bd29277bcd0
tests/builtins/test_abs.py
tests/builtins/test_abs.py
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class AbsTests(TranspileTestCase): pass class BuiltinAbsFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["abs"] not_implemented = [ 'test_bool', 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_frozenset', 'test_set', ]
from unittest import expectedFailure from .. utils import TranspileTestCase, BuiltinFunctionTestCase class AbsTests(TranspileTestCase): @expectedFailure def test_abs_not_implemented(self): self.assertCodeExecution(""" class NotAbsLike: pass x = NotAbsLike() print(abs(x)) """) class BuiltinAbsFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["abs"] not_implemented = [ 'test_bool', 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_frozenset', 'test_set', ]
Add failing test for builtin abs() on objects without __abs__()
Add failing test for builtin abs() on objects without __abs__()
Python
bsd-3-clause
pombredanne/voc,ASP1234/voc,freakboy3742/voc,gEt-rIgHt-jR/voc,cflee/voc,cflee/voc,Felix5721/voc,glasnt/voc,glasnt/voc,pombredanne/voc,freakboy3742/voc,gEt-rIgHt-jR/voc,ASP1234/voc,Felix5721/voc
--- +++ @@ -1,8 +1,17 @@ +from unittest import expectedFailure + from .. utils import TranspileTestCase, BuiltinFunctionTestCase class AbsTests(TranspileTestCase): - pass + @expectedFailure + def test_abs_not_implemented(self): + self.assertCodeExecution(""" + class NotAbsLike: + pass + x = NotAbsLike() + print(abs(x)) + """) class BuiltinAbsFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
bc4fb65f76aa011e44bbe01b7965bc99eff5d85e
tests/test_recalcitrant.py
tests/test_recalcitrant.py
"Test for recalcitrant and obtuse graphs to describe" from wordgraph.points import Point import wordgraph import random from utilities import EPOCH_START, time_values def test_time_goes_backwards(): "A valid time series where time changes linearly backwards" values = [1.0] * 10 times = (EPOCH_START-i for i in range(10)) datapoints = [Point(x=t, y=v) for (v, t) in zip(values, time)] features = wordgraph.describe(datapoints) assert features is None def test_random_data(): "A time series of 50 data points where every value is random" rng = random.Random(0) values = [rng.random() for i in range(50)] datapoints = time_values(values) features = wordgraph.describe(datapoints) assert features is None
"Test for recalcitrant and obtuse graphs to describe" from wordgraph.points import Point import wordgraph import random import pytest from utilities import EPOCH_START, time_values def test_time_goes_backwards(): "A valid time series where time changes linearly backwards" values = [1.0] * 10 times = (EPOCH_START-i for i in range(10)) datapoints = [Point(x=t, y=v) for (v, t) in zip(values, time)] features = wordgraph.describe(datapoints) assert features is None def test_random_data(): "A time series of 50 data points where every value is random" rng = random.Random(0) values = [rng.random() for i in range(50)] datapoints = time_values(values) features = wordgraph.describe(datapoints) assert features is None def test_too_few_points(): """A time series with too few data points to be analysed. Expected to raise an exception. """ with pytest.raises(ValueError): features = wordgraph.describe([Point(x=0, y=0)]) def test_nonuniform_time_periods(): """A time series where time periods are wildly different. Expected to raise an exception. """ times = [1, 3, 4, 6, 7, 9, 10] datapoints = [Point(x=t, y=1.0) for t in times] with pytest.raises(ValueError): features = wordgraph.describe(datapoints)
Test expected failures of the anlayzer
Test expected failures of the anlayzer The analyzer is not expected to cope with too few data points for time series with greatly varying time ranges. It should raise an exception in these cases.
Python
apache-2.0
tleeuwenburg/wordgraph,tleeuwenburg/wordgraph
--- +++ @@ -3,6 +3,7 @@ import wordgraph import random +import pytest from utilities import EPOCH_START, time_values @@ -21,3 +22,21 @@ datapoints = time_values(values) features = wordgraph.describe(datapoints) assert features is None + +def test_too_few_points(): + """A time series with too few data points to be analysed. + + Expected to raise an exception. + """ + with pytest.raises(ValueError): + features = wordgraph.describe([Point(x=0, y=0)]) + +def test_nonuniform_time_periods(): + """A time series where time periods are wildly different. + + Expected to raise an exception. + """ + times = [1, 3, 4, 6, 7, 9, 10] + datapoints = [Point(x=t, y=1.0) for t in times] + with pytest.raises(ValueError): + features = wordgraph.describe(datapoints)
e562223cd45c89b9ce4d5a70ef4f4ad5daea968b
deflect/urls.py
deflect/urls.py
from django.conf.urls import patterns from django.conf.urls import url from .views import redirect urlpatterns = patterns('', url(r'^(?P<key>[a-zA-Z0-9]+)$', redirect, name='deflect-redirect'), )
from django.conf.urls import patterns from django.conf.urls import url from .views import redirect urlpatterns = patterns('', url(r'^(?P<key>[a-zA-Z0-9-]+)$', redirect, name='deflect-redirect'), )
Allow dashes in URL path regexp
Allow dashes in URL path regexp
Python
bsd-3-clause
jbittel/django-deflect
--- +++ @@ -5,5 +5,5 @@ urlpatterns = patterns('', - url(r'^(?P<key>[a-zA-Z0-9]+)$', redirect, name='deflect-redirect'), + url(r'^(?P<key>[a-zA-Z0-9-]+)$', redirect, name='deflect-redirect'), )
48da1258ddaa7b8c740eba67fc82edb11b163b64
server_env_ebill_paynet/__manifest__.py
server_env_ebill_paynet/__manifest__.py
# Copyright 2020 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) { "name": "Server environment for Ebill Paynet", "version": "13.0.1.0.0", "author": "Camptocamp,Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Tools", "depends": ["server_environment", "ebill_paynet"], "website": "https://www.camptocamp.com", "installable": True, }
# Copyright 2020 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) { "name": "Server environment for Ebill Paynet", "version": "13.0.1.0.0", "author": "Camptocamp,Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Tools", "depends": ["server_environment", "ebill_paynet"], "website": "https://github.com/OCA/l10n-switzerland", "installable": True, }
Fix linting and add info in roadmap
Fix linting and add info in roadmap
Python
agpl-3.0
OCA/l10n-switzerland,OCA/l10n-switzerland
--- +++ @@ -8,6 +8,6 @@ "license": "AGPL-3", "category": "Tools", "depends": ["server_environment", "ebill_paynet"], - "website": "https://www.camptocamp.com", + "website": "https://github.com/OCA/l10n-switzerland", "installable": True, }
c70a409c7717fa62517b69f8a5f20f10d5325751
test/common/memcached_workload_common.py
test/common/memcached_workload_common.py
# This is a (hopefully temporary) shim that uses the rdb protocol to # implement part of the memcache API import contextlib import rdb_workload_common @contextlib.contextmanager def make_memcache_connection(opts): with rdb_workload_common.make_table_and_connection(opts) as (table, conn): yield MemcacheRdbShim(table, conn) class MemcacheRdbShim(object): def __init__(self, table, conn): self.table = table self.conn = conn def get(self, key): response = self.table.get(key).run(self.conn) if response: return response['val'] def set(self, key, val): response = self.table.insert({ 'id': key, 'val': val }, upsert=True ).run(self.conn) error = response.get('first_error') if error: raise Exception(error) return response['inserted'] | response['replaced'] | response['unchanged'] def delete(self, key): response = self.table.get(key).delete().run(self.conn) error = response.get('first_error') if error: raise Exception(error) return response['deleted'] def option_parser_for_memcache(): return rdb_workload_common.option_parser_for_connect()
# This is a (hopefully temporary) shim that uses the rdb protocol to # implement part of the memcache API import contextlib import rdb_workload_common @contextlib.contextmanager def make_memcache_connection(opts): with rdb_workload_common.make_table_and_connection(opts) as (table, conn): yield MemcacheRdbShim(table, conn) class MemcacheRdbShim(object): def __init__(self, table, conn): self.table = table self.conn = conn def get(self, key): response = self.table.get(key).run(self.conn) if response: return response['val'] def set(self, key, val): response = self.table.insert({ 'id': key, 'val': val }, conflict='replace' ).run(self.conn) error = response.get('first_error') if error: raise Exception(error) return response['inserted'] | response['replaced'] | response['unchanged'] def delete(self, key): response = self.table.get(key).delete().run(self.conn) error = response.get('first_error') if error: raise Exception(error) return response['deleted'] def option_parser_for_memcache(): return rdb_workload_common.option_parser_for_connect()
Replace upsert=True with conflict='replace' in tests
Replace upsert=True with conflict='replace' in tests Review 1804 by @gchpaco Related to #2733
Python
apache-2.0
jesseditson/rethinkdb,lenstr/rethinkdb,gdi2290/rethinkdb,grandquista/rethinkdb,catroot/rethinkdb,bpradipt/rethinkdb,gavioto/rethinkdb,jesseditson/rethinkdb,sbusso/rethinkdb,sontek/rethinkdb,bchavez/rethinkdb,wujf/rethinkdb,greyhwndz/rethinkdb,Qinusty/rethinkdb,gdi2290/rethinkdb,urandu/rethinkdb,jmptrader/rethinkdb,bchavez/rethinkdb,pap/rethinkdb,grandquista/rethinkdb,AntouanK/rethinkdb,elkingtonmcb/rethinkdb,alash3al/rethinkdb,losywee/rethinkdb,jmptrader/rethinkdb,wkennington/rethinkdb,mbroadst/rethinkdb,robertjpayne/rethinkdb,matthaywardwebdesign/rethinkdb,losywee/rethinkdb,lenstr/rethinkdb,sbusso/rethinkdb,Qinusty/rethinkdb,niieani/rethinkdb,scripni/rethinkdb,bpradipt/rethinkdb,KSanthanam/rethinkdb,jmptrader/rethinkdb,yakovenkodenis/rethinkdb,gavioto/rethinkdb,dparnell/rethinkdb,pap/rethinkdb,catroot/rethinkdb,rrampage/rethinkdb,rrampage/rethinkdb,eliangidoni/rethinkdb,sebadiaz/rethinkdb,catroot/rethinkdb,marshall007/rethinkdb,RubenKelevra/rethinkdb,Qinusty/rethinkdb,4talesa/rethinkdb,niieani/rethinkdb,scripni/rethinkdb,wujf/rethinkdb,yaolinz/rethinkdb,dparnell/rethinkdb,sontek/rethinkdb,gavioto/rethinkdb,mquandalle/rethinkdb,alash3al/rethinkdb,JackieXie168/rethinkdb,rrampage/rethinkdb,AntouanK/rethinkdb,wujf/rethinkdb,niieani/rethinkdb,JackieXie168/rethinkdb,marshall007/rethinkdb,yaolinz/rethinkdb,wojons/rethinkdb,tempbottle/rethinkdb,ajose01/rethinkdb,sbusso/rethinkdb,robertjpayne/rethinkdb,matthaywardwebdesign/rethinkdb,AntouanK/rethinkdb,yaolinz/rethinkdb,mquandalle/rethinkdb,tempbottle/rethinkdb,tempbottle/rethinkdb,marshall007/rethinkdb,catroot/rethinkdb,Wilbeibi/rethinkdb,jesseditson/rethinkdb,bpradipt/rethinkdb,4talesa/rethinkdb,rrampage/rethinkdb,yaolinz/rethinkdb,urandu/rethinkdb,bchavez/rethinkdb,sebadiaz/rethinkdb,wojons/rethinkdb,captainpete/rethinkdb,4talesa/rethinkdb,sbusso/rethinkdb,eliangidoni/rethinkdb,grandquista/rethinkdb,sbusso/rethinkdb,RubenKelevra/rethinkdb,spblightadv/rethinkdb,mcanthony/rethinkdb,captainpete/rethinkdb,gavioto/rethinkdb,ayumilong/rethinkdb,catroot/rethinkdb,Qinusty/rethinkdb,mbroadst/rethinkdb,spblightadv/rethinkdb,jesseditson/rethinkdb,sontek/rethinkdb,bchavez/rethinkdb,RubenKelevra/rethinkdb,catroot/rethinkdb,JackieXie168/rethinkdb,dparnell/rethinkdb,victorbriz/rethinkdb,niieani/rethinkdb,sontek/rethinkdb,elkingtonmcb/rethinkdb,bpradipt/rethinkdb,RubenKelevra/rethinkdb,robertjpayne/rethinkdb,ajose01/rethinkdb,dparnell/rethinkdb,lenstr/rethinkdb,KSanthanam/rethinkdb,catroot/rethinkdb,eliangidoni/rethinkdb,captainpete/rethinkdb,grandquista/rethinkdb,eliangidoni/rethinkdb,greyhwndz/rethinkdb,grandquista/rethinkdb,gdi2290/rethinkdb,mquandalle/rethinkdb,alash3al/rethinkdb,victorbriz/rethinkdb,wujf/rethinkdb,matthaywardwebdesign/rethinkdb,RubenKelevra/rethinkdb,sebadiaz/rethinkdb,lenstr/rethinkdb,alash3al/rethinkdb,tempbottle/rethinkdb,lenstr/rethinkdb,jmptrader/rethinkdb,ajose01/rethinkdb,scripni/rethinkdb,sontek/rethinkdb,yaolinz/rethinkdb,tempbottle/rethinkdb,tempbottle/rethinkdb,victorbriz/rethinkdb,mcanthony/rethinkdb,rrampage/rethinkdb,dparnell/rethinkdb,scripni/rethinkdb,yakovenkodenis/rethinkdb,spblightadv/rethinkdb,matthaywardwebdesign/rethinkdb,wojons/rethinkdb,losywee/rethinkdb,Qinusty/rethinkdb,KSanthanam/rethinkdb,gdi2290/rethinkdb,grandquista/rethinkdb,urandu/rethinkdb,scripni/rethinkdb,wujf/rethinkdb,4talesa/rethinkdb,bpradipt/rethinkdb,victorbriz/rethinkdb,JackieXie168/rethinkdb,AntouanK/rethinkdb,mquandalle/rethinkdb,dparnell/rethinkdb,victorbriz/rethinkdb,elkingtonmcb/rethinkdb,grandquista/rethinkdb,wujf/rethinkdb,niieani/rethinkdb,alash3al/rethinkdb,captainpete/rethinkdb,wojons/rethinkdb,eliangidoni/rethinkdb,spblightadv/rethinkdb,Wilbeibi/rethinkdb,sebadiaz/rethinkdb,ayumilong/rethinkdb,bpradipt/rethinkdb,lenstr/rethinkdb,gdi2290/rethinkdb,catroot/rethinkdb,pap/rethinkdb,matthaywardwebdesign/rethinkdb,yakovenkodenis/rethinkdb,jesseditson/rethinkdb,Wilbeibi/rethinkdb,urandu/rethinkdb,captainpete/rethinkdb,ayumilong/rethinkdb,wkennington/rethinkdb,yakovenkodenis/rethinkdb,mcanthony/rethinkdb,jesseditson/rethinkdb,robertjpayne/rethinkdb,marshall007/rethinkdb,bchavez/rethinkdb,marshall007/rethinkdb,elkingtonmcb/rethinkdb,sbusso/rethinkdb,robertjpayne/rethinkdb,marshall007/rethinkdb,eliangidoni/rethinkdb,gdi2290/rethinkdb,JackieXie168/rethinkdb,elkingtonmcb/rethinkdb,losywee/rethinkdb,KSanthanam/rethinkdb,KSanthanam/rethinkdb,gavioto/rethinkdb,AntouanK/rethinkdb,marshall007/rethinkdb,jesseditson/rethinkdb,losywee/rethinkdb,bchavez/rethinkdb,spblightadv/rethinkdb,Qinusty/rethinkdb,elkingtonmcb/rethinkdb,yaolinz/rethinkdb,mbroadst/rethinkdb,wojons/rethinkdb,gdi2290/rethinkdb,ajose01/rethinkdb,mbroadst/rethinkdb,urandu/rethinkdb,wkennington/rethinkdb,rrampage/rethinkdb,ayumilong/rethinkdb,sontek/rethinkdb,sebadiaz/rethinkdb,alash3al/rethinkdb,urandu/rethinkdb,Wilbeibi/rethinkdb,mbroadst/rethinkdb,mquandalle/rethinkdb,Qinusty/rethinkdb,spblightadv/rethinkdb,rrampage/rethinkdb,KSanthanam/rethinkdb,matthaywardwebdesign/rethinkdb,tempbottle/rethinkdb,gavioto/rethinkdb,greyhwndz/rethinkdb,Qinusty/rethinkdb,eliangidoni/rethinkdb,jmptrader/rethinkdb,yaolinz/rethinkdb,losywee/rethinkdb,losywee/rethinkdb,yakovenkodenis/rethinkdb,yakovenkodenis/rethinkdb,bchavez/rethinkdb,yakovenkodenis/rethinkdb,4talesa/rethinkdb,sontek/rethinkdb,dparnell/rethinkdb,bpradipt/rethinkdb,matthaywardwebdesign/rethinkdb,RubenKelevra/rethinkdb,mcanthony/rethinkdb,eliangidoni/rethinkdb,greyhwndz/rethinkdb,matthaywardwebdesign/rethinkdb,lenstr/rethinkdb,sbusso/rethinkdb,captainpete/rethinkdb,Wilbeibi/rethinkdb,4talesa/rethinkdb,ajose01/rethinkdb,AntouanK/rethinkdb,robertjpayne/rethinkdb,ayumilong/rethinkdb,mquandalle/rethinkdb,mcanthony/rethinkdb,victorbriz/rethinkdb,bchavez/rethinkdb,yakovenkodenis/rethinkdb,wkennington/rethinkdb,gavioto/rethinkdb,jesseditson/rethinkdb,mquandalle/rethinkdb,wujf/rethinkdb,sebadiaz/rethinkdb,mbroadst/rethinkdb,Qinusty/rethinkdb,AntouanK/rethinkdb,grandquista/rethinkdb,JackieXie168/rethinkdb,spblightadv/rethinkdb,Wilbeibi/rethinkdb,wkennington/rethinkdb,urandu/rethinkdb,bchavez/rethinkdb,mcanthony/rethinkdb,KSanthanam/rethinkdb,ayumilong/rethinkdb,jmptrader/rethinkdb,wojons/rethinkdb,greyhwndz/rethinkdb,victorbriz/rethinkdb,niieani/rethinkdb,mbroadst/rethinkdb,dparnell/rethinkdb,ayumilong/rethinkdb,mcanthony/rethinkdb,urandu/rethinkdb,wkennington/rethinkdb,ayumilong/rethinkdb,victorbriz/rethinkdb,spblightadv/rethinkdb,niieani/rethinkdb,pap/rethinkdb,wkennington/rethinkdb,sebadiaz/rethinkdb,niieani/rethinkdb,ajose01/rethinkdb,captainpete/rethinkdb,wojons/rethinkdb,Wilbeibi/rethinkdb,mbroadst/rethinkdb,AntouanK/rethinkdb,RubenKelevra/rethinkdb,greyhwndz/rethinkdb,robertjpayne/rethinkdb,JackieXie168/rethinkdb,RubenKelevra/rethinkdb,elkingtonmcb/rethinkdb,robertjpayne/rethinkdb,jmptrader/rethinkdb,mcanthony/rethinkdb,ajose01/rethinkdb,marshall007/rethinkdb,robertjpayne/rethinkdb,bpradipt/rethinkdb,jmptrader/rethinkdb,scripni/rethinkdb,eliangidoni/rethinkdb,ajose01/rethinkdb,captainpete/rethinkdb,alash3al/rethinkdb,4talesa/rethinkdb,pap/rethinkdb,JackieXie168/rethinkdb,Wilbeibi/rethinkdb,elkingtonmcb/rethinkdb,alash3al/rethinkdb,pap/rethinkdb,lenstr/rethinkdb,pap/rethinkdb,4talesa/rethinkdb,tempbottle/rethinkdb,mquandalle/rethinkdb,wojons/rethinkdb,grandquista/rethinkdb,rrampage/rethinkdb,KSanthanam/rethinkdb,gavioto/rethinkdb,sontek/rethinkdb,greyhwndz/rethinkdb,scripni/rethinkdb,sbusso/rethinkdb,JackieXie168/rethinkdb,pap/rethinkdb,losywee/rethinkdb,bpradipt/rethinkdb,mbroadst/rethinkdb,dparnell/rethinkdb,wkennington/rethinkdb,yaolinz/rethinkdb,sebadiaz/rethinkdb,scripni/rethinkdb,greyhwndz/rethinkdb
--- +++ @@ -24,7 +24,7 @@ 'id': key, 'val': val }, - upsert=True + conflict='replace' ).run(self.conn) error = response.get('first_error')
db30a8044f790dec8dd18255786d39e31021c7df
imbox/utils.py
imbox/utils.py
import logging logger = logging.getLogger(__name__) def str_encode(value='', encoding=None, errors='strict'): logger.debug("Encode str {} with and errors {}".format(value, encoding, errors)) return str(value, encoding, errors) def str_decode(value='', encoding=None, errors='strict'): if isinstance(value, str): return bytes(value, encoding, errors).decode('utf-8') elif isinstance(value, bytes): return value.decode(encoding or 'utf-8', errors=errors) else: raise TypeError("Cannot decode '{}' object".format(value.__class__))
import logging logger = logging.getLogger(__name__) def str_encode(value='', encoding=None, errors='strict'): logger.debug("Encode str {value} with encoding {encoding} and errors {errors}".format( value=value, encoding=encoding, errors=errors)) return str(value, encoding, errors) def str_decode(value='', encoding=None, errors='strict'): if isinstance(value, str): return bytes(value, encoding, errors).decode('utf-8') elif isinstance(value, bytes): return value.decode(encoding or 'utf-8', errors=errors) else: raise TypeError("Cannot decode '{}' object".format(value.__class__))
Add a forgotten parameter in a log line
Add a forgotten parameter in a log line
Python
mit
martinrusev/imbox
--- +++ @@ -3,7 +3,10 @@ def str_encode(value='', encoding=None, errors='strict'): - logger.debug("Encode str {} with and errors {}".format(value, encoding, errors)) + logger.debug("Encode str {value} with encoding {encoding} and errors {errors}".format( + value=value, + encoding=encoding, + errors=errors)) return str(value, encoding, errors)
440295122eec2a73012c6cb6c75ba384cc25b17b
formapi/calls.py
formapi/calls.py
from django.forms import forms class APICall(forms.Form): def __init__(self, api_key=None, *args, **kwargs): super(APICall, self).__init__(*args, **kwargs) self.api_key = api_key def add_error(self, error_msg): errors = self.non_field_errors() errors.append(error_msg) self._errors[forms.NON_FIELD_ERRORS] = errors def clean(self): for name, data in self.cleaned_data.iteritems(): setattr(self, name, data) return super(APICall, self).clean() def action(self, test): raise NotImplementedError('APIForms must implement action(self, test)')
# coding=utf-8 from django.forms import forms class APICall(forms.Form): def __init__(self, api_key=None, *args, **kwargs): super(APICall, self).__init__(*args, **kwargs) self.api_key = api_key def add_error(self, error_msg, field_name=forms.NON_FIELD_ERRORS): # TODO: with Django master you would just raise ValidationError({field_name: error_msg}) self._errors.setdefault(field_name, self.error_class()).append(error_msg) def clean(self): for name, data in self.cleaned_data.iteritems(): setattr(self, name, data) return super(APICall, self).clean() def action(self, test): raise NotImplementedError('APIForms must implement action(self, test)')
Allow adding error message for specified field
Allow adding error message for specified field
Python
mit
5monkeys/django-formapi,andreif/django-formapi,andreif/django-formapi,5monkeys/django-formapi
--- +++ @@ -1,3 +1,4 @@ +# coding=utf-8 from django.forms import forms @@ -7,10 +8,9 @@ super(APICall, self).__init__(*args, **kwargs) self.api_key = api_key - def add_error(self, error_msg): - errors = self.non_field_errors() - errors.append(error_msg) - self._errors[forms.NON_FIELD_ERRORS] = errors + def add_error(self, error_msg, field_name=forms.NON_FIELD_ERRORS): + # TODO: with Django master you would just raise ValidationError({field_name: error_msg}) + self._errors.setdefault(field_name, self.error_class()).append(error_msg) def clean(self): for name, data in self.cleaned_data.iteritems():
5b600e32a05d041facd64db79ea91e928d37f300
tests/test_postgres_processor.py
tests/test_postgres_processor.py
import pytest # from sqlalchemy import create_engine # from sqlalchemy.orm import sessionmaker from scrapi.linter.document import NormalizedDocument, RawDocument from scrapi.processing.postgres import PostgresProcessor, Document from . import utils test_db = PostgresProcessor() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) @pytest.mark.postgres def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID']
import pytest import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings") from . import utils from scrapi.linter.document import NormalizedDocument, RawDocument from scrapi.processing.postgres import PostgresProcessor, Document test_db = PostgresProcessor() NORMALIZED = NormalizedDocument(utils.RECORD) RAW = RawDocument(utils.RAW_DOC) @pytest.mark.postgres def test_process_raw(): test_db.process_raw(RAW) queryset = Document(docID='someID', source=RAW['source']) assert queryset.docID == RAW.attributes['docID']
Use newly configured conftest in postgres processor test
Use newly configured conftest in postgres processor test
Python
apache-2.0
fabianvf/scrapi,felliott/scrapi,mehanig/scrapi,erinspace/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,fabianvf/scrapi,felliott/scrapi
--- +++ @@ -1,13 +1,11 @@ import pytest -# from sqlalchemy import create_engine -# from sqlalchemy.orm import sessionmaker - -from scrapi.linter.document import NormalizedDocument, RawDocument - -from scrapi.processing.postgres import PostgresProcessor, Document +import os +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings") from . import utils +from scrapi.linter.document import NormalizedDocument, RawDocument +from scrapi.processing.postgres import PostgresProcessor, Document test_db = PostgresProcessor()
73154aa2498b6826612fae3b287c528e3406bec4
jacquard/service/commands.py
jacquard/service/commands.py
"""Command-line utilities for HTTP service subsystem.""" import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): """ Run a debug server. **This is for debug, local use only, not production.** This command is named to mirror its equivalent in Django. It configures the WSGI app and serves it through Werkzeug's simple serving mechanism, with a debugger attached, and auto-reloading. """ help = "run a (local, debug) server" def add_arguments(self, parser): """Add argparse arguments.""" parser.add_argument( '-p', '--port', type=int, default=1212, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): """Run command.""" app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
"""Command-line utilities for HTTP service subsystem.""" import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): """ Run a debug server. **This is for debug, local use only, not production.** This command is named to mirror its equivalent in Django. It configures the WSGI app and serves it through Werkzeug's simple serving mechanism, with a debugger attached, and auto-reloading. """ plumbing = True help = "run a (local, debug) server" def add_arguments(self, parser): """Add argparse arguments.""" parser.add_argument( '-p', '--port', type=int, default=1212, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): """Run command.""" app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
Mark runserver as a plumbing command
Mark runserver as a plumbing command
Python
mit
prophile/jacquard,prophile/jacquard
--- +++ @@ -18,6 +18,7 @@ with a debugger attached, and auto-reloading. """ + plumbing = True help = "run a (local, debug) server" def add_arguments(self, parser):
3e58c3707b8451bb053b2465a6a68438219fd348
python/script_device_PIR_hallway.py
python/script_device_PIR_hallway.py
#!/usr/bin/python # -*- coding: utf-8 -*- import domoticz try: execfile("/etc/domoticz/scripts.conf") except: exec(open("/etc/domoticz/scripts.conf").read()) debug = True if changed_device.name == pir: if debug: domoticz.log("Start " + pir) dev = domoticz.devices[atSleep] dev.off() if debug: domoticz.log("End " + pir)
#!/usr/bin/python # -*- coding: utf-8 -*- import domoticz try: execfile("/etc/domoticz/scripts.conf") except: exec(open("/etc/domoticz/scripts.conf").read()) debug = True if changed_device.name == pir and changed_device.is_on(): if debug: domoticz.log("Start " + pir) dev = domoticz.devices[atSleep] dev.off() if debug: domoticz.log("End " + pir)
Make pir in hallway only trigger at on events
Make pir in hallway only trigger at on events
Python
mit
tomhur/domoticz-scripts,tomhur/domoticz-scripts
--- +++ @@ -9,7 +9,7 @@ debug = True -if changed_device.name == pir: +if changed_device.name == pir and changed_device.is_on(): if debug: domoticz.log("Start " + pir) dev = domoticz.devices[atSleep]
70df4ca8235b3ae29ef2843169f9119d29bda44a
tracker/models/__init__.py
tracker/models/__init__.py
from BasicInfo import BasicInfo from BloodExam import BloodExam from BloodExam import BloodParasite from Child import Child from ChildForm import ChildForm from DentalExam import DentalExam from DentalExam import DentalExamDiagnosis from MedicalExamPart1Info import MedicalExamPart1Info from MedicalExamPart2Info import MedicalExamPart2Info from MedicalExamPart2Info import MedicalExamDiagnosis from PsychologicalExamInfo import PsychologicalExamInfo from PsychologicalExamInfo import PsychologicalExamDiagnosis from Residence import Residence from SocialExamInfo import SocialExamInfo
from BasicInfo import BasicInfo from BloodExam import BloodExam from BloodExam import BloodParasite from Child import Child from ChildForm import ChildForm from DentalExam import DentalExam from DentalExam import DentalExamDiagnosis from MedicalExamPart1Info import MedicalExamPart1Info from MedicalExamPart2Info import MedicalExamPart2Info from MedicalExamPart2Info import MedicalExamDiagnosis from PsychologicalExamInfo import PsychologicalExamInfo from PsychologicalExamInfo import PsychologicalExamDiagnosis from Residence import Residence from SocialExamInfo import SocialExamInfo from ConsultationHistory import ConsultationHistory from DiseaseHistory import DiseaseHistory from OperationHistory import OperationHistory
Include history in the models.
Include history in the models.
Python
mit
sscalpone/HBI,sscalpone/HBI,sscalpone/HBI,sscalpone/HBI
--- +++ @@ -12,3 +12,6 @@ from PsychologicalExamInfo import PsychologicalExamDiagnosis from Residence import Residence from SocialExamInfo import SocialExamInfo +from ConsultationHistory import ConsultationHistory +from DiseaseHistory import DiseaseHistory +from OperationHistory import OperationHistory
5368e0ad7be4cdf7df2da392fdaabb89c3a4ad55
test_settings.py
test_settings.py
SECRET_KEY = "lorem ipsum" INSTALLED_APPS = ( 'tango_shared', )
SECRET_KEY = "lorem ipsum" INSTALLED_APPS = ( 'tango_shared', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } SITE_ID = 1
Add missing test settings (in-memory sqlite3 db + SITE_ID)
Add missing test settings (in-memory sqlite3 db + SITE_ID)
Python
mit
tBaxter/tango-shared-core,tBaxter/tango-shared-core,tBaxter/tango-shared-core
--- +++ @@ -3,3 +3,12 @@ INSTALLED_APPS = ( 'tango_shared', ) + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': ':memory:', + } +} + +SITE_ID = 1
f629e0ea3dc06e91d6d666b1a8bfefdd925287ff
rafem/__init__.py
rafem/__init__.py
"""River Avulsion Module.""" from .riverbmi import BmiRiverModule from .rivermodule import RiverModule __all__ = ['BmiRiverModule', 'RiverModule']
"""River Avulsion Module.""" from .riverbmi import BmiRiverModule from .rivermodule import rivermodule __all__ = ['BmiRiverModule', 'rivermodule']
Rename package from avulsion to rafem.
Rename package from avulsion to rafem.
Python
mit
katmratliff/avulsion-bmi,mcflugen/avulsion-bmi
--- +++ @@ -1,7 +1,7 @@ """River Avulsion Module.""" from .riverbmi import BmiRiverModule -from .rivermodule import RiverModule +from .rivermodule import rivermodule -__all__ = ['BmiRiverModule', 'RiverModule'] +__all__ = ['BmiRiverModule', 'rivermodule']
46956660b1c4533e7a69fe2aa0dc17b73ce490ac
transporter/transporter.py
transporter/transporter.py
from urlparse import urlparse import os import adapters try: import paramiko except ImportError: pass """The following protocals are supported ftp, ftps, http and https. sftp and ssh require paramiko to be installed """ class Transporter(object): availible_adapters = { "ftp": adapters.FtpAdapter, "ftps": adapters.FtpAdapter, "file": adapters.LocalFileAdapter } adapter = None def __init__(self, uri): uri = urlparse(uri) if uri.scheme not in self.availible_adapters: msg = u"{0} is not a support scheme. Availible schemes: {1}".format( uri.scheme, [s for s in self.availible_adapters]) raise NotImplemented(msg) self.adapter = self.availible_adapters[uri.scheme](uri) def __getattr__(self, attr): return getattr(self.adapter, attr) def __repr__(self): return u'<Transporter {0}>'.format(self.adapter.__repr__()) def download(uri): f = os.path.basename(uri) uri = os.path.dirname(uri) uri = urlparse(uri) return Transporter(uri).download(f) def upload(f, uri): return Transporter(uri).upload(f) def transport(source, destination): f = download(source) return upload(destination, f)
from urlparse import urlparse import os import adapters try: import paramiko except ImportError: pass """The following protocals are supported ftp, ftps, http and https. sftp and ssh require paramiko to be installed """ class Transporter(object): availible_adapters = { "ftp": adapters.FtpAdapter, "ftps": adapters.FtpAdapter, "file": adapters.LocalFileAdapter } default_scheme = "file" adapter = None def __init__(self, uri): uri = urlparse(uri) scheme = uri.scheme or self.default_scheme if scheme not in self.availible_adapters: msg = u"{0} is not a support scheme. Availible schemes: {1}".format( scheme, [s for s in self.availible_adapters]) raise NotImplemented(msg) self.adapter = self.availible_adapters[scheme](uri) def __getattr__(self, attr): return getattr(self.adapter, attr) def __repr__(self): return u'<Transporter {0}>'.format(self.adapter.__repr__()) def download(uri): f = os.path.basename(uri) uri = os.path.dirname(uri) uri = urlparse(uri) return Transporter(uri).download(f) def upload(f, uri): return Transporter(uri).upload(f) def transport(source, destination): f = download(source) return upload(destination, f)
Use LocalFileAdapter when no scheme is given
Use LocalFileAdapter when no scheme is given >>> t1 = Transporter('/file/path') >>> t2 = Transporter('file:/file/path') >>> type(t1.adapter) == type(t2.adapter) True >>> t1.pwd() == t2.pwd() True
Python
bsd-2-clause
joshmaker/transporter
--- +++ @@ -19,16 +19,18 @@ "ftps": adapters.FtpAdapter, "file": adapters.LocalFileAdapter } + default_scheme = "file" adapter = None def __init__(self, uri): uri = urlparse(uri) - if uri.scheme not in self.availible_adapters: + scheme = uri.scheme or self.default_scheme + if scheme not in self.availible_adapters: msg = u"{0} is not a support scheme. Availible schemes: {1}".format( - uri.scheme, [s for s in self.availible_adapters]) + scheme, [s for s in self.availible_adapters]) raise NotImplemented(msg) - self.adapter = self.availible_adapters[uri.scheme](uri) + self.adapter = self.availible_adapters[scheme](uri) def __getattr__(self, attr): return getattr(self.adapter, attr)
a62343a536bf6a8b655ace66e09a17ea483e6fbe
txircd/modules/cmd_user.py
txircd/modules/cmd_user.py
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":You may not reregister") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
Fix message with 462 numeric
Fix message with 462 numeric
Python
bsd-3-clause
ElementalAlchemist/txircd,DesertBus/txircd,Heufneutje/txircd
--- +++ @@ -13,7 +13,7 @@ def processParams(self, user, params): if user.registered == 0: - user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") + user.sendMessage(irc.ERR_ALREADYREGISTRED, ":You may not reregister") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters")
dfdd9b2a8bad5d61f5bf166d9c72b19f4c639383
mock/buildbot_secret.py
mock/buildbot_secret.py
GITHUB_WEBHOOK_SECRET="nothing to see here" GITHUB_OAUTH_CLIENT_ID="nothing to see here" GITHUB_OAUTH_CLIENT_SECRET="nothing to see here" GITHUB_STATUS_OAUTH_TOKEN="nothing to see here" COVERALLS_REPO_TOKEN="nothing to see here" CODECOV_REPO_TOKEN="nothing to see here" FREEBSDCI_OAUTH_TOKEN="nothing to see here" FQDN="buildog.julialang.org" BUILDBOT_BRANCH="master" db_user="nothing to see here" db_password="nothing to see here" DOCUMENTER_KEY="nothing to see here"
GITHUB_WEBHOOK_SECRET="nothing to see here" GITHUB_OAUTH_CLIENT_ID="nothing to see here" GITHUB_OAUTH_CLIENT_SECRET="nothing to see here" GITHUB_STATUS_OAUTH_TOKEN="nothing to see here" COVERALLS_REPO_TOKEN="nothing to see here" CODECOV_REPO_TOKEN="nothing to see here" FREEBSDCI_OAUTH_TOKEN="nothing to see here" FQDN="buildog.julialang.org" BUILDBOT_BRANCH="master" db_user="nothing to see here" db_password="nothing to see here" DOCUMENTER_KEY="nothing to see here" MACOS_CODESIGN_IDENTITY="nothing to see here"
Add mock value for `MACOS_CODESIGN_IDENTITY`
Add mock value for `MACOS_CODESIGN_IDENTITY`
Python
mit
staticfloat/julia-buildbot,staticfloat/julia-buildbot
--- +++ @@ -10,3 +10,4 @@ db_user="nothing to see here" db_password="nothing to see here" DOCUMENTER_KEY="nothing to see here" +MACOS_CODESIGN_IDENTITY="nothing to see here"
886c2b92d8dcc40577341245f7973d4a2d31aa90
tests/core/test_mixer.py
tests/core/test_mixer.py
from __future__ import absolute_import, unicode_literals import unittest from mopidy import core class CoreMixerTest(unittest.TestCase): def setUp(self): # noqa: N802 self.core = core.Core(mixer=None, backends=[]) def test_volume(self): self.assertEqual(self.core.mixer.get_volume(), None) self.core.mixer.set_volume(30) self.assertEqual(self.core.mixer.get_volume(), 30) self.core.mixer.set_volume(70) self.assertEqual(self.core.mixer.get_volume(), 70) def test_mute(self): self.assertEqual(self.core.mixer.get_mute(), False) self.core.mixer.set_mute(True) self.assertEqual(self.core.mixer.get_mute(), True)
from __future__ import absolute_import, unicode_literals import unittest import mock from mopidy import core, mixer class CoreMixerTest(unittest.TestCase): def setUp(self): # noqa: N802 self.mixer = mock.Mock(spec=mixer.Mixer) self.core = core.Core(mixer=self.mixer, backends=[]) def test_get_volume(self): self.mixer.get_volume.return_value.get.return_value = 30 self.assertEqual(self.core.mixer.get_volume(), 30) self.mixer.get_volume.assert_called_once_with() def test_set_volume(self): self.core.mixer.set_volume(30) self.mixer.set_volume.assert_called_once_with(30) def test_get_mute(self): self.mixer.get_mute.return_value.get.return_value = True self.assertEqual(self.core.mixer.get_mute(), True) self.mixer.get_mute.assert_called_once_with() def test_set_mute(self): self.core.mixer.set_mute(True) self.mixer.set_mute.assert_called_once_with(True)
Use a mixer mock in tests
core: Use a mixer mock in tests
Python
apache-2.0
ali/mopidy,tkem/mopidy,dbrgn/mopidy,ali/mopidy,bacontext/mopidy,SuperStarPL/mopidy,mokieyue/mopidy,SuperStarPL/mopidy,swak/mopidy,mopidy/mopidy,jodal/mopidy,ali/mopidy,swak/mopidy,dbrgn/mopidy,dbrgn/mopidy,ZenithDK/mopidy,rawdlite/mopidy,hkariti/mopidy,quartz55/mopidy,jodal/mopidy,jodal/mopidy,kingosticks/mopidy,vrs01/mopidy,rawdlite/mopidy,diandiankan/mopidy,hkariti/mopidy,SuperStarPL/mopidy,dbrgn/mopidy,jcass77/mopidy,adamcik/mopidy,pacificIT/mopidy,jmarsik/mopidy,tkem/mopidy,jmarsik/mopidy,mopidy/mopidy,diandiankan/mopidy,tkem/mopidy,mopidy/mopidy,vrs01/mopidy,rawdlite/mopidy,vrs01/mopidy,ali/mopidy,pacificIT/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,ZenithDK/mopidy,jcass77/mopidy,bacontext/mopidy,ZenithDK/mopidy,glogiotatidis/mopidy,adamcik/mopidy,SuperStarPL/mopidy,glogiotatidis/mopidy,pacificIT/mopidy,bacontext/mopidy,bencevans/mopidy,vrs01/mopidy,rawdlite/mopidy,jcass77/mopidy,quartz55/mopidy,ZenithDK/mopidy,swak/mopidy,bencevans/mopidy,quartz55/mopidy,mokieyue/mopidy,kingosticks/mopidy,bencevans/mopidy,kingosticks/mopidy,diandiankan/mopidy,bencevans/mopidy,glogiotatidis/mopidy,tkem/mopidy,quartz55/mopidy,diandiankan/mopidy,mokieyue/mopidy,mokieyue/mopidy,jmarsik/mopidy,bacontext/mopidy,swak/mopidy,adamcik/mopidy,hkariti/mopidy,hkariti/mopidy,pacificIT/mopidy
--- +++ @@ -2,27 +2,34 @@ import unittest -from mopidy import core +import mock + +from mopidy import core, mixer class CoreMixerTest(unittest.TestCase): def setUp(self): # noqa: N802 - self.core = core.Core(mixer=None, backends=[]) + self.mixer = mock.Mock(spec=mixer.Mixer) + self.core = core.Core(mixer=self.mixer, backends=[]) - def test_volume(self): - self.assertEqual(self.core.mixer.get_volume(), None) + def test_get_volume(self): + self.mixer.get_volume.return_value.get.return_value = 30 + self.assertEqual(self.core.mixer.get_volume(), 30) + self.mixer.get_volume.assert_called_once_with() + + def test_set_volume(self): self.core.mixer.set_volume(30) - self.assertEqual(self.core.mixer.get_volume(), 30) + self.mixer.set_volume.assert_called_once_with(30) - self.core.mixer.set_volume(70) + def test_get_mute(self): + self.mixer.get_mute.return_value.get.return_value = True - self.assertEqual(self.core.mixer.get_volume(), 70) + self.assertEqual(self.core.mixer.get_mute(), True) + self.mixer.get_mute.assert_called_once_with() - def test_mute(self): - self.assertEqual(self.core.mixer.get_mute(), False) - + def test_set_mute(self): self.core.mixer.set_mute(True) - self.assertEqual(self.core.mixer.get_mute(), True) + self.mixer.set_mute.assert_called_once_with(True)
c45e00924fbe90fb6ff9465202a77d390c685dc4
tests/test_cli_update.py
tests/test_cli_update.py
# -*- coding: utf-8 -*- import pathlib import json def test_store_template_data_to_json(cli_runner, tmp_rc, tmp_templates_file): result = cli_runner([ '-c', tmp_rc, 'update' ]) assert result.exit_code == 0 templates = pathlib.Path(tmp_templates_file) assert templates.exists() with templates.open('r', encoding='utf8') as fh: template_data = json.load(fh) fetched_templates = [template['name'] for template in template_data] expected_templates = [ 'cookiecutter-pypackage', 'cookiecutter-pylibrary', 'cookiecutter-pytest-plugin', 'cookiecutter-tapioca', 'cookiecutter-django', ] assert fetched_templates == expected_templates
# -*- coding: utf-8 -*- import pathlib import json from configparser import RawConfigParser import pytest def test_store_template_data_to_json(cli_runner, tmp_rc, tmp_templates_file): result = cli_runner([ '-c', tmp_rc, 'update' ]) assert result.exit_code == 0 templates = pathlib.Path(tmp_templates_file) assert templates.exists() with templates.open('r', encoding='utf8') as fh: template_data = json.load(fh) fetched_templates = [template['name'] for template in template_data] expected_templates = [ 'cookiecutter-pypackage', 'cookiecutter-pylibrary', 'cookiecutter-pytest-plugin', 'cookiecutter-tapioca', 'cookiecutter-django', ] assert fetched_templates == expected_templates @pytest.fixture def incomplete_rc(tmpdir): rc_file = str(tmpdir / 'noperc') config = RawConfigParser() config['nope'] = {'foo': 'bar'} with open(rc_file, 'w', encoding='utf-8') as fh: config.write(fh) return rc_file def test_fail_missing_username(cli_runner, incomplete_rc, tmp_templates_file): result = cli_runner([ '-c', incomplete_rc, 'update', '-t', '1234', '-d', tmp_templates_file ]) assert result.exit_code == 2 assert 'Error: Missing option "-u" / "--username".' in result.output
Implement a test for missing username in update cmd
Implement a test for missing username in update cmd
Python
bsd-3-clause
hackebrot/cibopath
--- +++ @@ -2,6 +2,9 @@ import pathlib import json +from configparser import RawConfigParser + +import pytest def test_store_template_data_to_json(cli_runner, tmp_rc, tmp_templates_file): @@ -26,3 +29,26 @@ 'cookiecutter-django', ] assert fetched_templates == expected_templates + + +@pytest.fixture +def incomplete_rc(tmpdir): + rc_file = str(tmpdir / 'noperc') + + config = RawConfigParser() + config['nope'] = {'foo': 'bar'} + + with open(rc_file, 'w', encoding='utf-8') as fh: + config.write(fh) + return rc_file + + +def test_fail_missing_username(cli_runner, incomplete_rc, tmp_templates_file): + result = cli_runner([ + '-c', incomplete_rc, 'update', + '-t', '1234', + '-d', tmp_templates_file + ]) + + assert result.exit_code == 2 + assert 'Error: Missing option "-u" / "--username".' in result.output
a4104dea137b8fa2aedc38ac3bda53c559c1f45a
tests/test_opentransf.py
tests/test_opentransf.py
import pymorph import numpy as np def test_opentransf(): f = np.array([ [0,0,0,0,0,0,0,0], [0,0,1,1,1,1,0,0], [0,1,0,1,1,1,0,0], [0,0,1,1,1,1,0,0], [1,1,0,0,0,0,0,0]], bool) ot = pymorph.opentransf( f, 'city-block') for y in xrange(ot.shape[0]): for x in xrange(ot.shape[1]): r = ot[y,x] t = f.copy() for k in xrange(1, r+1): assert t[y,x] t = pymorph.open(f, pymorph.sedisk(k, 2, 'city-block')) assert not t[y,x] def test_all(): f = np.arange(9).reshape((3,3)) % 3 > 0 # linear-h crashed in 0.95 # and was underlying cause of crash in patsec(f, 'linear-h') g = pymorph.opentransf(f, 'linear-h')
import pymorph import numpy as np def test_opentransf(): f = np.array([ [0,0,0,0,0,0,0,0], [0,0,1,1,1,1,0,0], [0,1,0,1,1,1,0,0], [0,0,1,1,1,1,0,0], [1,1,0,0,0,0,0,0]], bool) ot = pymorph.opentransf( f, 'city-block') for y in xrange(ot.shape[0]): for x in xrange(ot.shape[1]): r = ot[y,x] t = f.copy() for k in xrange(1, r+1): assert t[y,x] t = pymorph.open(f, pymorph.sedisk(k, 2, 'city-block')) assert not t[y,x] def test_all_types(): f = np.arange(9).reshape((3,3)) % 3 > 0 # linear-h crashed in 0.95 # and was underlying cause of crash in patsec(f, 'linear-h') def test_type(type, Buser): g = pymorph.opentransf(f, type, Buser=Buser) yield test_type, 'linear-h', None yield test_type, 'octagon', None yield test_type, 'chessboard', None yield test_type, 'city-block', None yield test_type, 'linear-v', None yield test_type, 'linear-45r', None yield test_type, 'linear-45l', None Buser = np.ones((3,3),bool) Buser[2,2] = 0 yield test_type, 'user', Buser
Test all cases of type for opentransf
TST: Test all cases of type for opentransf
Python
bsd-3-clause
luispedro/pymorph
--- +++ @@ -17,9 +17,21 @@ t = pymorph.open(f, pymorph.sedisk(k, 2, 'city-block')) assert not t[y,x] -def test_all(): +def test_all_types(): f = np.arange(9).reshape((3,3)) % 3 > 0 # linear-h crashed in 0.95 # and was underlying cause of crash in patsec(f, 'linear-h') - g = pymorph.opentransf(f, 'linear-h') + def test_type(type, Buser): + g = pymorph.opentransf(f, type, Buser=Buser) + + yield test_type, 'linear-h', None + yield test_type, 'octagon', None + yield test_type, 'chessboard', None + yield test_type, 'city-block', None + yield test_type, 'linear-v', None + yield test_type, 'linear-45r', None + yield test_type, 'linear-45l', None + Buser = np.ones((3,3),bool) + Buser[2,2] = 0 + yield test_type, 'user', Buser
95e1d4c2ec42f09fddf48c5a32f0fe409132380b
lab/monitors/nova_service_list.py
lab/monitors/nova_service_list.py
def start(lab, log, args): import time from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') duration = args['duration'] period = args['period'] statuses = {'up': 1, 'down': 0} server = lab.director() start_time = time.time() while start_time + duration > time.time(): with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg)) time.sleep(period)
def start(lab, log, args): from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') statuses = {'up': 1, 'down': 0} server = lab.director() with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg))
Verify services status if FI is rebooted
Verify services status if FI is rebooted Change-Id: Ia02ef16d53fbb7b55a8de884ff16a4bef345a1f2
Python
apache-2.0
CiscoSystems/os-sqe,CiscoSystems/os-sqe,CiscoSystems/os-sqe
--- +++ @@ -1,20 +1,15 @@ def start(lab, log, args): - import time from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') - duration = args['duration'] - period = args['period'] statuses = {'up': 1, 'down': 0} server = lab.director() - start_time = time.time() - while start_time + duration > time.time(): - with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): - res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) - results = [line.split() for line in res.split('\n')] - msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) - log.info('{1}'.format(grep_host, msg)) - time.sleep(period) + with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): + res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) + results = [line.split() for line in res.split('\n')] + msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) + log.info('{1}'.format(grep_host, msg)) +
26bae1f6094550939b1ed2ded3885e5d7befc39d
rply/token.py
rply/token.py
class BaseBox(object): pass class Token(BaseBox): def __init__(self, name, value, source_pos=None): BaseBox.__init__(self) self.name = name self.value = value self.source_pos = source_pos def __eq__(self, other): return self.name == other.name and self.value == other.value def gettokentype(self): return self.name def getsourcepos(self): return self.source_pos def getstr(self): return self.value class SourcePosition(object): def __init__(self, idx, lineno, colno): self.idx = idx self.lineno = lineno self.colno = colno
class BaseBox(object): pass class Token(BaseBox): def __init__(self, name, value, source_pos=None): self.name = name self.value = value self.source_pos = source_pos def __eq__(self, other): return self.name == other.name and self.value == other.value def gettokentype(self): return self.name def getsourcepos(self): return self.source_pos def getstr(self): return self.value class SourcePosition(object): def __init__(self, idx, lineno, colno): self.idx = idx self.lineno = lineno self.colno = colno
Drop the __init__ call to object.__init__, RPython doesn't like it and it doesn't doa nything
Drop the __init__ call to object.__init__, RPython doesn't like it and it doesn't doa nything
Python
bsd-3-clause
agamdua/rply,agamdua/rply
--- +++ @@ -4,7 +4,6 @@ class Token(BaseBox): def __init__(self, name, value, source_pos=None): - BaseBox.__init__(self) self.name = name self.value = value self.source_pos = source_pos
be53f1234bec0bca4c35f020905e24d0637b91e3
tests/run/coroutines.py
tests/run/coroutines.py
# cython: language_level=3 # mode: run # tag: pep492, pure3.5 async def test_coroutine_frame(awaitable): """ >>> class Awaitable(object): ... def __await__(self): ... return iter([2]) >>> coro = test_coroutine_frame(Awaitable()) >>> import types >>> isinstance(coro.cr_frame, types.FrameType) or coro.cr_frame True >>> coro.cr_frame is coro.cr_frame # assert that it's cached True >>> coro.cr_frame.f_code is not None True >>> code_obj = coro.cr_frame.f_code >>> code_obj.co_argcount 1 >>> code_obj.co_varnames ('awaitable', 'b') >>> next(coro.__await__()) # avoid "not awaited" warning 2 """ b = await awaitable return b
# cython: language_level=3 # mode: run # tag: pep492, pure3.5, gh1462, async, await async def test_coroutine_frame(awaitable): """ >>> class Awaitable(object): ... def __await__(self): ... return iter([2]) >>> coro = test_coroutine_frame(Awaitable()) >>> import types >>> isinstance(coro.cr_frame, types.FrameType) or coro.cr_frame True >>> coro.cr_frame is coro.cr_frame # assert that it's cached True >>> coro.cr_frame.f_code is not None True >>> code_obj = coro.cr_frame.f_code >>> code_obj.co_argcount 1 >>> code_obj.co_varnames ('awaitable', 'b') >>> next(coro.__await__()) # avoid "not awaited" warning 2 """ b = await awaitable return b # gh1462: Using decorators on coroutines. def pass_through(func): return func @pass_through async def test_pass_through(): """ >>> t = test_pass_through() >>> try: t.send(None) ... except StopIteration as ex: ... print(ex.args[0] if ex.args else None) ... else: print("NOT STOPPED!") None """ @pass_through(pass_through) async def test_pass_through_with_args(): """ >>> t = test_pass_through_with_args() >>> try: t.send(None) ... except StopIteration as ex: ... print(ex.args[0] if ex.args else None) ... else: print("NOT STOPPED!") None """
Add an explicit test for async-def functions with decorators. Closes GH-1462.
Add an explicit test for async-def functions with decorators. Closes GH-1462.
Python
apache-2.0
scoder/cython,da-woods/cython,scoder/cython,scoder/cython,cython/cython,da-woods/cython,cython/cython,cython/cython,da-woods/cython,scoder/cython,cython/cython,da-woods/cython
--- +++ @@ -1,6 +1,6 @@ # cython: language_level=3 # mode: run -# tag: pep492, pure3.5 +# tag: pep492, pure3.5, gh1462, async, await async def test_coroutine_frame(awaitable): @@ -28,3 +28,33 @@ """ b = await awaitable return b + + +# gh1462: Using decorators on coroutines. + +def pass_through(func): + return func + + +@pass_through +async def test_pass_through(): + """ + >>> t = test_pass_through() + >>> try: t.send(None) + ... except StopIteration as ex: + ... print(ex.args[0] if ex.args else None) + ... else: print("NOT STOPPED!") + None + """ + + +@pass_through(pass_through) +async def test_pass_through_with_args(): + """ + >>> t = test_pass_through_with_args() + >>> try: t.send(None) + ... except StopIteration as ex: + ... print(ex.args[0] if ex.args else None) + ... else: print("NOT STOPPED!") + None + """
fa78cd1b3aa29cfe2846f4a999b4bb7436b339ea
tests/test_responses.py
tests/test_responses.py
from jsonrpcclient.responses import Ok, parse, parse_json def test_parse(): assert parse({"jsonrpc": "2.0", "result": "pong", "id": 1}) == Ok("pong", 1) def test_parse_json(): assert parse_json('{"jsonrpc": "2.0", "result": "pong", "id": 1}') == Ok("pong", 1)
from jsonrpcclient.responses import Error, Ok, parse, parse_json def test_Ok(): assert repr(Ok("foo", 1)) == "Ok(result='foo', id=1)" def test_Error(): assert ( repr(Error(1, "foo", "bar", 2)) == "Error(code=1, message='foo', data='bar', id=2)" ) def test_parse(): assert parse({"jsonrpc": "2.0", "result": "pong", "id": 1}) == Ok("pong", 1) def test_parse_json(): assert parse_json('{"jsonrpc": "2.0", "result": "pong", "id": 1}') == Ok("pong", 1)
Bring code coverage to 100%
Bring code coverage to 100%
Python
mit
bcb/jsonrpcclient
--- +++ @@ -1,4 +1,15 @@ -from jsonrpcclient.responses import Ok, parse, parse_json +from jsonrpcclient.responses import Error, Ok, parse, parse_json + + +def test_Ok(): + assert repr(Ok("foo", 1)) == "Ok(result='foo', id=1)" + + +def test_Error(): + assert ( + repr(Error(1, "foo", "bar", 2)) + == "Error(code=1, message='foo', data='bar', id=2)" + ) def test_parse():
9dfe31f52d1cf4dfb11a1ffd8c14274e4b9ec135
tests/test_tokenizer.py
tests/test_tokenizer.py
import unittest from halng.tokenizer import MegaHALTokenizer class testMegaHALTokenizer(unittest.TestCase): def setUp(self): self.tokenizer = MegaHALTokenizer() def testSplitEmpty(self): self.assertEquals(len(self.tokenizer.split("")), 0) def testSplitSentence(self): words = self.tokenizer.split("hi.") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitImplicitStop(self): words = self.tokenizer.split("hi") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitUrl(self): words = self.tokenizer.split("http://www.google.com/") self.assertEquals(len(words), 8) self.assertEquals(words[0], "HTTP") self.assertEquals(words[1], "://") self.assertEquals(words[2], "WWW") self.assertEquals(words[3], ".") self.assertEquals(words[4], "GOOGLE") self.assertEquals(words[5], ".") self.assertEquals(words[6], "COM") self.assertEquals(words[7], "/.") if __name__ == '__main__': unittest.main()
import unittest from halng.tokenizer import MegaHALTokenizer class testMegaHALTokenizer(unittest.TestCase): def setUp(self): self.tokenizer = MegaHALTokenizer() def testSplitEmpty(self): self.assertEquals(len(self.tokenizer.split("")), 0) def testSplitSentence(self): words = self.tokenizer.split("hi.") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitComma(self): words = self.tokenizer.split("hi, hal") self.assertEquals(len(words), 4) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ", ") self.assertEquals(words[2], "HAL") self.assertEquals(words[3], ".") def testSplitImplicitStop(self): words = self.tokenizer.split("hi") self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") def testSplitUrl(self): words = self.tokenizer.split("http://www.google.com/") self.assertEquals(len(words), 8) self.assertEquals(words[0], "HTTP") self.assertEquals(words[1], "://") self.assertEquals(words[2], "WWW") self.assertEquals(words[3], ".") self.assertEquals(words[4], "GOOGLE") self.assertEquals(words[5], ".") self.assertEquals(words[6], "COM") self.assertEquals(words[7], "/.") if __name__ == '__main__': unittest.main()
Add a test that ensures commas are part of non-word runs.
Add a test that ensures commas are part of non-word runs.
Python
mit
meska/cobe,wodim/cobe-ng,meska/cobe,tiagochiavericosta/cobe,DarkMio/cobe,LeMagnesium/cobe,tiagochiavericosta/cobe,pteichman/cobe,pteichman/cobe,LeMagnesium/cobe,DarkMio/cobe,wodim/cobe-ng
--- +++ @@ -14,6 +14,14 @@ self.assertEquals(len(words), 2) self.assertEquals(words[0], "HI") self.assertEquals(words[1], ".") + + def testSplitComma(self): + words = self.tokenizer.split("hi, hal") + self.assertEquals(len(words), 4) + self.assertEquals(words[0], "HI") + self.assertEquals(words[1], ", ") + self.assertEquals(words[2], "HAL") + self.assertEquals(words[3], ".") def testSplitImplicitStop(self): words = self.tokenizer.split("hi")
9ffcae90963ed97136142bdd1443f633f11a5837
settings.py
settings.py
from fabric.api import env env.hosts = ['zygal@kontar.kattare.com'] env.local_dir = 'public' env.remote_dir = 'temp'
from fabric.api import env env.hosts = ['myuser@mysite.com'] env.local_dir = 'public' env.remote_dir = 'temp'
Set some default hosts environment
Set some default hosts environment
Python
mit
nfletton/froid,nfletton/froid
--- +++ @@ -1,6 +1,6 @@ from fabric.api import env -env.hosts = ['zygal@kontar.kattare.com'] +env.hosts = ['myuser@mysite.com'] env.local_dir = 'public' env.remote_dir = 'temp'
03c7f149ac0162a78892593d33b5866a1a9b72df
tests/test_settings.py
tests/test_settings.py
from __future__ import unicode_literals from django.test import TestCase from rest_framework.settings import APISettings class TestSettings(TestCase): def test_import_error_message_maintained(self): """ Make sure import errors are captured and raised sensibly. """ settings = APISettings({ 'DEFAULT_RENDERER_CLASSES': [ 'tests.invalid_module.InvalidClassName' ] }) with self.assertRaises(ImportError): settings.DEFAULT_RENDERER_CLASSES class TestSettingTypes(TestCase): def test_settings_consistently_coerced_to_list(self): settings = APISettings({ 'DEFAULT_THROTTLE_CLASSES': ('rest_framework.throttling.BaseThrottle',) }) self.assertTrue(isinstance(settings.DEFAULT_THROTTLE_CLASSES, list)) settings = APISettings({ 'DEFAULT_THROTTLE_CLASSES': () }) self.assertTrue(isinstance(settings.DEFAULT_THROTTLE_CLASSES, list))
from __future__ import unicode_literals from django.test import TestCase from rest_framework.settings import APISettings class TestSettings(TestCase): def test_import_error_message_maintained(self): """ Make sure import errors are captured and raised sensibly. """ settings = APISettings({ 'DEFAULT_RENDERER_CLASSES': [ 'tests.invalid_module.InvalidClassName' ] }) with self.assertRaises(ImportError): settings.DEFAULT_RENDERER_CLASSES def test_loud_error_raised_on_removed_setting(self): """ Make sure user is alerted with an error when a removed setting is set. """ with self.asserRaise(AttributeError): APISettings({ 'MAX_PAGINATE_BY': 100 }) class TestSettingTypes(TestCase): def test_settings_consistently_coerced_to_list(self): settings = APISettings({ 'DEFAULT_THROTTLE_CLASSES': ('rest_framework.throttling.BaseThrottle',) }) self.assertTrue(isinstance(settings.DEFAULT_THROTTLE_CLASSES, list)) settings = APISettings({ 'DEFAULT_THROTTLE_CLASSES': () }) self.assertTrue(isinstance(settings.DEFAULT_THROTTLE_CLASSES, list))
Test case for settings check
Test case for settings check
Python
bsd-2-clause
davesque/django-rest-framework,dmwyatt/django-rest-framework,jpadilla/django-rest-framework,kgeorgy/django-rest-framework,atombrella/django-rest-framework,davesque/django-rest-framework,pombredanne/django-rest-framework,cyberj/django-rest-framework,ossanna16/django-rest-framework,dmwyatt/django-rest-framework,edx/django-rest-framework,johnraz/django-rest-framework,agconti/django-rest-framework,davesque/django-rest-framework,callorico/django-rest-framework,tomchristie/django-rest-framework,edx/django-rest-framework,uploadcare/django-rest-framework,pombredanne/django-rest-framework,pombredanne/django-rest-framework,sheppard/django-rest-framework,tomchristie/django-rest-framework,kgeorgy/django-rest-framework,callorico/django-rest-framework,linovia/django-rest-framework,edx/django-rest-framework,jpadilla/django-rest-framework,kgeorgy/django-rest-framework,agconti/django-rest-framework,tomchristie/django-rest-framework,jpadilla/django-rest-framework,johnraz/django-rest-framework,ossanna16/django-rest-framework,cyberj/django-rest-framework,rhblind/django-rest-framework,atombrella/django-rest-framework,werthen/django-rest-framework,linovia/django-rest-framework,uploadcare/django-rest-framework,rhblind/django-rest-framework,cyberj/django-rest-framework,werthen/django-rest-framework,ossanna16/django-rest-framework,sheppard/django-rest-framework,dmwyatt/django-rest-framework,linovia/django-rest-framework,rhblind/django-rest-framework,werthen/django-rest-framework,sheppard/django-rest-framework,callorico/django-rest-framework,atombrella/django-rest-framework,johnraz/django-rest-framework,agconti/django-rest-framework,uploadcare/django-rest-framework
--- +++ @@ -18,6 +18,16 @@ with self.assertRaises(ImportError): settings.DEFAULT_RENDERER_CLASSES + def test_loud_error_raised_on_removed_setting(self): + """ + Make sure user is alerted with an error when a removed setting + is set. + """ + with self.asserRaise(AttributeError): + APISettings({ + 'MAX_PAGINATE_BY': 100 + }) + class TestSettingTypes(TestCase): def test_settings_consistently_coerced_to_list(self):
fabc8a9cd7f2f23cac3b6cab12eb08fc83875045
vtki/_version.py
vtki/_version.py
""" version info for vtki """ # major, minor, patch version_info = 0, 16, 5 # Nice string for the version __version__ = '.'.join(map(str, version_info))
""" version info for vtki """ # major, minor, patch version_info = 0, 16, 6 # Nice string for the version __version__ = '.'.join(map(str, version_info))
Bump version: 0.16.5 → 0.16.6
Bump version: 0.16.5 → 0.16.6
Python
mit
akaszynski/vtkInterface
--- +++ @@ -1,6 +1,6 @@ """ version info for vtki """ # major, minor, patch -version_info = 0, 16, 5 +version_info = 0, 16, 6 # Nice string for the version __version__ = '.'.join(map(str, version_info))
4f5e20cc85395312ad66ef3731f2bf7e09987976
commands/alias.py
commands/alias.py
from devbot import chat def call(message, name, protocol, cfg, commands): if message == '': chat.say('/r ' + commands['help']['alias'].format('alias'), protocol) return aliases = '' for tupl in commands['regex'].items(): if tupl[1] == message: aliases = aliases + tupl[0] + ', ' if aliases == '': chat.say('Sorry, there is no command by that name.', protocol) else: chat.say('/r ' + aliases, protocol)
from devbot import chat def call(message, name, protocol, cfg, commands): if message == '': chat.say('/r ' + commands['help']['alias'].format('alias'), protocol) return aliases = '' for tupl in commands['regex'].items(): if tupl[1] == message: aliases = aliases + tupl[0] + ', ' if aliases == '': chat.say('/r Sorry, there is no command by that name.', protocol) else: chat.say('/r ' + aliases, protocol)
Fix bug with DevotedBot speaking error in chat
Fix bug with DevotedBot speaking error in chat
Python
mit
Ameliorate/DevotedBot,Ameliorate/DevotedBot
--- +++ @@ -11,7 +11,7 @@ if tupl[1] == message: aliases = aliases + tupl[0] + ', ' if aliases == '': - chat.say('Sorry, there is no command by that name.', protocol) + chat.say('/r Sorry, there is no command by that name.', protocol) else: chat.say('/r ' + aliases, protocol)
033a9c6e8b704eb92a7b1a9a82235fee7374f6be
logger/utilities.py
logger/utilities.py
#!/usr/bin/env python3 """Small utility functions for use in various places.""" __all__ = ["pick", "is_dunder", "convert_to_od", "counter_to_iterable"] import collections import itertools def pick(arg, default): """Handler for default versus given argument.""" return default if arg is None else arg def is_dunder(name): """Return True if a __dunder__ name, False otherwise.""" return name[:2] == name[-2:] == "__" and "_" not in (name[2:3], name[-3:-2]) def convert_to_od(mapping, order): """Convert mapping to an OrderedDict instance using order.""" return collections.OrderedDict([(i, mapping[i]) for i in order]) def counter_to_iterable(counter): """Convert a counter to an iterable / iterator.""" for item in itertools.starmap(itertools.repeat, counter): yield from item
#!/usr/bin/env python3 """Small utility functions for use in various places.""" __all__ = ["pick", "is_dunder", "convert_to_od", "counter_to_iterable", "count"] import collections import itertools def pick(arg, default): """Handler for default versus given argument.""" return default if arg is None else arg def is_dunder(name): """Return True if a __dunder__ name, False otherwise.""" return name[:2] == name[-2:] == "__" and "_" not in (name[2:3], name[-3:-2]) def convert_to_od(mapping, order): """Convert mapping to an OrderedDict instance using order.""" return collections.OrderedDict([(i, mapping[i]) for i in order]) def counter_to_iterable(counter): """Convert a counter to an iterable / iterator.""" for item in itertools.starmap(itertools.repeat, counter): yield from item def count(iterable): """Yield (item, count) two-tuples of the iterable.""" seen = [] full = list(iterable) for item in full: if item in seen: continue seen.append(item) yield (item, full.count(item))
Add a new 'count' utility function
Add a new 'count' utility function
Python
bsd-2-clause
Vgr255/logging
--- +++ @@ -2,7 +2,8 @@ """Small utility functions for use in various places.""" -__all__ = ["pick", "is_dunder", "convert_to_od", "counter_to_iterable"] +__all__ = ["pick", "is_dunder", "convert_to_od", + "counter_to_iterable", "count"] import collections import itertools @@ -23,3 +24,14 @@ """Convert a counter to an iterable / iterator.""" for item in itertools.starmap(itertools.repeat, counter): yield from item + +def count(iterable): + """Yield (item, count) two-tuples of the iterable.""" + seen = [] + full = list(iterable) + + for item in full: + if item in seen: + continue + seen.append(item) + yield (item, full.count(item))
e75e741770d1735c52770900b1cf59f207f2264e
asp/__init__.py
asp/__init__.py
# From http://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package # Author: James Antill (http://stackoverflow.com/users/10314/james-antill) __version__ = '0.1' __version_info__ = tuple([ int(num) for num in __version__.split('.')])
# From http://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package # Author: James Antill (http://stackoverflow.com/users/10314/james-antill) __version__ = '0.1' __version_info__ = tuple([ int(num) for num in __version__.split('.')]) class SpecializationError(Exception): """ Exception that caused specialization not to occur. Attributes: msg -- the message/explanation to the user phase -- which phase of specialization caused the error """ def __init__(self, msg, phase="Unknown phase"): self.value = value
Add asp.SpecializationError class for specialization-related exceptions.
Add asp.SpecializationError class for specialization-related exceptions.
Python
bsd-3-clause
shoaibkamil/asp,mbdriscoll/asp-old,mbdriscoll/asp-old,shoaibkamil/asp,richardxia/asp-multilevel-debug,richardxia/asp-multilevel-debug,pbirsinger/aspNew,pbirsinger/aspNew,mbdriscoll/asp-old,mbdriscoll/asp-old,shoaibkamil/asp,richardxia/asp-multilevel-debug,pbirsinger/aspNew
--- +++ @@ -2,3 +2,17 @@ # Author: James Antill (http://stackoverflow.com/users/10314/james-antill) __version__ = '0.1' __version_info__ = tuple([ int(num) for num in __version__.split('.')]) + + +class SpecializationError(Exception): + """ + Exception that caused specialization not to occur. + + Attributes: + msg -- the message/explanation to the user + phase -- which phase of specialization caused the error + """ + + def __init__(self, msg, phase="Unknown phase"): + self.value = value +
64fdf3a83b7b8649de6216cd67fb1a8ae0d3f1a0
bin/receive.py
bin/receive.py
#!/usr/bin/env python import pika import subprocess import json import os from pymongo import MongoClient dbcon = MongoClient() NETSNIFF_UTIL = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tools', 'netsniff.js') queuecon = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = queuecon.channel() channel.exchange_declare(exchange='perfmonitor', type='direct') result = channel.queue_declare('perf') queue_name = result.method.queue channel.queue_bind(exchange='perfmonitor', queue=queue_name, routing_key='perftest') print ' [*] Waiting for messages. To exit press CTRL+C' def callback(ch, method, properties, body): print " [x] Received %r" % (body,) content = json.loads(body) print ' [x] Executing command phantomjs', content['url'] harcontent = subprocess.check_output(['phantomjs', NETSNIFF_UTIL, content['url']]) jscontent = json.loads(harcontent) jscontent['site'] = content['site'] dbcon.perfmonitor.har.insert(jscontent) ch.basic_ack(delivery_tag = method.delivery_tag) print " [x] Done" channel.basic_consume(callback, queue=queue_name) channel.start_consuming()
#!/usr/bin/env python import pika import subprocess import json import os from pymongo import MongoClient dbcon = MongoClient() NETSNIFF_UTIL = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tools', 'netsniff.js') queuecon = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = queuecon.channel() channel.exchange_declare(exchange='perfmonitor', type='direct') result = channel.queue_declare('perf') queue_name = result.method.queue channel.queue_bind(exchange='perfmonitor', queue=queue_name, routing_key='perftest') print ' [*] Waiting for messages. To exit press CTRL+C' def callback(ch, method, properties, body): print " [x] Received %r" % (body,) content = json.loads(body) print ' [x] Executing command phantomjs', content['url'] harcontent = subprocess.check_output(['phantomjs', NETSNIFF_UTIL, content['url']]) try: jscontent = json.loads(harcontent) jscontent['site'] = content['site'] dbcon.perfmonitor.har.insert(jscontent) except: print ' [x] Unable to parse JSON, ignoring request' ch.basic_ack(delivery_tag = method.delivery_tag) print " [x] Done" channel.basic_consume(callback, queue=queue_name) channel.start_consuming()
Handle errors in queue processing
Handle errors in queue processing
Python
mit
leibowitz/perfmonitor,leibowitz/perfmonitor,leibowitz/perfmonitor
--- +++ @@ -28,9 +28,12 @@ content = json.loads(body) print ' [x] Executing command phantomjs', content['url'] harcontent = subprocess.check_output(['phantomjs', NETSNIFF_UTIL, content['url']]) - jscontent = json.loads(harcontent) - jscontent['site'] = content['site'] - dbcon.perfmonitor.har.insert(jscontent) + try: + jscontent = json.loads(harcontent) + jscontent['site'] = content['site'] + dbcon.perfmonitor.har.insert(jscontent) + except: + print ' [x] Unable to parse JSON, ignoring request' ch.basic_ack(delivery_tag = method.delivery_tag) print " [x] Done"
4708751802258c724bafe843845e91d88599df8b
marmoset/installimage/__init__.py
marmoset/installimage/__init__.py
from .installimage_config import InstallimageConfig def create(args): install_config = InstallimageConfig(args.mac) for var in args.var: install_config.add_or_set(var[0], var[1]) install_config.create() msg = 'Created %s with following Options:\n%s' % (install_config.file_path(), install_config.get_content()) print(msg) def list(args): for install_config in InstallimageConfig.all(): print('%s' % install_config.mac) def remove(args): install_config = InstallimageConfig(args.mac) if install_config.remove(): print('Removed', install_config.file_path()) else: print('No entry found for', install_config.mac)
Add cli handling for installimage
Add cli handling for installimage
Python
agpl-3.0
aibor/marmoset
--- +++ @@ -0,0 +1,27 @@ +from .installimage_config import InstallimageConfig + + +def create(args): + install_config = InstallimageConfig(args.mac) + + for var in args.var: + install_config.add_or_set(var[0], var[1]) + + install_config.create() + + msg = 'Created %s with following Options:\n%s' % (install_config.file_path(), install_config.get_content()) + + print(msg) + +def list(args): + for install_config in InstallimageConfig.all(): + print('%s' % install_config.mac) + + +def remove(args): + install_config = InstallimageConfig(args.mac) + if install_config.remove(): + print('Removed', install_config.file_path()) + else: + print('No entry found for', install_config.mac) +
6711d68999e5a9b0ea72a9a4f33cfc86b4230012
pattern_matcher/pattern_matcher.py
pattern_matcher/pattern_matcher.py
from .regex import RegexFactory from .patterns import Patterns class Matcher(object): NO_MATCH = 'NO MATCH' def __init__(self, raw_patterns, path, re_factory=RegexFactory): self.raw_patterns = raw_patterns self.path = path self.re = re_factory().create(self.path) self.patterns = Patterns(self.re.findall(self.raw_patterns)) class Matcher(object): def __init__(self, patterns, re_factory=RegexFactory): self.patterns self.re_factory = re_factory def _find_matches(self, path): regex = self.re_factory.new(path) return regex.findall(self.patterns) def _get_best_match(self, matches): pass def match(self, path): """Matches a path to a path pattern.""" matches = self._find_matches(path) return self._get_best_match(matches) class PathMatcher(object): """Matches a Path to the Path Pattern.""" def __init__(self, input, output): self.input = InputManager(input) self.output = OutputManager(output) self.matcher = Matcher() def match(self): for path in self.input.stream: self.matcher.match(path.strip()) # send to stdout class InputManager(object): """Manages the input to the matcher.""" pass class OutputManager(object): """Manages the output of the matcher.""" pass if __name__ == '__main__': import sys main = PathMatcher(sys.stdin, sys.stdout) main.match()
from .regex import RegexFactory from .patterns import Patterns class Matcher(object): NO_MATCH = 'NO MATCH' def __init__(self, raw_patterns, path, re_factory=RegexFactory): self.raw_patterns = raw_patterns self.path = path self.re = re_factory().create(self.path) self.patterns = Patterns(self.re.findall(self.raw_patterns)) def match(self): matches = self.patterns.get_best_patterns() if len(matches) != 1: return self.NO_MATCH return str(matches.pop()) class PathMatcher(object): """Matches a Path to the Path Pattern.""" def __init__(self, input, output): self.input = InputManager(input) self.output = OutputManager(output) self.matcher = Matcher def match(self): for path in self.input.stream: matcher = self.Matcher(path.strip()) print(matcher.match()) # send to stdout class InputManager(object): """Manages the input to the matcher.""" pass class OutputManager(object): """Manages the output of the matcher.""" pass if __name__ == '__main__': import sys main = PathMatcher(sys.stdin, sys.stdout) main.match()
Change the way the Matcher is initialized and how matches are retrieved.
Change the way the Matcher is initialized and how matches are retrieved.
Python
mit
damonkelley/pattern-matcher
--- +++ @@ -11,22 +11,13 @@ self.re = re_factory().create(self.path) self.patterns = Patterns(self.re.findall(self.raw_patterns)) -class Matcher(object): - def __init__(self, patterns, re_factory=RegexFactory): - self.patterns - self.re_factory = re_factory + def match(self): + matches = self.patterns.get_best_patterns() - def _find_matches(self, path): - regex = self.re_factory.new(path) - return regex.findall(self.patterns) + if len(matches) != 1: + return self.NO_MATCH - def _get_best_match(self, matches): - pass - - def match(self, path): - """Matches a path to a path pattern.""" - matches = self._find_matches(path) - return self._get_best_match(matches) + return str(matches.pop()) class PathMatcher(object): @@ -35,11 +26,12 @@ def __init__(self, input, output): self.input = InputManager(input) self.output = OutputManager(output) - self.matcher = Matcher() + self.matcher = Matcher def match(self): for path in self.input.stream: - self.matcher.match(path.strip()) + matcher = self.Matcher(path.strip()) + print(matcher.match()) # send to stdout
34b736645e45126c6cabb6d3f5427a697ebe74ff
tutorial/polls/views.py
tutorial/polls/views.py
from django.shortcuts import render # Create your views here.
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello world you are at the index")
Create a simple Index view
Create a simple Index view
Python
mit
ikosenn/django_reignited,ikosenn/django_reignited
--- +++ @@ -1,3 +1,7 @@ from django.shortcuts import render +from django.http import HttpResponse + # Create your views here. +def index(request): + return HttpResponse("Hello world you are at the index")
1bc95e2e2a2d4d0daf6cfcdbf7e4803b13262a49
etcd3/__init__.py
etcd3/__init__.py
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' import grpc from etcdrpc import rpc_pb2 as etcdrpc channel = grpc.insecure_channel('localhost:2379') stub = etcdrpc.KVStub(channel) put_request = etcdrpc.PutRequest() put_request.key = 'doot'.encode('utf-8') put_request.value = 'toottoot'.encode('utf-8') print(stub.Put(put_request)) class Etcd3Client(object): def __init__(self): pass def get(self, key): pass def put(self, key, value): pass
from __future__ import absolute_import __author__ = 'Louis Taylor' __email__ = 'louis@kragniz.eu' __version__ = '0.1.0' import grpc from etcdrpc import rpc_pb2 as etcdrpc class Etcd3Client(object): def __init__(self): self.channel = grpc.insecure_channel('localhost:2379') self.kvstub = etcdrpc.KVStub(channel) def get(self, key): pass def put(self, key, value): put_request = etcdrpc.PutRequest() put_request.key = key.encode('utf-8') put_request.value = value.encode('utf-8') self.kvstub.Put(put_request)
Move put code into method
Move put code into method
Python
apache-2.0
kragniz/python-etcd3
--- +++ @@ -8,21 +8,17 @@ from etcdrpc import rpc_pb2 as etcdrpc -channel = grpc.insecure_channel('localhost:2379') -stub = etcdrpc.KVStub(channel) - -put_request = etcdrpc.PutRequest() -put_request.key = 'doot'.encode('utf-8') -put_request.value = 'toottoot'.encode('utf-8') -print(stub.Put(put_request)) - class Etcd3Client(object): def __init__(self): - pass + self.channel = grpc.insecure_channel('localhost:2379') + self.kvstub = etcdrpc.KVStub(channel) def get(self, key): pass def put(self, key, value): - pass + put_request = etcdrpc.PutRequest() + put_request.key = key.encode('utf-8') + put_request.value = value.encode('utf-8') + self.kvstub.Put(put_request)
536211012be24a20c34ef0af1fcc555672129354
byceps/util/system.py
byceps/util/system.py
# -*- coding: utf-8 -*- """ byceps.util.system ~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import os CONFIG_ENV_VAR_NAME = 'BYCEPS_CONFIG' def get_config_env_name_from_env(*, default=None): """Return the configuration environment name set via environment variable. Raise an exception if it isn't set. """ env = os.environ.get(CONFIG_ENV_VAR_NAME) if env is None: if default is None: raise Exception( "No configuration environment was specified via the '{}' " "environment variable.".format(CONFIG_ENV_VAR_NAME)) env = default return env
# -*- coding: utf-8 -*- """ byceps.util.system ~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import os CONFIG_ENV_VAR_NAME = 'BYCEPS_CONFIG' def get_config_env_name_from_env(): """Return the configuration environment name set via environment variable. Raise an exception if it isn't set. """ env = os.environ.get(CONFIG_ENV_VAR_NAME) if not env: raise Exception( "No configuration environment was specified via the '{}' " "environment variable.".format(CONFIG_ENV_VAR_NAME)) return env
Remove default argument from function that reads the configuration name from the environment
Remove default argument from function that reads the configuration name from the environment
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps
--- +++ @@ -14,7 +14,7 @@ CONFIG_ENV_VAR_NAME = 'BYCEPS_CONFIG' -def get_config_env_name_from_env(*, default=None): +def get_config_env_name_from_env(): """Return the configuration environment name set via environment variable. @@ -22,12 +22,9 @@ """ env = os.environ.get(CONFIG_ENV_VAR_NAME) - if env is None: - if default is None: - raise Exception( - "No configuration environment was specified via the '{}' " - "environment variable.".format(CONFIG_ENV_VAR_NAME)) - - env = default + if not env: + raise Exception( + "No configuration environment was specified via the '{}' " + "environment variable.".format(CONFIG_ENV_VAR_NAME)) return env
703ba21925f2e7ad9c5bb970ac89e834676962a8
api/rest.py
api/rest.py
#!/usr/bin/env python from mcapi.mcapp import app from mcapi import tservices, public, utils, private, access from mcapi.user import account, datadirs, datafiles, reviews, ud import sys if __name__ == '__main__': if len(sys.argv) >= 2: debug = True else: debug = False if len(sys.argv) == 3: app.run(debug=debug, host='0.0.0.0') else: app.run(debug=debug)
#!/usr/bin/env python from mcapi.mcapp import app from mcapi import tservices, public, utils, private, access, process, machine, template from mcapi.user import account, datadirs, datafiles, reviews, ud import sys if __name__ == '__main__': if len(sys.argv) >= 2: debug = True else: debug = False if len(sys.argv) == 3: app.run(debug=debug, host='0.0.0.0') else: app.run(debug=debug)
Add in references to new services.
Add in references to new services.
Python
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
--- +++ @@ -1,7 +1,7 @@ #!/usr/bin/env python from mcapi.mcapp import app -from mcapi import tservices, public, utils, private, access +from mcapi import tservices, public, utils, private, access, process, machine, template from mcapi.user import account, datadirs, datafiles, reviews, ud import sys
87153cb1a9727d17d31f3aabb28affddca3191bf
sqltocpp.py
sqltocpp.py
import click from sqltocpp import convert @click.command() @click.option('--sql', help='schema file name') @click.option('--target', default='schema.hpp', help='hpp file name') def execute(sql, target): convert.schema_to_struct(sql, target) if __name__ == '__main__': try: execute() except: execute("--help")
import click from sqltocpp import convert @click.command() @click.argument('sql_schema_file') @click.option('--target', default='schema.hpp', help='hpp file name') def execute(sql_schema_file, target): convert.schema_to_struct(sql_schema_file, target) if __name__ == '__main__': execute()
Add click based commandline interface script
Add click based commandline interface script sqltocpp is intended to be a CLI command. This enables it to be so
Python
mit
banjocat/SqlToCpp,banjocat/SqlToCpp
--- +++ @@ -3,15 +3,12 @@ @click.command() -@click.option('--sql', help='schema file name') +@click.argument('sql_schema_file') @click.option('--target', default='schema.hpp', help='hpp file name') -def execute(sql, target): - convert.schema_to_struct(sql, target) +def execute(sql_schema_file, target): + convert.schema_to_struct(sql_schema_file, target) if __name__ == '__main__': - try: - execute() - except: - execute("--help") + execute()
fe2300d809d863b63f3100ff72757f48cb11789b
nn_patterns/explainer/__init__.py
nn_patterns/explainer/__init__.py
from .base import * from .gradient_based import * from .misc import * from .pattern_based import * from .relevance_based import * def create_explainer(name, output_layer, patterns=None, to_layer=None, **kwargs): return { # Utility. "input": InputExplainer, "random": RandomExplainer, # Gradient based "gradient": GradientExplainer, "deconvnet": DeConvNetExplainer, "guided": GuidedBackpropExplainer, "gradient.alt": AlternativeGradientExplainer, # Relevance based "lrp.z": LRPZExplainer, "lrp.eps": LRPEpsExplainer, # Pattern based "patternnet": PatternNetExplainer, "patternnet.guided": GuidedPatternNetExplainer, "patternlrp": PatternLRPExplainer, }[name](output_layer, patterns=patterns, to_layer=to_layer, **kwargs)
from .base import * from .gradient_based import * from .misc import * from .pattern_based import * from .relevance_based import * def create_explainer(name, output_layer, patterns=None, **kwargs): return { # Utility. "input": InputExplainer, "random": RandomExplainer, # Gradient based "gradient": GradientExplainer, "deconvnet": DeConvNetExplainer, "guided": GuidedBackpropExplainer, "gradient.alt": AlternativeGradientExplainer, # Relevance based "lrp.z": LRPZExplainer, "lrp.eps": LRPEpsExplainer, # Pattern based "patternnet": PatternNetExplainer, "patternnet.guided": GuidedPatternNetExplainer, "patternlrp": PatternLRPExplainer, }[name](output_layer, patterns=patterns, **kwargs)
Fix interface. to_layer parameter is obsolete.
Fix interface. to_layer parameter is obsolete.
Python
mit
pikinder/nn-patterns
--- +++ @@ -8,7 +8,7 @@ def create_explainer(name, - output_layer, patterns=None, to_layer=None, **kwargs): + output_layer, patterns=None, **kwargs): return { # Utility. "input": InputExplainer, @@ -28,4 +28,4 @@ "patternnet": PatternNetExplainer, "patternnet.guided": GuidedPatternNetExplainer, "patternlrp": PatternLRPExplainer, - }[name](output_layer, patterns=patterns, to_layer=to_layer, **kwargs) + }[name](output_layer, patterns=patterns, **kwargs)
267c17ce984952d16623b0305975626397529ca8
tests/config_test.py
tests/config_test.py
import pytest from timewreport.config import TimeWarriorConfig def test_get_value_should_return_value_if_key_available(): config = TimeWarriorConfig({'FOO': 'foo'}) assert config.get_value('FOO', 'bar') == 'foo' def test_get_value_should_return_default_if_key_not_available(): config = TimeWarriorConfig({'BAR': 'foo'}) assert config.get_value('FOO', 'bar') == 'bar' @pytest.fixture(scope='function', params=['on', 1, 'yes', 'y', 'true']) def trueish_value(request): return request.param def test_get_boolean_should_return_true_on_trueish_values(trueish_value): config = TimeWarriorConfig({'KEY': trueish_value}) assert config.get_boolean('KEY', False) is True def test_get_boolean_should_return_false_on_falseish_values(): config = TimeWarriorConfig({'KEY': 'foo'}) assert config.get_boolean('KEY', True) is False
import pytest from timewreport.config import TimeWarriorConfig def test_get_value_should_return_value_if_key_available(): config = TimeWarriorConfig({'FOO': 'foo'}) assert config.get_value('FOO', 'bar') == 'foo' def test_get_value_should_return_default_if_key_not_available(): config = TimeWarriorConfig({'BAR': 'foo'}) assert config.get_value('FOO', 'bar') == 'bar' @pytest.fixture(scope='function', params=['on', 1, 'yes', 'y', 'true']) def trueish_value(request): return request.param def test_get_boolean_should_return_true_on_trueish_values(trueish_value): config = TimeWarriorConfig({'KEY': trueish_value}) assert config.get_boolean('KEY', False) is True @pytest.fixture(scope='function', params=['off', 0, 'no', 'n', 'false']) def falseish_value(request): return request.param def test_get_boolean_should_return_false_on_falseish_values(falseish_value): config = TimeWarriorConfig({'KEY': falseish_value}) assert config.get_boolean('KEY', True) is False
Add tests for falseish config values
Add tests for falseish config values
Python
mit
lauft/timew-report
--- +++ @@ -26,7 +26,12 @@ assert config.get_boolean('KEY', False) is True -def test_get_boolean_should_return_false_on_falseish_values(): - config = TimeWarriorConfig({'KEY': 'foo'}) +@pytest.fixture(scope='function', params=['off', 0, 'no', 'n', 'false']) +def falseish_value(request): + return request.param + + +def test_get_boolean_should_return_false_on_falseish_values(falseish_value): + config = TimeWarriorConfig({'KEY': falseish_value}) assert config.get_boolean('KEY', True) is False
6c157525bc32f1e6005be69bd6fde61d0d002ad3
wizard/post_function.py
wizard/post_function.py
from openerp import pooler def call_post_function(cr, uid, context): """This functionality allows users of module account.move.reversal to call a function of the desired openerp model, after the reversal of the move. The call automatically sends at least the database cursor (cr) and the user id (uid) for security reasons. Two key parameters are required in the context to do so: - 'post_function_obj': the osv model where the function is defined, - 'post_function_name': the name of the function to call, And two optional key parameters: - 'post_function_args': an iterable object listing the required arguments to pass after 'cr, uid', - 'post_function_kwargs': a dictionary object listing the optionnal keyword args to pass. """ if 'post_function_obj' in context: # We get the function addr by its name, # and call it with (cr, uid, *args, **kwargs) getattr( pooler.get_pool(cr.dbname)[context['post_function_obj']], context['post_function_name'] )( cr, uid, *context['post_function_args'], **context['post_function_kwargs'] ) # We clean the context to avoid multiple calls of the function. context.pop('post_function_obj') context.pop('post_function_name') context.pop('post_function_args') context.pop('post_function_kwargs')
from openerp import pooler def call_post_function(cr, uid, context): """This functionality allows users of module account.move.reversal to call a function of the desired openerp model, after the reversal of the move. The call automatically sends at least the database cursor (cr) and the user id (uid) for security reasons. Two key parameters are required in the context to do so: - 'post_function_obj': the osv model where the function is defined, - 'post_function_name': the name of the function to call, And two optional key parameters: - 'post_function_args': an iterable object listing the required arguments to pass after 'cr, uid', - 'post_function_kwargs': a dictionary object listing the optionnal keyword args to pass. """ if 'post_function_obj' in context: # We get the function addr by its name, # and call it with (cr, uid, *args, **kwargs) getattr( pooler.get_pool(cr.dbname)[context['post_function_obj']], context['post_function_name'] )( cr, uid, *context.get('post_function_args', []), **context.get('post_function_kwargs', {}) ) # We clean the context to avoid multiple calls of the function. context.pop('post_function_obj') context.pop('post_function_name') context.pop('post_function_args') context.pop('post_function_kwargs')
Remove some required arguments in post function context
Remove some required arguments in post function context
Python
agpl-3.0
xcgd/account_move_reversal
--- +++ @@ -25,8 +25,8 @@ context['post_function_name'] )( cr, uid, - *context['post_function_args'], - **context['post_function_kwargs'] + *context.get('post_function_args', []), + **context.get('post_function_kwargs', {}) ) # We clean the context to avoid multiple calls of the function. context.pop('post_function_obj')
3271722d3905a7727c20989fa98d804cb4df1b82
mysite/urls.py
mysite/urls.py
"""vote URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ]
"""vote URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from django.http.response import HttpResponseRedirect urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), url(r'^$', lambda r: HttpResponseRedirect('polls/')), ]
Add redirect from / to /polls
Add redirect from / to /polls
Python
apache-2.0
gerard-/votingapp,gerard-/votingapp
--- +++ @@ -15,8 +15,10 @@ """ from django.conf.urls import include, url from django.contrib import admin +from django.http.response import HttpResponseRedirect urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), + url(r'^$', lambda r: HttpResponseRedirect('polls/')), ]
f405ee262ab6f87df8e83e024d3c615842fa37ce
fandjango/urls.py
fandjango/urls.py
from django.conf.urls.defaults import * from views import * urlpatterns = patterns('', url(r'^authorize_application.html$', authorize_application, name='authorize_application'), url(r'^deauthorize_application.html$', deauthorize_application) )
from django.conf.urls.defaults import * from views import * urlpatterns = patterns('', url(r'^authorize_application.html$', authorize_application, name='authorize_application'), url(r'^deauthorize_application.html$', deauthorize_application, name='deauthorize_application') )
Add a name to the URL configuration for 'deauthorize_application'
Add a name to the URL configuration for 'deauthorize_application'
Python
mit
jgorset/fandjango,jgorset/fandjango
--- +++ @@ -4,5 +4,5 @@ urlpatterns = patterns('', url(r'^authorize_application.html$', authorize_application, name='authorize_application'), - url(r'^deauthorize_application.html$', deauthorize_application) + url(r'^deauthorize_application.html$', deauthorize_application, name='deauthorize_application') )
a2ea31300e614c27c3f99e079293728bee9fbcf4
paws_config.py
paws_config.py
import tornado from tornado import gen import json import os BASE_PATH = '.' base_url = '/paws/public/' @gen.coroutine def uid_for_user(user): url = 'https://meta.wikimedia.org/w/api.php?' + \ 'action=query&meta=globaluserinfo' + \ '&format=json&formatversion=2' + \ '&guiuser={}'.format(user) client = tornado.httpclient.AsyncHTTPClient() resp = yield client.fetch(url) parsed = json.loads(resp.body.decode('utf-8')) if 'missing' in parsed['query']['globaluserinfo']: return None return parsed['query']['globaluserinfo']['id'] cached_uids = {} @gen.coroutine def path_for_url_segment(url): """ Takes a URL segment and returns a full filesystem path Example: input: YuviPanda/Something.ipynb output: 43/public/Something.ipynb """ splits = url.split('/') username = splits[0] path = '/'.join(splits[1:]) if username in cached_uids: uid = cached_uids[username] else: uid = yield uid_for_user(username) if uid is None: raise tornado.web.HTTPError(404) cached_uids[username] = uid return os.path.join(BASE_PATH, str(uid), 'public', path)
import tornado from tornado import gen import json import os BASE_PATH = '.' base_url = '/paws/public/' @gen.coroutine def uid_for_user(user): url = 'https://meta.wikimedia.org/w/api.php?' + \ 'action=query&meta=globaluserinfo' + \ '&format=json&formatversion=2' + \ '&guiuser={}'.format(user) client = tornado.httpclient.AsyncHTTPClient() resp = yield client.fetch(url) parsed = json.loads(resp.body.decode('utf-8')) if 'missing' in parsed['query']['globaluserinfo']: return None return parsed['query']['globaluserinfo']['id'] # These do not change, so let's cache them in memory cached_uids = {} @gen.coroutine def path_for_url_segment(url): """ Takes a URL segment and returns a full filesystem path Example: input: YuviPanda/Something.ipynb output: 43/public/Something.ipynb """ splits = url.split('/') username = splits[0] path = '/'.join(splits[1:]) if username in cached_uids: uid = cached_uids[username] else: uid = yield uid_for_user(username) if uid is None: raise tornado.web.HTTPError(404) cached_uids[username] = uid return os.path.join(BASE_PATH, str(uid), 'public', path)
Add clarifying(?) comment about uid caching
Add clarifying(?) comment about uid caching
Python
bsd-3-clause
yuvipanda/nbserve
--- +++ @@ -25,6 +25,7 @@ return parsed['query']['globaluserinfo']['id'] +# These do not change, so let's cache them in memory cached_uids = {}
20f67ed02cd31d88a897b6e7ac3c93c482ea1684
awslimits/data_setup.py
awslimits/data_setup.py
from .support import load_tickets, load_default_limits import settings def update_data(): print 'loading default limits...' load_default_limits() if settings.PREMIUM_ACCOUNT: print 'loading tickets...' load_tickets() print 'done' if __name__ == "__main__": update_data()
from .support import load_tickets, load_default_limits import settings def update_data(): print('loading default limits...') load_default_limits() if settings.PREMIUM_ACCOUNT: print('loading tickets...') load_tickets() print('done') if __name__ == "__main__": update_data()
Fix print statements for Python 3
Fix print statements for Python 3
Python
apache-2.0
spulec/awslimits,Yipit/awslimits,Yipit/awslimits,spulec/awslimits
--- +++ @@ -2,12 +2,12 @@ import settings def update_data(): - print 'loading default limits...' + print('loading default limits...') load_default_limits() if settings.PREMIUM_ACCOUNT: - print 'loading tickets...' + print('loading tickets...') load_tickets() - print 'done' + print('done') if __name__ == "__main__": update_data()
bd20dbda918cdec93ab6d1fe5bba0ce064a60103
fairseq/scoring/wer.py
fairseq/scoring/wer.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import editdistance from fairseq.scoring import register_scoring @register_scoring("wer") class WerScorer(object): def __init__(self, *unused): self.reset() def reset(self): self.distance = 0 self.target_length = 0 def add_string(self, ref, pred): pred_items = ref.split() targ_items = pred.split() self.distance += editdistance.eval(pred_items, targ_items) self.target_length += len(targ_items) def result_string(self): return f"WER: {self.score()}" def score(self): return ( 100.0 * self.distance / self.target_length if self.target_length > 0 else 0 )
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import editdistance from fairseq.scoring import register_scoring @register_scoring("wer") class WerScorer(object): def __init__(self, *unused): self.reset() def reset(self): self.distance = 0 self.ref_length = 0 def add_string(self, ref, pred): ref_items = ref.split() pred_items = pred.split() self.distance += editdistance.eval(ref_items, pred_items) self.ref_length += len(ref_items) def result_string(self): return f"WER: {self.score()}" def score(self): return ( 100.0 * self.distance / self.ref_length if self.ref_length > 0 else 0 )
Fix typos in WER scorer
Fix typos in WER scorer Summary: Fix typos in WER scorer - The typos lead to using prediction length as the denominator in the formula, which is wrong. Reviewed By: alexeib Differential Revision: D23139261 fbshipit-source-id: d1bba0044365813603ce358388e880c1b3f9ec6b
Python
mit
pytorch/fairseq,pytorch/fairseq,pytorch/fairseq
--- +++ @@ -15,18 +15,18 @@ def reset(self): self.distance = 0 - self.target_length = 0 + self.ref_length = 0 def add_string(self, ref, pred): - pred_items = ref.split() - targ_items = pred.split() - self.distance += editdistance.eval(pred_items, targ_items) - self.target_length += len(targ_items) + ref_items = ref.split() + pred_items = pred.split() + self.distance += editdistance.eval(ref_items, pred_items) + self.ref_length += len(ref_items) def result_string(self): return f"WER: {self.score()}" def score(self): return ( - 100.0 * self.distance / self.target_length if self.target_length > 0 else 0 + 100.0 * self.distance / self.ref_length if self.ref_length > 0 else 0 )
6a219ca1451be9a68b567288fbd014624cc2417b
murano/tests/unit/api/middleware/test_version_negotiation.py
murano/tests/unit/api/middleware/test_version_negotiation.py
# Copyright 2016 AT&T 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 webob from murano.api import versions from murano.api.middleware import version_negotiation from murano.tests.unit import base class MiddlewareVersionNegotiationTest(base.MuranoTestCase): def test_middleware_version_negotiation_default(self): middleware_vn = version_negotiation.VersionNegotiationFilter(None) request = webob.Request.blank('/environments') result = middleware_vn.process_request(request) self.assertTrue(isinstance(result, versions.Controller))
# Copyright 2016 AT&T 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 webob from murano.api import versions from murano.api.middleware import version_negotiation from murano.tests.unit import base class MiddlewareVersionNegotiationTest(base.MuranoTestCase): def test_middleware_version_negotiation_default(self): middleware_vn = version_negotiation.VersionNegotiationFilter(None) request = webob.Request.blank('/environments') result = middleware_vn.process_request(request) self.assertIsInstance(result, versions.Controller)
Change assertTrue(isinstance()) by optimal assert
Change assertTrue(isinstance()) by optimal assert Some of tests use different method of assertTrue(isinstance(A, B)) or assertEqual(type(A), B). The correct way is to use assertIsInstance(A, B) provided by testtools Change-Id: I3231db85708b36d2092c14ad45b42f42a0151027
Python
apache-2.0
openstack/murano,openstack/murano
--- +++ @@ -28,4 +28,4 @@ middleware_vn = version_negotiation.VersionNegotiationFilter(None) request = webob.Request.blank('/environments') result = middleware_vn.process_request(request) - self.assertTrue(isinstance(result, versions.Controller)) + self.assertIsInstance(result, versions.Controller)
7a7b42495fda7e7fabbf982e1194ea2fff6fdf15
code/DataSet.py
code/DataSet.py
# Neurotopics/code/DataSet.py import neurosynth.analysis.reduce as nsar class DataSet: """ A DataSet takes a NeuroSynth dataset and extracts the DOI's, and word subset of interest. It uses reduce.average_within_regions to get the average activation in the regions of interest (ROIs) of the img. """ def __init__(self, neurosynth_dataset, img, word_counts_file): self.word_subset = neurosynth_dataset.get_feature_names() self.dois = list(neurosynth_dataset.feature_table.ids) self.average_activation = nsar.average_within_regions(neurosynth_dataset, img) self.get_word_subset_counts(self.word_subset, word_counts_file) def get_word_subset_counts(self, word_subset, word_counts_file): pass
# Neurotopics/code/DataSet.py import neurosynth.analysis.reduce as nsar class DataSet: """ A DataSet takes a NeuroSynth dataset and extracts the DOI's, and word subset of interest. It uses reduce.average_within_regions to get the average activation in the regions of interest (ROIs) of the img. """ def __init__(self, neurosynth_dataset, image_file_name, word_counts_file): self.word_subset = neurosynth_dataset.get_feature_names() self.dois = list(neurosynth_dataset.feature_table.ids) self.average_activation = nsar.average_within_regions(neurosynth_dataset, image_file_name) self.get_word_subset_counts(self.word_subset, word_counts_file) def get_word_subset_counts(self, word_subset, word_counts_file): pass
Make more explicit variable name.
Make more explicit variable name.
Python
agpl-3.0
ambimorph/neurotopics-obs
--- +++ @@ -11,11 +11,11 @@ the img. """ - def __init__(self, neurosynth_dataset, img, word_counts_file): + def __init__(self, neurosynth_dataset, image_file_name, word_counts_file): self.word_subset = neurosynth_dataset.get_feature_names() self.dois = list(neurosynth_dataset.feature_table.ids) - self.average_activation = nsar.average_within_regions(neurosynth_dataset, img) + self.average_activation = nsar.average_within_regions(neurosynth_dataset, image_file_name) self.get_word_subset_counts(self.word_subset, word_counts_file) def get_word_subset_counts(self, word_subset, word_counts_file):
c47468128ab831133a12f942d32dd73b4198458e
scent.py
scent.py
# -*- coding: utf-8 -*- import os import time import subprocess from sniffer.api import select_runnable, file_validator, runnable try: from pync import Notifier except ImportError: notify = None else: notify = Notifier.notify watch_paths = ['demo/', 'tests/'] @select_runnable('python_tests') @file_validator def py_files(filename): return all((filename.endswith('.py'), not os.path.basename(filename).startswith('.'))) @runnable def python_tests(*args): group = int(time.time()) # unique per run for count, (command, title) in enumerate(( (('make', 'test-unit'), "Unit Tests"), (('make', 'test-int'), "Integration Tests"), (('make', 'test-all'), "Combined Tests"), ), start=1): failure = subprocess.call(command) if failure: if notify: mark = "❌" * count notify(mark + " [FAIL] " + mark, title=title, group=group) return False else: if notify: mark = "✅" * count notify(mark + " [PASS] " + mark, title=title, group=group) return True
# -*- coding: utf-8 -*- import os import time import subprocess from sniffer.api import select_runnable, file_validator, runnable try: from pync import Notifier except ImportError: notify = None else: notify = Notifier.notify watch_paths = ['demo/', 'tests/'] @select_runnable('python_tests') @file_validator def py_files(filename): return all((filename.endswith('.py'), not os.path.basename(filename).startswith('.'))) @runnable def python_tests(*args): group = int(time.time()) # unique per run for count, (command, title) in enumerate(( (('make', 'test-unit'), "Unit Tests"), (('make', 'test-int'), "Integration Tests"), (('make', 'test-all'), "Combined Tests"), (('make', 'check'), "Static Analysis"), (('make', 'doc'), None), ), start=1): failure = subprocess.call(command) if failure: if notify and title: mark = "❌" * count notify(mark + " [FAIL] " + mark, title=title, group=group) return False else: if notify and title: mark = "✅" * count notify(mark + " [PASS] " + mark, title=title, group=group) return True
Deploy Travis CI build 478 to GitHub
Deploy Travis CI build 478 to GitHub
Python
mit
jacebrowning/template-python-demo
--- +++ @@ -32,17 +32,19 @@ (('make', 'test-unit'), "Unit Tests"), (('make', 'test-int'), "Integration Tests"), (('make', 'test-all'), "Combined Tests"), + (('make', 'check'), "Static Analysis"), + (('make', 'doc'), None), ), start=1): failure = subprocess.call(command) if failure: - if notify: + if notify and title: mark = "❌" * count notify(mark + " [FAIL] " + mark, title=title, group=group) return False else: - if notify: + if notify and title: mark = "✅" * count notify(mark + " [PASS] " + mark, title=title, group=group)
cc80f90a4f003c0967c31d5177971061350ee683
pycall/call.py
pycall/call.py
"""A simple wrapper for Asterisk calls.""" class Call(object): """Stores and manipulates Asterisk calls.""" def __init__(self, channel, callerid=None, account=None, wait_time=None, max_retries=None): """Create a new `Call` object. :param str channel: The Asterisk channel to call. Should be in standard Asterisk format. :param str callerid: CallerID to use. :param str account: Account code to associate with this call. :param int wait_time: Amount of time to wait (in seconds) between retry attempts. :param int max_retries: Maximum amount of retry attempts. """ self.channel = channel self.callerid = callerid self.account = account self.wait_time = int(wait_time) self.max_retries = int(max_retries)
"""A simple wrapper for Asterisk calls.""" class Call(object): """Stores and manipulates Asterisk calls.""" def __init__(self, channel, callerid=None, account=None, wait_time=None, max_retries=None): """Create a new `Call` object. :param str channel: The Asterisk channel to call. Should be in standard Asterisk format. :param str callerid: CallerID to use. :param str account: Account code to associate with this call. :param int wait_time: Amount of time to wait (in seconds) between retry attempts. :param int max_retries: Maximum amount of retry attempts. """ self.channel = channel self.callerid = callerid self.account = account self.wait_time = wait_time self.max_retries = max_retries
Revert "Forcing type coersion for int params."
Revert "Forcing type coersion for int params." This is a pointless bit of code. Since we lazy-evaluate them anyhow, it's a duplicate effort. This reverts commit 1ca6b96d492f8f33ac3b3a520937378effb66744.
Python
unlicense
rdegges/pycall
--- +++ @@ -19,5 +19,5 @@ self.channel = channel self.callerid = callerid self.account = account - self.wait_time = int(wait_time) - self.max_retries = int(max_retries) + self.wait_time = wait_time + self.max_retries = max_retries
d3c585a0ad11a75c308c70954184a526033f0420
setup.py
setup.py
import sys from setuptools import setup, find_packages, Command from distutils import log setup( name='diffenator', version='0.0.2', author="Google Fonts Project Authors", description="Font regression tester for Google Fonts", url="https://github.com/googlefonts/diffenator", license="Apache Software License 2.0", package_dir={"": "Lib"}, packages=find_packages("Lib"), entry_points={ "console_scripts": [ "diffenator = diffenator.__main__:main", ], }, dependency_links=[ "git+https://github.com/googlei18n/nototools/tarball/master#egg=nototools-0.0.1", ], install_requires=[ "fonttools>=3.4.0", ], )
import sys from setuptools import setup, find_packages, Command from distutils import log setup( name='diffenator', version='0.0.2', author="Google Fonts Project Authors", description="Font regression tester for Google Fonts", url="https://github.com/googlefonts/diffenator", license="Apache Software License 2.0", package_dir={"": "Lib"}, packages=find_packages("Lib"), entry_points={ "console_scripts": [ "diffenator = diffenator.__main__:main", ], }, install_requires=[ "fonttools>=3.4.0", ], )
Remove dependency link to nototools
Remove dependency link to nototools
Python
apache-2.0
googlefonts/fontdiffenator,googlefonts/fontdiffenator
--- +++ @@ -16,9 +16,6 @@ "diffenator = diffenator.__main__:main", ], }, - dependency_links=[ - "git+https://github.com/googlei18n/nototools/tarball/master#egg=nototools-0.0.1", - ], install_requires=[ "fonttools>=3.4.0", ],
5250a31587f414f6673c13e42095dbb859bf8cb4
setup.py
setup.py
# Copyright 2013-2015 Massachusetts Open Cloud Contributors # # 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 setuptools import setup, find_packages setup(name='haas', version='0.2rc2', url='https://github.com/CCI-MOC/haas', packages=find_packages(), scripts=['scripts/haas', 'scripts/create_bridges'], install_requires=['SQLAlchemy==0.9.7', 'Werkzeug>=0.9.4,<0.10', 'Flask>=0.10.1,<0.11', 'schema==0.3.1', 'importlib==1.0.3', 'passlib==1.6.2', 'pexpect==3.3', 'requests==2.4.1', 'pytest>=2.6.2,<3.0', 'pytest-cov==1.8.0', 'pytest-xdist', ])
# Copyright 2013-2015 Massachusetts Open Cloud Contributors # # 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 setuptools import setup, find_packages setup(name='haas', version='0.2rc2', url='https://github.com/CCI-MOC/haas', packages=find_packages(), scripts=['scripts/haas', 'scripts/create_bridges'], install_requires=['Flask-SQLAlchemy', 'Werkzeug>=0.9.4,<0.10', 'Flask>=0.10.1,<0.11', 'schema==0.3.1', 'importlib==1.0.3', 'passlib==1.6.2', 'pexpect==3.3', 'requests==2.4.1', 'pytest>=2.6.2,<3.0', 'pytest-cov==1.8.0', 'pytest-xdist', ])
Replace dependency on SQLAlchemy with Flask-SQLALchemy
Replace dependency on SQLAlchemy with Flask-SQLALchemy
Python
apache-2.0
CCI-MOC/haas,kylehogan/haas,kylehogan/hil,henn/hil_sahil,henn/hil,henn/hil,kylehogan/hil,SahilTikale/haas,meng-sun/hil,henn/hil_sahil,meng-sun/hil,henn/haas
--- +++ @@ -19,7 +19,7 @@ url='https://github.com/CCI-MOC/haas', packages=find_packages(), scripts=['scripts/haas', 'scripts/create_bridges'], - install_requires=['SQLAlchemy==0.9.7', + install_requires=['Flask-SQLAlchemy', 'Werkzeug>=0.9.4,<0.10', 'Flask>=0.10.1,<0.11', 'schema==0.3.1',
475b89c2d4ce94bc208b610808916246e4e3a575
setup.py
setup.py
from setuptools import setup, Extension module1 = Extension('earl', sources = ['earl.cpp']) setup ( name = "Earl", version = "1.6", description = "Earl, the fanciest External Term Format packer and unpacker available for Python.", ext_modules = [module1], url="https://github.com/ccubed/Earl", author="Charles Click", author_email="CharlesClick@vertinext.com", license="MIT", keywords="Erlang ETF External Term Format" )
from setuptools import setup, Extension module1 = Extension('earl', sources = ['earl.cpp']) setup ( name = "Earl", version = "1.6.1", description = "Earl, the fanciest External Term Format packer and unpacker available for Python.", ext_modules = [module1], url="https://github.com/ccubed/Earl", author="Charles Click", author_email="CharlesClick@vertinext.com", license="MIT", keywords="Erlang ETF External Term Format" )
Update to 1.6.1. Small bug fix.
Update to 1.6.1. Small bug fix.
Python
mit
ccubed/Earl,ccubed/Earl
--- +++ @@ -4,7 +4,7 @@ setup ( name = "Earl", - version = "1.6", + version = "1.6.1", description = "Earl, the fanciest External Term Format packer and unpacker available for Python.", ext_modules = [module1], url="https://github.com/ccubed/Earl",
3daaf21879c6b2fc2099708e967cd4d67da1cd4f
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages __name__ == '__main__' and setup(name='aiohttp-json-rpc', version='0.10.1', author='Florian Scherf', url='https://github.com/pengutronix/aiohttp-json-rpc/', author_email='f.scherf@pengutronix.de', license='Apache 2.0', install_requires=['aiohttp>=3,<3.1'], python_requires='>=3.5', packages=find_packages(), zip_safe=False, entry_points={ 'pytest11': [ 'aiohttp-json-rpc = aiohttp_json_rpc.pytest', ] })
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages __name__ == '__main__' and setup(name='aiohttp-json-rpc', version='0.10.1', author='Florian Scherf', url='https://github.com/pengutronix/aiohttp-json-rpc/', author_email='f.scherf@pengutronix.de', license='Apache 2.0', install_requires=['aiohttp>=3,<3.4'], python_requires='>=3.5', packages=find_packages(), zip_safe=False, entry_points={ 'pytest11': [ 'aiohttp-json-rpc = aiohttp_json_rpc.pytest', ] })
Bump aiohttp version constraint to <3.4
Bump aiohttp version constraint to <3.4
Python
apache-2.0
pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc
--- +++ @@ -9,7 +9,7 @@ url='https://github.com/pengutronix/aiohttp-json-rpc/', author_email='f.scherf@pengutronix.de', license='Apache 2.0', - install_requires=['aiohttp>=3,<3.1'], + install_requires=['aiohttp>=3,<3.4'], python_requires='>=3.5', packages=find_packages(), zip_safe=False,
d7201be1fbd5659f60887572f18d103a3f71deaf
setup.py
setup.py
"""Setup for pyexperiment """ from __future__ import print_function # from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import os from setuptools import setup try: from pypandoc import convert read_md = lambda fname: convert(fname, 'rst') except ImportError: print("Warning: pypandoc module not found") read_md = lambda fname: open( os.path.join(os.path.dirname(__file__), fname), 'r').read() LONG_DESCRIPTION = 'Framework for easy and clean experiments with python.' if os.path.exists('README.md'): LONG_DESCRIPTION = read_md('README.md') setup( name="pyexperiment", version="0.1.15", author="Peter Duerr", author_email="duerrp@gmail.com", description="Run experiments with Python - quick and clean.", license="MIT", keywords="science experiment", url="https://github.com/duerrp/pyexperiment", download_url="https://github.com/duerrp/pyexperiment/tarball/0.1.15", packages=['pyexperiment', 'pyexperiment.conf', 'pyexperiment.state', 'pyexperiment.utils', 'pyexperiment.log', ], long_description=LONG_DESCRIPTION, classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: MIT License", ], )
"""Setup for pyexperiment """ from __future__ import print_function # from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import os from setuptools import setup try: from pypandoc import convert read_md = lambda fname: convert(fname, 'rst') except ImportError: print("Warning: pypandoc module not found") read_md = lambda fname: open( os.path.join(os.path.dirname(__file__), fname), 'r').read() LONG_DESCRIPTION = 'Framework for easy and clean experiments with python.' if os.path.exists('README.md'): LONG_DESCRIPTION = read_md('README.md') setup( name="pyexperiment", version="0.1.15-test", author="Peter Duerr", author_email="duerrp@gmail.com", description="Run experiments with Python - quick and clean.", license="MIT", keywords="science experiment", url="https://github.com/duerrp/pyexperiment", # download_url="https://github.com/duerrp/pyexperiment/tarball/0.1.15", packages=['pyexperiment', 'pyexperiment.conf', 'pyexperiment.state', 'pyexperiment.utils', 'pyexperiment.log', ], long_description=LONG_DESCRIPTION, classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: MIT License", ], )
Move to test version for pypi-test
Move to test version for pypi-test
Python
mit
DeercoderResearch/pyexperiment,shaunstanislaus/pyexperiment,duerrp/pyexperiment,kinverarity1/pyexperiment,duerrp/pyexperiment,shaunstanislaus/pyexperiment,shaunstanislaus/pyexperiment,DeercoderResearch/pyexperiment,DeercoderResearch/pyexperiment,kinverarity1/pyexperiment,shaunstanislaus/pyexperiment,kinverarity1/pyexperiment,kinverarity1/pyexperiment,duerrp/pyexperiment,DeercoderResearch/pyexperiment
--- +++ @@ -22,14 +22,14 @@ setup( name="pyexperiment", - version="0.1.15", + version="0.1.15-test", author="Peter Duerr", author_email="duerrp@gmail.com", description="Run experiments with Python - quick and clean.", license="MIT", keywords="science experiment", url="https://github.com/duerrp/pyexperiment", - download_url="https://github.com/duerrp/pyexperiment/tarball/0.1.15", + # download_url="https://github.com/duerrp/pyexperiment/tarball/0.1.15", packages=['pyexperiment', 'pyexperiment.conf', 'pyexperiment.state',
70377c4397680c32b9ee6958bd250dce697fcb62
setup.py
setup.py
from setuptools import setup, find_packages install_requires = [ 'dill==0.2.5', 'easydict==1.6', 'h5py==2.6.0', 'jsonpickle==0.9.3', 'Keras==1.2.0', 'nflgame==1.2.20', 'numpy==1.11.2', 'pandas==0.19.1', 'scikit-learn==0.18.1', 'scipy==0.18.1', 'tensorflow==0.12.0rc1', 'Theano==0.8.2', ] with open('README.md', 'r') as f: readme = f.read() setup( name="wincast", version='0.0.1', url='https://github.com/kahnjw/wincast', author_email='thomas.welfley+djproxy@gmail.com', long_description=readme, license='MIT', packages=find_packages(exclude=['tests', 'tests.*']), install_requires=install_requires, data_files=[ ('', ['models/wincast.model.h5', 'models/wincast.scaler.pkl']), ('', ['data/Xy.csv']) ] )
from setuptools import setup, find_packages install_requires = [ 'dill==0.2.5', 'easydict==1.6', 'h5py==2.6.0', 'jsonpickle==0.9.3', 'Keras==1.2.0', 'nflgame==1.2.20', 'numpy==1.11.2', 'pandas==0.19.1', 'scikit-learn==0.18.1', 'scipy==0.18.1', 'tensorflow==0.12.0rc1', 'Theano==0.8.2', ] with open('README.md', 'r') as f: readme = f.read() setup( name="wincast", version='0.0.1', url='https://github.com/kahnjw/wincast', author_email='thomas.welfley+djproxy@gmail.com', long_description=readme, license='MIT', packages=find_packages(exclude=['tests', 'tests.*']), install_requires=install_requires, data_files=[ ('models', ['models/wincast.model.h5', 'models/wincast.scaler.pkl']), ('data', ['data/Xy.csv']) ] )
Add back models and data
Add back models and data
Python
mit
kahnjw/wincast
--- +++ @@ -29,7 +29,7 @@ packages=find_packages(exclude=['tests', 'tests.*']), install_requires=install_requires, data_files=[ - ('', ['models/wincast.model.h5', 'models/wincast.scaler.pkl']), - ('', ['data/Xy.csv']) + ('models', ['models/wincast.model.h5', 'models/wincast.scaler.pkl']), + ('data', ['data/Xy.csv']) ] )
739860d8da3e3380e49283a1fca2c43750349909
setup.py
setup.py
from setuptools import setup import mikla setup( name='mikla', version=mikla.__version__.strip(), url='http://dirtymonkey.co.uk/mikla', license='MIT', author=mikla.__author__.strip(), author_email='matt@dirtymonkey.co.uk', description=mikla.__doc__.strip().replace('\n', ' '), long_description=open('README.rst').read(), keywords='encryption security gnupg gpg', packages=['mikla'], include_package_data=True, entry_points={ 'console_scripts': [ 'mikla = mikla.main:main', ], }, install_requires=[ 'docopt>=0.6.2', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Operating System :: POSIX :: BSD', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Security :: Cryptography', 'Topic :: Communications', 'Topic :: Utilities', ], )
from __future__ import print_function import sys from setuptools import setup if sys.version_info[:2] < (3, 5): print('Mikla only runs on Python 3.5 or later', file=sys.stderr) sys.exit(1) import mikla setup( name='mikla', version=mikla.__version__.strip(), url='http://dirtymonkey.co.uk/mikla', license='MIT', author=mikla.__author__.strip(), author_email='matt@dirtymonkey.co.uk', description=mikla.__doc__.strip().replace('\n', ' '), long_description=open('README.rst').read(), keywords='encryption security gnupg gpg', packages=['mikla'], include_package_data=True, entry_points={ 'console_scripts': [ 'mikla = mikla.main:main', ], }, install_requires=[ 'docopt>=0.6.2', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Operating System :: POSIX :: BSD', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Security :: Cryptography', 'Topic :: Communications', 'Topic :: Utilities', ], )
Add helpful message for users trying to install with Python < 3.5
Add helpful message for users trying to install with Python < 3.5
Python
mit
Matt-Deacalion/Mikla
--- +++ @@ -1,6 +1,15 @@ +from __future__ import print_function + +import sys + from setuptools import setup +if sys.version_info[:2] < (3, 5): + print('Mikla only runs on Python 3.5 or later', file=sys.stderr) + sys.exit(1) + import mikla + setup( name='mikla',
bc6d4f060b36418d7dc57ee4068e705b9bd28678
setup.py
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup from setuptools import find_packages with open('README.rst', 'rb') as readme: readme_text = readme.read().decode('utf-8') setup( name='django-bootstrap-pagination', version='1.6.0', keywords="django bootstrap pagination templatetag", author=u'Jason McClellan', author_email='jason@jasonmccllelan.net', packages=find_packages(), url='https://github.com/jmcclell/django-bootstrap-pagination', license='MIT licence, see LICENCE', description='Render Django Page objects as Bootstrap 3.x Pagination compatible HTML', long_description=readme_text, zip_safe=False, include_package_data=True, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Framework :: Django", "Framework :: Django :: 1.4", "Framework :: Django :: 1.5", "Framework :: Django :: 1.6", "Framework :: Django :: 1.7", "Framework :: Django :: 1.8", "Framework :: Django :: 1.9", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ] )
# -*- coding: utf-8 -*- from distutils.core import setup from setuptools import find_packages with open('README.rst', 'rb') as readme: readme_text = readme.read().decode('utf-8') setup( name='django-bootstrap-pagination', version='1.6.1', keywords="django bootstrap pagination templatetag", author=u'Jason McClellan', author_email='jason@jasonmccllelan.net', packages=find_packages(), url='https://github.com/jmcclell/django-bootstrap-pagination', license='MIT licence, see LICENCE', description='Render Django Page objects as Bootstrap 3.x Pagination compatible HTML', long_description=readme_text, zip_safe=False, include_package_data=True, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Framework :: Django", "Framework :: Django :: 1.4", "Framework :: Django :: 1.5", "Framework :: Django :: 1.6", "Framework :: Django :: 1.7", "Framework :: Django :: 1.8", "Framework :: Django :: 1.9", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ] )
Prepare for 1.6.1 on pypi
Prepare for 1.6.1 on pypi
Python
mit
jmcclell/django-bootstrap-pagination,jmcclell/django-bootstrap-pagination
--- +++ @@ -8,7 +8,7 @@ setup( name='django-bootstrap-pagination', - version='1.6.0', + version='1.6.1', keywords="django bootstrap pagination templatetag", author=u'Jason McClellan', author_email='jason@jasonmccllelan.net',
413d9304b5ff0a45e70512dadc4527843eee7b68
setup.py
setup.py
import sys from setuptools import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' setup( name='raygun4py', version='2.0.0', packages=['raygun4py'], package_dir= { "raygun4py": base_dir + "/raygun4py" }, license='LICENSE', url='http://raygun.io', author='Mindscape', author_email='contact@mindscape.co.nz', long_description=open('README.rst').read(), install_requires=[ "jsonpickle == 0.7.0" ], )
import sys from setuptools import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' setup( name='raygun4py', version='2.0.0', packages=['raygun4py'], package_dir= { "raygun4py": base_dir + "/raygun4py" }, license='LICENSE', url='http://raygun.io', author='Mindscape', author_email='contact@mindscape.co.nz', long_description=open('README.rst').read(), install_requires=[ "jsonpickle == 0.7.0" ],classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Communications', ], )
Add classifiers with py ver info
Add classifiers with py ver info
Python
mit
ferringb/raygun4py,MindscapeHQ/raygun4py,Osmose/raygun4py
--- +++ @@ -20,5 +20,19 @@ long_description=open('README.rst').read(), install_requires=[ "jsonpickle == 0.7.0" + ],classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.1', + 'Programming Language :: Python :: 3.2', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Topic :: Communications', ], )
b1bfb600240a006eed0cfce19d3fc87b3c72669f
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup setup( name = 'jargparse', packages = ['jargparse'], # this must be the same as the name above version = '0.0.3', description = 'A tiny super-dumb python module just because I like to see the usage info on stdout on an error', author = 'Justin Clark-Casey', author_email = 'justincc@justincc.org', url = 'https://github.com/justinccdev/jargparse', # use the URL to the github repo keywords = ['logging'], # arbitrary keywords )
#!/usr/bin/env python from distutils.core import setup setup( name = 'jargparse', packages = ['jargparse'], # this must be the same as the name above version = '0.0.4', description = 'A tiny super-dumb module just because I like to see the usage info on stdout on an error. jargparse.ArgParser just wraps argparse.ArgParser', author = 'Justin Clark-Casey', author_email = 'justincc@justincc.org', url = 'https://github.com/justinccdev/jargparse', # use the URL to the github repo keywords = ['logging'], # arbitrary keywords )
Add a bit more to description
Add a bit more to description
Python
apache-2.0
justinccdev/jargparse
--- +++ @@ -4,8 +4,8 @@ setup( name = 'jargparse', packages = ['jargparse'], # this must be the same as the name above - version = '0.0.3', - description = 'A tiny super-dumb python module just because I like to see the usage info on stdout on an error', + version = '0.0.4', + description = 'A tiny super-dumb module just because I like to see the usage info on stdout on an error. jargparse.ArgParser just wraps argparse.ArgParser', author = 'Justin Clark-Casey', author_email = 'justincc@justincc.org', url = 'https://github.com/justinccdev/jargparse', # use the URL to the github repo
1fea3970bd6979834f17e1a01bd204f60e4361ba
setup.py
setup.py
#!/usr/bin/env python import setuptools import os setuptools.setup( name='endpoints-proto-datastore', version='0.9.0', description='Google Cloud Endpoints Proto Datastore Library', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), url='https://github.com/GoogleCloudPlatform/endpoints-proto-datastore', license='Apache', author='Danny Hermes', author_email='daniel.j.hermes@gmail.com', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python' ], packages=setuptools.find_packages(exclude=['examples*', 'docs*']), )
#!/usr/bin/env python import setuptools import os setuptools.setup( name='endpoints-proto-datastore', version='0.9.0', description='Google Cloud Endpoints Proto Datastore Library', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(), url='https://github.com/GoogleCloudPlatform/endpoints-proto-datastore', license='Apache', author='Danny Hermes', author_email='daniel.j.hermes@gmail.com', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python' ], packages=setuptools.find_packages(exclude=['examples*', 'docs*']), )
Add trailing newline since PyCharm stripped it
Add trailing newline since PyCharm stripped it
Python
apache-2.0
jbergant/endpoints-proto-datastore,dhermes/endpoints-proto-datastore,GoogleCloudPlatform/endpoints-proto-datastore,mnieper/endpoints-proto-datastore,maxandron/endpoints-proto-datastore
--- +++ @@ -21,3 +21,4 @@ ], packages=setuptools.find_packages(exclude=['examples*', 'docs*']), ) +
6d702526d04fab65ee62bcec7db668d65f9de97f
setup.py
setup.py
from setuptools import setup import jasinja, sys requires = ['Jinja2'] if sys.version_info < (2, 6): requires += ['simplejson'] setup( name='jasinja', version=jasinja.__version__, url='http://bitbucket.org/djc/jasinja', license='BSD', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='A JavaScript code generator for Jinja templates', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=['jasinja', 'jasinja.tests'], package_data={ 'jasinja': ['*.js'] }, install_requires=requires, test_suite='jasinja.tests.run.suite', test_requires=['python-spidermonkey'], entry_points={ 'console_scripts': ['jasinja-compile = jasinja.compile:main'], }, )
from setuptools import setup import jasinja, sys requires = ['Jinja2'] if sys.version_info < (2, 6): requires += ['simplejson'] setup( name='jasinja', version=jasinja.__version__, url='http://bitbucket.org/djc/jasinja', license='BSD', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='A JavaScript code generator for Jinja templates', long_description=open('README.txt').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=['jasinja', 'jasinja.tests'], package_data={ 'jasinja': ['*.js'] }, install_requires=requires, test_suite='jasinja.tests.run.suite', test_requires=['python-spidermonkey'], entry_points={ 'console_scripts': ['jasinja-compile = jasinja.compile:main'], }, )
Add long description (from README).
Add long description (from README).
Python
bsd-3-clause
djc/jasinja,djc/jasinja
--- +++ @@ -13,6 +13,7 @@ author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='A JavaScript code generator for Jinja templates', + long_description=open('README.txt').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment',
1fe7b9c3c9a3764a1e209b2699ef51b84c87e897
setup.py
setup.py
from distutils.core import setup import os setup( name='python-jambel', version='0.1', py_module=['jambel'], url='http://github.com/jambit/python-jambel', license='UNKNOWN', author='Sebastian Rahlf', author_email='sebastian.rahlf@jambit.com', description="Interface to jambit's project traffic lights.", long_description=open(os.path.join(os.path.dirname(__file__), 'README.txt')).read(), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: Other/Proprietary License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ] )
from distutils.core import setup import os setup( name='python-jambel', version='0.1', py_module=['jambel'], url='http://github.com/jambit/python-jambel', license='UNKNOWN', author='Sebastian Rahlf', author_email='sebastian.rahlf@jambit.com', description="Interface to jambit's project traffic lights.", long_description=open(os.path.join(os.path.dirname(__file__), 'README.txt')).read(), test_requires=['pytest'], entry_points={ 'console_scripts': [ 'jambel = jambel:main', ] }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: Other/Proprietary License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ] )
Add console script and test requirements.
Add console script and test requirements.
Python
mit
redtoad/python-jambel,jambit/python-jambel
--- +++ @@ -11,6 +11,12 @@ author_email='sebastian.rahlf@jambit.com', description="Interface to jambit's project traffic lights.", long_description=open(os.path.join(os.path.dirname(__file__), 'README.txt')).read(), + test_requires=['pytest'], + entry_points={ + 'console_scripts': [ + 'jambel = jambel:main', + ] + }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers',
6ca66af32e522e897495a1fbe1748caec37da9bf
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2008 Jason Davies # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = 'CouchDB-FUSE', version = '0.1', description = 'CouchDB FUSE module', long_description = \ """This is a Python FUSE module for CouchDB. It allows CouchDB document attachments to be mounted on a virtual filesystem and edited directly.""", author = 'Jason Davies', author_email = 'jason@jasondavies.com', license = 'BSD', url = 'http://code.google.com/p/couchdb-fuse/', zip_safe = True, classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Database :: Front-Ends', ], packages = ['couchdbfuse'], entry_points = { 'console_scripts': [ 'couchmount = couchdbfuse:main', ], }, install_requires = ['CouchDB>=0.5', 'fuse-python>=0.2'], )
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2008 Jason Davies # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = 'CouchDB-FUSE', version = '0.1', description = 'CouchDB FUSE module', long_description = \ """This is a Python FUSE module for CouchDB. It allows CouchDB document attachments to be mounted on a virtual filesystem and edited directly.""", author = 'Jason Davies', author_email = 'jason@jasondavies.com', license = 'BSD', url = 'http://code.google.com/p/couchdb-fuse/', zip_safe = True, classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Database :: Front-Ends', ], packages = ['couchdbfuse'], entry_points = { 'console_scripts': [ 'couchmount = couchdbfuse:main', ], }, install_requires = ['CouchDB>=0.5'], )
Revert previous commit as fuse-python doesn't seem to play nicely with easy_install (at least on Ubuntu).
Revert previous commit as fuse-python doesn't seem to play nicely with easy_install (at least on Ubuntu).
Python
bsd-3-clause
johnko/couchdb-fuse
--- +++ @@ -41,5 +41,5 @@ ], }, - install_requires = ['CouchDB>=0.5', 'fuse-python>=0.2'], + install_requires = ['CouchDB>=0.5'], )
8b874d83e3840e1e67e2cd81c18fe0b415130619
setup.py
setup.py
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup setup(name='chevron', version='0.7.1', license='MIT', description='Mustache templating language renderer', author='noah morrison', author_email='noah@morrison.ph', url='https://github.com/noahmorrison/chevron', packages=['chevron'], entry_points={ 'console_scripts': ['chevron=chevron:cli_main'] }, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Text Processing :: Markup' ] )
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup import pypandoc readme = pypandoc.convert('README.md', 'rst') setup(name='chevron', version='0.7.1', license='MIT', description='Mustache templating language renderer', long_description=readme, author='noah morrison', author_email='noah@morrison.ph', url='https://github.com/noahmorrison/chevron', packages=['chevron'], entry_points={ 'console_scripts': ['chevron=chevron:cli_main'] }, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Text Processing :: Markup' ] )
Convert README.md to rst for pypi using pandoc.
Convert README.md to rst for pypi using pandoc. Closes #11 Thanks for the tips/help Marc :)
Python
mit
noahmorrison/chevron,noahmorrison/chevron
--- +++ @@ -5,10 +5,14 @@ except ImportError: from distutils.core import setup +import pypandoc +readme = pypandoc.convert('README.md', 'rst') + setup(name='chevron', version='0.7.1', license='MIT', description='Mustache templating language renderer', + long_description=readme, author='noah morrison', author_email='noah@morrison.ph', url='https://github.com/noahmorrison/chevron',
c65d11f82b6d33d4940cdfd7b4d6b81e083c6e34
setup.py
setup.py
from distutils.core import setup setup( name='django_autologin', version='0.1', packages=['django_autologin', 'django_autologin.templatetags'], install_requires=['django>=1.0'], description='Token generator and processor to provide automatic login links for users' )
from distutils.core import setup setup( name='django_autologin', version='0.1', packages=['django_autologin', 'django_autologin.templatetags'], install_requires=['django>=1.0'], description='Token generator and processor to provide automatic login links for users' )
Use 4 spaces for indentation.
Use 4 spaces for indentation.
Python
bsd-3-clause
playfire/django-autologin
--- +++ @@ -1,8 +1,8 @@ from distutils.core import setup setup( - name='django_autologin', - version='0.1', - packages=['django_autologin', 'django_autologin.templatetags'], - install_requires=['django>=1.0'], - description='Token generator and processor to provide automatic login links for users' + name='django_autologin', + version='0.1', + packages=['django_autologin', 'django_autologin.templatetags'], + install_requires=['django>=1.0'], + description='Token generator and processor to provide automatic login links for users' )
2cbc3a5197694905606ce5251516c825b28927d7
setup.py
setup.py
import os from setuptools import setup longDesc = "" if os.path.exists("README.rst"): longDesc = open("README.rst").read().strip() setup( name = "pytesseract", version = "0.1.7", author = "Samuel Hoffstaetter", author_email="pytesseract@madmaze.net", maintainer = "Matthias Lee", maintainer_email = "pytesseract@madmaze.net", description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"), long_description = longDesc, license = "GPLv3", keywords = "python-tesseract OCR Python", url = "https://github.com/madmaze/python-tesseract", packages=['pytesseract'], package_dir={'pytesseract': 'src'}, package_data = {'pytesseract': ['*.png','*.jpg']}, entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']}, classifiers = [ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ] )
import os from setuptools import setup README_PATH = 'README.rst' longDesc = "" if os.path.exists(README_PATH): with open(README_PATH) as readme: longDesc = readme.read() setup( name = "pytesseract", version = "0.1.7", author = "Samuel Hoffstaetter", author_email="pytesseract@madmaze.net", maintainer = "Matthias Lee", maintainer_email = "pytesseract@madmaze.net", description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"), long_description = longDesc, license = "GPLv3", keywords = "python-tesseract OCR Python", url = "https://github.com/madmaze/python-tesseract", packages=['pytesseract'], package_dir={'pytesseract': 'src'}, package_data = {'pytesseract': ['*.png','*.jpg']}, entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']}, classifiers = [ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ] )
Fix long_description loading for PyPI
Fix long_description loading for PyPI
Python
apache-2.0
madmaze/pytesseract
--- +++ @@ -2,9 +2,11 @@ from setuptools import setup +README_PATH = 'README.rst' longDesc = "" -if os.path.exists("README.rst"): - longDesc = open("README.rst").read().strip() +if os.path.exists(README_PATH): + with open(README_PATH) as readme: + longDesc = readme.read() setup( name = "pytesseract",
13494098e2941ff87d80710ecc00c35142851175
setup.py
setup.py
#!/usr/bin/env python # Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT import setuptools setuptools.setup( setup_requires=['pbr'], pbr=True)
#!/usr/bin/env python # Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT import setuptools, sys if sys.version_info < (2, 7): sys.exit('Sorry, Python < 2.7 is not supported for' ' python-swiftclient>=3.0') setuptools.setup( setup_requires=['pbr'], pbr=True)
Add python version constraint python>=2.7
Add python version constraint python>=2.7 The 'swift' command from v3.0.0 does not work in Python 2.6, bacause some code is incompatible with Python 2.6 This patch is to add a constraint of python version Change-Id: I5197cba0c2cd3135d08498df827a52f8bba98d4d Closes-bug: #1590334
Python
apache-2.0
openstack/python-swiftclient,openstack/python-swiftclient,sohonetlabs/python-swiftclient,sohonetlabs/python-swiftclient
--- +++ @@ -15,7 +15,11 @@ # limitations under the License. # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT -import setuptools +import setuptools, sys + +if sys.version_info < (2, 7): + sys.exit('Sorry, Python < 2.7 is not supported for' + ' python-swiftclient>=3.0') setuptools.setup( setup_requires=['pbr'],
23d7418aa18f6e4ce1b97938144a8968e2b0cb9b
setup.py
setup.py
#!/usr/bin/env python """Setup script for the pyparsing module distribution.""" # Setuptools depends on pyparsing (via packaging) as of version 34, so allow # installing without it to avoid bootstrap problems. try: from setuptools import setup except ImportError: from distutils.core import setup import sys import os from pyparsing import __version__ as pyparsing_version modules = ["pyparsing",] setup(# Distribution meta-data name = "pyparsing", version = pyparsing_version, description = "Python parsing module", author = "Paul McGuire", author_email = "ptmcg@users.sourceforge.net", url = "https://github.com/pyparsing/pyparsing/", download_url = "https://pypi.org/project/pyparsing/", license = "MIT License", py_modules = modules, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ] )
#!/usr/bin/env python """Setup script for the pyparsing module distribution.""" # Setuptools depends on pyparsing (via packaging) as of version 34, so allow # installing without it to avoid bootstrap problems. try: from setuptools import setup except ImportError: from distutils.core import setup import sys import os from pyparsing import __version__ as pyparsing_version modules = ["pyparsing",] setup(# Distribution meta-data name = "pyparsing", version = pyparsing_version, description = "Python parsing module", author = "Paul McGuire", author_email = "ptmcg@users.sourceforge.net", url = "https://github.com/pyparsing/pyparsing/", download_url = "https://pypi.org/project/pyparsing/", license = "MIT License", py_modules = modules, python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ] )
Add python_requires to help pip
Add python_requires to help pip
Python
mit
pyparsing/pyparsing,pyparsing/pyparsing
--- +++ @@ -26,6 +26,7 @@ download_url = "https://pypi.org/project/pyparsing/", license = "MIT License", py_modules = modules, + python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers',
a71c9ef43b1801343bccbaf4e9f3a4a2eaa570f0
setup.py
setup.py
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.2.0dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv'), os.path.join('oedb', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1, < 0.25', 'requests < 3.0'], extras_require={ 'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat', 'numpy']})
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.2.0dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv'), os.path.join('oedb', '*.csv')]}, long_description=read('README.rst'), long_description_content_type='text/x-rst', zip_safe=False, install_requires=['pandas >= 0.19.1, < 0.25', 'requests < 3.0'], extras_require={ 'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat', 'numpy']})
Add content type for long description
Add content type for long description
Python
mit
wind-python/windpowerlib
--- +++ @@ -18,6 +18,7 @@ 'windpowerlib': [os.path.join('data', '*.csv'), os.path.join('oedb', '*.csv')]}, long_description=read('README.rst'), + long_description_content_type='text/x-rst', zip_safe=False, install_requires=['pandas >= 0.19.1, < 0.25', 'requests < 3.0'],
269b3951049255fd3b459ce254afe3b8d6ffea1b
setup.py
setup.py
"""Setup for drewtils project.""" import os try: from setuptools import setup setupTools = True except ImportError: from distutils.core import setup setupTools = False _classifiers = [ 'License :: OSI Approved :: MIT License', ] if os.path.exists('README.rst'): with open('README.rst') as readme: long_description = readme.read() else: long_description = '' setupArgs = { 'name': 'drewtils', 'version': "0.1.9", 'packages': ['drewtils'], 'author': 'Andrew Johnson', 'author_email': 'drewej@protonmail.com', 'description': 'Simple tools to make testing and file parsing easier', 'long_description': long_description, 'license': 'MIT', 'keywords': 'parsing files', 'url': 'https://github.com/drewejohnson/drewtils', 'classifiers': _classifiers, } if setupTools: setupArgs.update(**{ 'test_suite': 'drewtils.tests', 'python_requires': '>=2.7,!=3.1,!=3.2,!=3.3,!=3.4' }) setup(**setupArgs)
"""Setup for drewtils project.""" try: from setuptools import setup setupTools = True except ImportError: from distutils.core import setup setupTools = False _classifiers = [ 'License :: OSI Approved :: MIT License', ] with open('README.rst') as readme: long_description = readme.read() setupArgs = { 'name': 'drewtils', 'version': "0.1.9", 'packages': ['drewtils'], 'author': 'Andrew Johnson', 'author_email': 'drewej@protonmail.com', 'description': 'Simple tools to make testing and file parsing easier', 'long_description': long_description, 'license': 'MIT', 'keywords': 'parsing files', 'url': 'https://github.com/drewejohnson/drewtils', 'classifiers': _classifiers, } if setupTools: setupArgs.update(**{ 'test_suite': 'drewtils.tests', 'python_requires': '>=2.7,!=3.1,!=3.2,!=3.3,!=3.4' }) setup(**setupArgs)
Read long description from readme always
Read long description from readme always
Python
mit
drewejohnson/drewtils
--- +++ @@ -1,6 +1,4 @@ """Setup for drewtils project.""" - -import os try: from setuptools import setup @@ -13,11 +11,8 @@ 'License :: OSI Approved :: MIT License', ] -if os.path.exists('README.rst'): - with open('README.rst') as readme: - long_description = readme.read() -else: - long_description = '' +with open('README.rst') as readme: + long_description = readme.read() setupArgs = { 'name': 'drewtils',
0578b55f4e1e62b7c5c9c6f62721576970f43fdd
setup.py
setup.py
#!/usr/bin/env python # # Setup script for Django Evolution from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test from django_evolution import get_package_version, VERSION def run_tests(*args): import os os.system('tests/runtests.py') test.run_tests = run_tests PACKAGE_NAME = 'django_evolution' download_url = ( 'http://downloads.reviewboard.org/releases/django-evolution/%s.%s/' % (VERSION[0], VERSION[1])) # Build the package setup( name=PACKAGE_NAME, version=get_package_version(), description='A database schema evolution tool for the Django web framework.', url='http://code.google.com/p/django-evolution/', author='Ben Khoo', author_email='khoobks@westnet.com.au', maintainer='Christian Hammond', maintainer_email='christian@beanbaginc.com', download_url=download_url, packages=find_packages(exclude=['tests']), install_requires=[ 'Django>=1.4.10', ], include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
#!/usr/bin/env python # # Setup script for Django Evolution from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test from django_evolution import get_package_version, VERSION def run_tests(*args): import os os.system('tests/runtests.py') test.run_tests = run_tests PACKAGE_NAME = 'django_evolution' download_url = ( 'http://downloads.reviewboard.org/releases/django-evolution/%s.%s/' % (VERSION[0], VERSION[1])) # Build the package setup( name=PACKAGE_NAME, version=get_package_version(), description='A database schema evolution tool for the Django web framework.', url='http://code.google.com/p/django-evolution/', author='Ben Khoo', author_email='khoobks@westnet.com.au', maintainer='Christian Hammond', maintainer_email='christian@beanbaginc.com', download_url=download_url, packages=find_packages(exclude=['tests']), install_requires=[ 'Django>=1.4.10,<1.7.0', ], include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Revert "Allow Django Evolution to install along with Django >= 1.7."
Revert "Allow Django Evolution to install along with Django >= 1.7." This reverts commit 28b280bb04f806f614f6f2cd25ce779b551fef9e. This was committed to the wrong branch.
Python
bsd-3-clause
beanbaginc/django-evolution
--- +++ @@ -38,7 +38,7 @@ download_url=download_url, packages=find_packages(exclude=['tests']), install_requires=[ - 'Django>=1.4.10', + 'Django>=1.4.10,<1.7.0', ], include_package_data=True, classifiers=[
c55b69aec422a28429f759893bfc1e1bd7352a59
setup.py
setup.py
#!/usr/bin/env python import sys from setuptools import setup, find_packages import versioneer versioneer.versionfile_source = 'obfsproxy/_version.py' versioneer.versionfile_build = 'obfsproxy/_version.py' versioneer.tag_prefix = 'obfsproxy-' # tags are like 1.2.0 versioneer.parentdir_prefix = 'obfsproxy-' # dirname like 'myproject-1.2.0' setup( name = "obfsproxy", author = "asn", author_email = "asn@torproject.org", description = ("A pluggable transport proxy written in Python"), license = "BSD", keywords = ['tor', 'obfuscation', 'twisted'], version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), packages = find_packages(), entry_points = { 'console_scripts': [ 'obfsproxy = obfsproxy.pyobfsproxy:run' ] }, install_requires = [ 'setuptools', 'PyCrypto', 'Twisted', 'argparse', 'pyptlib >= 0.0.5', 'gmpy' ], )
#!/usr/bin/env python import sys from setuptools import setup, find_packages import versioneer versioneer.versionfile_source = 'obfsproxy/_version.py' versioneer.versionfile_build = 'obfsproxy/_version.py' versioneer.tag_prefix = 'obfsproxy-' # tags are like 1.2.0 versioneer.parentdir_prefix = 'obfsproxy-' # dirname like 'myproject-1.2.0' setup( name = "obfsproxy", author = "asn", author_email = "asn@torproject.org", description = ("A pluggable transport proxy written in Python"), license = "BSD", keywords = ['tor', 'obfuscation', 'twisted'], version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), packages = find_packages(), entry_points = { 'console_scripts': [ 'obfsproxy = obfsproxy.pyobfsproxy:run' ] }, install_requires = [ 'setuptools', 'PyCrypto', 'Twisted', 'argparse', 'pyptlib >= 0.0.5', 'gmpy', 'pyyaml' ], )
Add "pyyaml" because it is used by ScrambleSuit.
Add "pyyaml" because it is used by ScrambleSuit.
Python
bsd-3-clause
isislovecruft/obfsproxy,masterkorp/obfsproxy,qdzheng/obfsproxy,infinity0/obfsproxy,catinred2/obfsproxy,Yawning/obfsproxy,david415/obfsproxy,Yawning/obfsproxy-wfpadtools,NullHypothesis/obfsproxy
--- +++ @@ -34,6 +34,7 @@ 'Twisted', 'argparse', 'pyptlib >= 0.0.5', - 'gmpy' + 'gmpy', + 'pyyaml' ], )
5b7685131030249cd1a6213eca8134e782e8d12d
setup.py
setup.py
import sys try: from setuptools import setup except ImportError: from distutils.core import setup requirements = [req.strip() for req in open('requirements.pip')] setup( name = 'leaderboard', version = "2.0.0", author = 'David Czarnecki', author_email = "dczarnecki@agoragames.com", packages = ['leaderboard'], install_requires = requirements, url = 'https://github.com/agoragames/leaderboard-python', license = "LICENSE.txt", description = 'Leaderboards backed by Redis in Python', long_description = open('README.md').read(), keywords = ['python', 'redis', 'leaderboard'], classifiers = [ 'Development Status :: 1 - Production', 'License :: OSI Approved :: MIT License', "Intended Audience :: Developers", "Operating System :: POSIX", "Topic :: Communications", "Topic :: System :: Distributed Computing", "Topic :: Software Development :: Libraries :: Python Modules", 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries' ] )
import sys try: from setuptools import setup except ImportError: from distutils.core import setup requirements = [req.strip() for req in open('requirements.pip')] setup( name = 'leaderboard', version = "2.0.0", author = 'David Czarnecki', author_email = "dczarnecki@agoragames.com", packages = ['leaderboard'], install_requires = requirements, url = 'https://github.com/agoragames/leaderboard-python', license = "LICENSE.txt", description = 'Leaderboards backed by Redis in Python', long_description = open('README.md').read(), keywords = ['python', 'redis', 'leaderboard'], classifiers = [ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', "Intended Audience :: Developers", "Operating System :: POSIX", "Topic :: Communications", "Topic :: System :: Distributed Computing", "Topic :: Software Development :: Libraries :: Python Modules", 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries' ] )
Use the correct classifier for production
Use the correct classifier for production
Python
mit
agoragames/leaderboard-python,SixMinute/leaderboard-python
--- +++ @@ -20,7 +20,7 @@ long_description = open('README.md').read(), keywords = ['python', 'redis', 'leaderboard'], classifiers = [ - 'Development Status :: 1 - Production', + 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', "Intended Audience :: Developers", "Operating System :: POSIX",
e889c0420a0770d2be633af5ad2b20fb27e0d05c
setup.py
setup.py
import codecs from setuptools import find_packages, setup import digestive setup( name='digestive', version=digestive.__version__, url='https://github.com/akaIDIOT/Digestive', packages=find_packages(), description='TODO', author='Mattijs Ugen', author_email=codecs.encode('nxnvqvbg@hfref.abercyl.tvguho.pbz', 'rot_13'), license='ISC', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'License :: OSI Approved :: ISC License (ISCL)', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], tests_require=['pytest'], scripts=['bin/digestive'], # TODO: turn this into an entry_points= )
import codecs from setuptools import find_packages, setup import digestive setup( name='digestive', version=digestive.__version__, url='https://github.com/akaIDIOT/Digestive', packages=find_packages(), description='TODO', author='Mattijs Ugen', author_email=codecs.encode('nxnvqvbg@hfref.abercyl.tvguho.pbz', 'rot_13'), license='ISC', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'License :: OSI Approved :: ISC License (ISCL)', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], tests_require=['pytest'], entry_points={ 'console_scripts': { 'digestive = digestive.main:main' } } )
Use console_scripts entry_point instead of scripts
Use console_scripts entry_point instead of scripts
Python
isc
akaIDIOT/Digestive
--- +++ @@ -23,5 +23,9 @@ 'Programming Language :: Python :: 3.4', ], tests_require=['pytest'], - scripts=['bin/digestive'], # TODO: turn this into an entry_points= + entry_points={ + 'console_scripts': { + 'digestive = digestive.main:main' + } + } )