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 |
|---|---|---|---|---|---|---|---|---|---|---|
489129bd26f72967fbbc279ab488fe047714a250 | qual/tests/test_iso.py | qual/tests/test_iso.py | import unittest
from hypothesis import given
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date
class TestIsoUtils(unittest.TestCase):
@given(datetimes())
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d.isocalendar... | import unittest
from hypothesis import given
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d... | Use timezones=[] to underline that we only care about dates. | Use timezones=[] to underline that we only care about dates.
| Python | apache-2.0 | jwg4/qual,jwg4/calexicon | ---
+++
@@ -7,7 +7,7 @@
from datetime import date
class TestIsoUtils(unittest.TestCase):
- @given(datetimes())
+ @given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d.isocalendar()), d) |
b72f0ed25750a29b5dc1cdd2790102d8351606f9 | pronto_feedback/feedback/views.py | pronto_feedback/feedback/views.py | import csv
from datetime import datetime
from django.shortcuts import render
from django.utils import timezone
from django.views.generic import TemplateView
from .forms import FeedbackUploadForm
from .models import Feedback
class FeedbackView(TemplateView):
template_name = 'index.html'
def get(self, reques... | import csv
from datetime import datetime
from django.shortcuts import render
from django.utils import timezone
from django.views.generic import TemplateView
from .forms import FeedbackUploadForm
from .models import Feedback
class FeedbackView(TemplateView):
template_name = 'index.html'
def get(self, reques... | Use next method of reader object | Use next method of reader object
| Python | mit | zkan/pronto-feedback,zkan/pronto-feedback | ---
+++
@@ -46,7 +46,7 @@
if form.is_valid():
reader = csv.reader(request.FILES['file_upload'])
- next(reader, None)
+ reader.next()
map(self.save_feedback, reader)
return render( |
8780d2eb3d7782e7f1e6c23e2e428a72e6bd3dad | server/kcaa/manipulator_util_test.py | server/kcaa/manipulator_util_test.py | #!/usr/bin/env python
import pytest
import manipulator_util
class TestManipulatorManager(object):
def pytest_funcarg__manager(self, request):
return manipulator_util.ManipulatorManager(None, {}, 0)
def test_in_schedule_fragment(self):
in_schedule_fragment = (
manipulator_util.M... | #!/usr/bin/env python
import pytest
import manipulator_util
class TestManipulatorManager(object):
def pytest_funcarg__manager(self, request):
return manipulator_util.ManipulatorManager(None, {}, 0)
def test_in_schedule_fragment(self):
in_schedule_fragment = (
manipulator_util.M... | Add a test for one schedule fragment. | Add a test for one schedule fragment.
| Python | apache-2.0 | kcaa/kcaa,kcaa/kcaa,kcaa/kcaa,kcaa/kcaa | ---
+++
@@ -20,8 +20,16 @@
assert not in_schedule_fragment(5400, [0, 3600])
def test_are_auto_manipulator_scheduled_disabled(self, manager):
- manager.set_auto_manipulator_schedules(False, [0, 3600])
+ manager.set_auto_manipulator_schedules(False, [[0, 3600]])
assert not manager... |
3987f059632c64058862425407cdc165d4f3182b | python/qisrc/test/test_qisrc_list.py | python/qisrc/test/test_qisrc_list.py | from qisys import ui
def test_list_tips_when_empty(qisrc_action, record_messages):
qisrc_action("init")
qisrc_action("list")
assert ui.find_message("Tips")
| from qisys import ui
def test_list_tips_when_empty(qisrc_action, record_messages):
qisrc_action("init")
qisrc_action("list")
assert ui.find_message("Tips")
def test_list_with_pattern(qisrc_action, record_messages):
qisrc_action.git_worktree.create_git_project("foo")
qisrc_action.git_worktree.creat... | Add test for qisrc list | Add test for qisrc list
Change-Id: I04c08f60044ffb0ba2ff63141d085e4dc2545455
| Python | bsd-3-clause | dmerejkowsky/qibuild,aldebaran/qibuild,aldebaran/qibuild,dmerejkowsky/qibuild,dmerejkowsky/qibuild,aldebaran/qibuild,dmerejkowsky/qibuild,dmerejkowsky/qibuild,aldebaran/qibuild | ---
+++
@@ -4,3 +4,13 @@
qisrc_action("init")
qisrc_action("list")
assert ui.find_message("Tips")
+
+def test_list_with_pattern(qisrc_action, record_messages):
+ qisrc_action.git_worktree.create_git_project("foo")
+ qisrc_action.git_worktree.create_git_project("baz")
+ qisrc_action.git_worktre... |
46352a3252e7827d349573c58608a1eefe163c21 | cbagent/collectors/eventing_stats.py | cbagent/collectors/eventing_stats.py | from cbagent.collectors import Collector
class EventingStats(Collector):
COLLECTOR = "eventing_stats"
def __init__(self, settings, test):
super().__init__(settings)
self.eventing_node = test.function_nodes[0]
self.functions = test.functions
def _get_processing_stats(self, functi... | from cbagent.collectors import Collector
class EventingStats(Collector):
COLLECTOR = "eventing_stats"
def __init__(self, settings, test):
super().__init__(settings)
self.eventing_node = test.function_nodes[0]
self.functions = test.functions
def _get_processing_stats(self, functi... | Fix port number for eventing stats | Fix port number for eventing stats
Change-Id: Ifaa7e9957f919febb1a297683077cd1c71c6aa9d
Reviewed-on: http://review.couchbase.org/84633
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Mahesh Mandhare <f05f25073b6d9a2858c6a374b80c02d5a2bccf33@couchbase.com>
| Python | apache-2.0 | pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,couchbase/perfrunner | ---
+++
@@ -11,7 +11,7 @@
self.functions = test.functions
def _get_processing_stats(self, function_name="perf-test1"):
- port = '25000'
+ port = '8096'
uri = "/getEventProcessingStats?name={}".format(function_name)
samples = self.get_http(path=uri, server=self.eventing_... |
bccd730eea204bd5c5ff99c919d87b13d9f25c73 | examples/plugin_example/gwexample/analyses/tasks.py | examples/plugin_example/gwexample/analyses/tasks.py | from girder_worker.app import app
@app.task
@app.argument('n', app.types.Integer)
def fibonacci(n):
"""Compute the nth fibonacci number recursively."""
if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
| from girder_worker.app import app
@app.task
@app.argument('n', app.types.Integer, min=1)
def fibonacci(n):
"""Compute the nth fibonacci number recursively."""
if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
| Add a minimum value to fibonacci example | Add a minimum value to fibonacci example
| Python | apache-2.0 | girder/girder_worker,girder/girder_worker,girder/girder_worker | ---
+++
@@ -2,7 +2,7 @@
@app.task
-@app.argument('n', app.types.Integer)
+@app.argument('n', app.types.Integer, min=1)
def fibonacci(n):
"""Compute the nth fibonacci number recursively."""
if n == 1 or n == 2: |
06dc49becd393e07086e368b26ab1aea3a9bc149 | pyelasticsearch/tests/__init__.py | pyelasticsearch/tests/__init__.py | """
Unit tests for pyelasticsearch
These require an elasticsearch server running on the default port
(localhost:9200).
"""
import unittest
from nose.tools import eq_
# Test that __all__ is sufficient:
from pyelasticsearch import *
class ElasticSearchTestCase(unittest.TestCase):
def setUp(self):
self.co... | """
Unit tests for pyelasticsearch
These require a local elasticsearch server running on the default port
(localhost:9200).
"""
from time import sleep
from unittest import TestCase
from nose import SkipTest
from nose.tools import eq_
from six.moves import xrange
# Test that __all__ is sufficient:
from pyelasticsearc... | Add a wait to see if we can get Travis passing again. | Add a wait to see if we can get Travis passing again.
| Python | bsd-3-clause | erikrose/pyelasticsearch | ---
+++
@@ -1,18 +1,32 @@
"""
Unit tests for pyelasticsearch
-These require an elasticsearch server running on the default port
+These require a local elasticsearch server running on the default port
(localhost:9200).
"""
-import unittest
+from time import sleep
+from unittest import TestCase
+from nose impor... |
d716dba6e61f4f7fcb2962dff06fc0d022bd04af | registration/__init__.py | registration/__init__.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.cor... | Add utility function for retrieving the active registration backend. | Add utility function for retrieving the active registration backend.
| Python | bsd-3-clause | austinhappel/django-registration,danielsamuels/django-registration,Troyhy/django-registration,gone/django-registration,ubernostrum/django-registration,sandipagr/django-registration,liberation/django-registration,akvo/django-registration,artursmet/django-registration,Troyhy/django-registration,hacklabr/django-registrati... | ---
+++
@@ -0,0 +1,23 @@
+from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
+from django.utils.importlib import import_module
+
+def get_backend():
+ """
+ Return an instance of the registration backend for use on this
+ site, as determined by the ``REGISTRATION_BACKEN... | |
fbb0abe3bdb62ec64bfdd03f9b45ded4def9613a | wsgi_intercept/test/test_mechanize.py | wsgi_intercept/test/test_mechanize.py |
from nose.tools import with_setup, raises
from urllib2 import URLError
from wsgi_intercept.mechanize_intercept import Browser
import wsgi_intercept
from wsgi_intercept import test_wsgi_app
from mechanize import Browser as MechanizeBrowser
###
_saved_debuglevel = None
def add_intercept():
# _saved_debuglevel, ws... | from urllib2 import URLError
from wsgi_intercept import testing
from wsgi_intercept.testing import unittest
from wsgi_intercept.test import base
try:
import mechanize
has_mechanize = True
except ImportError:
has_mechanize = False
_skip_message = "mechanize is not installed"
@unittest.skipUnless(has_mecha... | Use unittest in the mechanize related tests. | Use unittest in the mechanize related tests.
| Python | mit | pumazi/wsgi_intercept2 | ---
+++
@@ -1,47 +1,36 @@
+from urllib2 import URLError
+from wsgi_intercept import testing
+from wsgi_intercept.testing import unittest
+from wsgi_intercept.test import base
-from nose.tools import with_setup, raises
-from urllib2 import URLError
-from wsgi_intercept.mechanize_intercept import Browser
-import wsgi... |
c0e87b32f9f3c5e306fb553990754ff4aae9dc3c | hub/urls.py | hub/urls.py | """hub URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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 v... | """hub URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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 v... | Make trailing slash optional for API URLs. | Make trailing slash optional for API URLs.
Admin website URLs will still redirect to canonical version with trailing slash.
| Python | mit | kblum/sensor-hub | ---
+++
@@ -19,6 +19,6 @@
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
- url(r'^api/temperatures/$', views.api.TemperatureApiView.as_view()),
- url(r'^api/status/$', views.api.StatusApiView.as_view()),
+ url(r'^api/temperatures/?$', views.api.TemperatureApiView.as_view()),
+ url(r'^a... |
0ea3b4eca6cbd70200ffc3a844cedf1b4a427a42 | src/doc/help2man_preformat.py | src/doc/help2man_preformat.py | #!/usr/bin/python
# Format the output from various oiio command line "$tool --help" invocations,
# and munge such that txt2man generates a simple man page with not-too-horrible
# formatting.
from __future__ import print_function
from __future__ import absolute_import
import sys
lines = [l.rstrip().replace('\t', ' '*... | #!/usr/bin/python
# Format the output from various oiio command line "$tool --help" invocations,
# and munge such that txt2man generates a simple man page with not-too-horrible
# formatting.
from __future__ import print_function
from __future__ import absolute_import
import sys
lines = [l.rstrip().replace('\t', ' '*... | Fix typo in man pages | Fix typo in man pages
| Python | bsd-3-clause | OpenImageIO/oiio,OpenImageIO/oiio,OpenImageIO/oiio,lgritz/oiio,OpenImageIO/oiio,lgritz/oiio,lgritz/oiio,lgritz/oiio | ---
+++
@@ -23,7 +23,7 @@
print('''DESCRIPTION
This program is part of the OpenImageIO (http://www.openimageio.org) tool suite.
-Detailed documentation is avaliable in pdf format with the OpenImageIO
+Detailed documentation is available in pdf format with the OpenImageIO
distribution.
''')
|
697c590bf60c261280e55f8580b33423dbe800c6 | splinter/driver/webdriver/firefox.py | splinter/driver/webdriver/firefox.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from splinter.driver.webdriver import BaseWebDriver, WebDriverElement as BaseWebDriverElement
from splinter.driver.webdriver.cookie_manager import... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from splinter.driver.webdriver import BaseWebDriver, WebDriverElement as BaseWebDriverElement
from splinter.driver.webdriver.cookie_manager import... | Fix error on Firefox 6 where pages are not open if this preference is True (default). | Fix error on Firefox 6 where pages are not open if this preference is True (default).
| Python | bsd-3-clause | bmcculley/splinter,cobrateam/splinter,bmcculley/splinter,nikolas/splinter,drptbl/splinter,objarni/splinter,nikolas/splinter,cobrateam/splinter,drptbl/splinter,underdogio/splinter,underdogio/splinter,bubenkoff/splinter,lrowe/splinter,bubenkoff/splinter,lrowe/splinter,objarni/splinter,gjvis/splinter,bmcculley/splinter,un... | ---
+++
@@ -14,6 +14,7 @@
self.old_popen = subprocess.Popen
firefox_profile = FirefoxProfile(profile)
firefox_profile.set_preference('extensions.logging.enabled', False)
+ firefox_profile.set_preference('network.dns.disableIPv6', False)
if extensions:
for exte... |
5009a88b16e8776e87a338796baa6d8e60c99ee7 | police_api/resource.py | police_api/resource.py | import requests
API_URL = 'http://data.police.uk/api/'
class APIError(Exception):
pass
def api_request(method):
r = requests.get(API_URL + method)
if r.status_code != 200:
raise APIError(r.status_code)
return r.json()
class Resource(object):
_requested = False
api_method = None
... | import requests
API_URL = 'http://data.police.uk/api/'
class APIError(Exception):
pass
def api_request(method):
r = requests.get(API_URL + method)
if r.status_code != 200:
raise APIError(r.status_code)
return r.json()
class Resource(object):
_requested = False
api_method = None
... | Fix IndexError bug in _hydrate | Fix IndexError bug in _hydrate
| Python | mit | rkhleics/police-api-client-python | ---
+++
@@ -37,4 +37,4 @@
def _hydrate(self):
for field in self.fields:
hydrate_field = getattr(self, '_hydrate_%s' % field, lambda x: x)
- setattr(self, field, hydrate_field(self._response_data[field]))
+ setattr(self, field, hydrate_field(self._response_data.get(fiel... |
f7dea9dbfc5714be08e6cf9f146ae9eca21929c3 | test/on_yubikey/cli_piv/test_misc.py | test/on_yubikey/cli_piv/test_misc.py | import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv',... | import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv',... | Fix test warning about wrong assert function | Fix test warning about wrong assert function
| Python | bsd-2-clause | Yubico/yubikey-manager,Yubico/yubikey-manager | ---
+++
@@ -25,6 +25,6 @@
'-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001',
'-', input='test data')
output = ykman_cli('piv', 'read-object', '0x5f0001')
- self.assertEquals('test data\n', output)
+ self.assertEqual('test data\n', output)
return [Misc... |
0e3952c0648375810b479d093e970d072db0fe6d | app/resources/forms.py | app/resources/forms.py | from flask.ext.wtf import Form
from wtforms.fields import (
StringField,
IntegerField,
SubmitField
)
from wtforms.validators import InputRequired, Length
class ResourceForm(Form):
autocomplete = StringField('Enter the address')
name = StringField('Name', validators=[
InputRequired(),
... | from flask.ext.wtf import Form
from wtforms.fields import (
StringField,
IntegerField,
SubmitField
)
from wtforms.validators import InputRequired, Length
class ResourceForm(Form):
autocomplete = StringField('Enter the address')
name = StringField('Name', validators=[
InputRequired(),
... | Comment about form field names for Google Autocomplete | Comment about form field names for Google Autocomplete
| Python | mit | hack4impact/women-veterans-rock,hack4impact/women-veterans-rock,hack4impact/women-veterans-rock | ---
+++
@@ -22,6 +22,7 @@
street_number = IntegerField('Street Number', validators=[
InputRequired()
])
+ # Google Place Autocomplete example divs named for Google address schema
route = StringField('Street Address', validators=[
InputRequired()
]) |
992b3302c4cb690e86436c54c43d0bb2aa406b0d | scrapi/harvesters/hacettepe_U_DIM.py | scrapi/harvesters/hacettepe_U_DIM.py | '''
Harvester for the DSpace on LibLiveCD for the SHARE project
Example API call: http://bbytezarsivi.hacettepe.edu.tr/oai/request?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class Hacettepe_u_dimHarvester(OAIHarvester):
short_name = 'h... | '''
Harvester for the DSpace on LibLiveCD for the SHARE project
Example API call: http://bbytezarsivi.hacettepe.edu.tr/oai/request?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class HacettepeHarvester(OAIHarvester):
short_name = 'hacette... | Change shortname and class name | Change shortname and class name
| Python | apache-2.0 | alexgarciac/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,ostwald/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,jeffreyliu3230/scrapi,mehanig/scrapi,erinspace/scrapi,felliott/scrapi,felliott/scrapi,fabianvf/scrapi | ---
+++
@@ -8,8 +8,8 @@
from scrapi.base import OAIHarvester
-class Hacettepe_u_dimHarvester(OAIHarvester):
- short_name = 'hacettepe_U_DIM'
+class HacettepeHarvester(OAIHarvester):
+ short_name = 'hacettepe'
long_name = 'DSpace on LibLiveCD'
url = 'http://bbytezarsivi.hacettepe.edu.tr/oai/reques... |
0da1b3984f1e518dffc55ac7d3c2d53ef4bf55cb | matchzoo/utils/util_preprocessor.py | matchzoo/utils/util_preprocessor.py | """Utils for preprocessors."""
def validate_context(func):
"""Validate context in the preprocessor."""
def transform_wrapper(self, *args, **kwargs):
if not self._context:
raise ValueError(
'Please fit parameters before transformation.')
return func(self, *args, **kw... | """Utils for preprocessors."""
def validate_context(func):
"""Validate context in the preprocessor."""
def transform_wrapper(self, *args, **kwargs):
if not self.context:
raise ValueError(
'Please fit parameters before transformation.')
return func(self, *args, **kwa... | Update context checker by using accessor instead | Update context checker by using accessor instead
| Python | apache-2.0 | faneshion/MatchZoo,faneshion/MatchZoo | ---
+++
@@ -4,7 +4,7 @@
def validate_context(func):
"""Validate context in the preprocessor."""
def transform_wrapper(self, *args, **kwargs):
- if not self._context:
+ if not self.context:
raise ValueError(
'Please fit parameters before transformation.')
... |
312c0d463940257cb1f777d3720778550b5bdb2d | bluebottle/organizations/serializers.py | bluebottle/organizations/serializers.py | from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'slug', 'address_line1', 'address_l... | from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'slug', 'address_line1', 'address_l... | Revert "Make the name of an organization required" | Revert "Make the name of an organization required"
This reverts commit 02140561a29a2b7fe50f7bf2402da566e60be641.
| Python | bsd-3-clause | jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -14,7 +14,7 @@
class ManageOrganizationSerializer(serializers.ModelSerializer):
slug = serializers.SlugField(required=False, allow_null=True)
- name = serializers.CharField(required=True)
+ name = serializers.CharField(required=True, allow_blank=True)
website = URLField(required=False, a... |
80fa2f3c47ddc845d4dc9e549df38f68267873d6 | corehq/ex-submodules/pillow_retry/tasks.py | corehq/ex-submodules/pillow_retry/tasks.py | from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db.models import Count
from corehq.util.datadog.gauges import datadog_gauge
from pillow_retry.models import PillowError
@periodic_task(
run_every=crontab(minute="*/15"),
queue=settings.CELE... | from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db.models import Count
from corehq.util.datadog.gauges import datadog_gauge
from pillow_retry.models import PillowError
@periodic_task(
run_every=crontab(minute="*/15"),
queue=settings.CELE... | Send error-type info to pillow error DD metrics | Send error-type info to pillow error DD metrics
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -17,5 +17,6 @@
datadog_gauge('commcare.pillowtop.error_queue', row['num_errors'], tags=[
'pillow_name:%s' % row['pillow'],
'host:celery',
- 'group:celery'
+ 'group:celery',
+ 'error_type:%s' % row['error_type']
]) |
3c64002217795e5d8d3eebb7b06f8ad72f342564 | thinglang/parser/tokens/functions.py | thinglang/parser/tokens/functions.py | from thinglang.lexer.symbols.base import LexicalAccess
from thinglang.parser.tokens import BaseToken, DefinitionPairToken
from thinglang.parser.tokens.collections import ListInitializationPartial, ListInitialization
from thinglang.utils.type_descriptors import ValueType
class Access(BaseToken):
def __init__(self... | from thinglang.lexer.symbols.base import LexicalAccess, LexicalIdentifier
from thinglang.lexer.symbols.functions import LexicalClassInitialization
from thinglang.parser.tokens import BaseToken, DefinitionPairToken
from thinglang.parser.tokens.collections import ListInitializationPartial, ListInitialization
from thingl... | Add proper support for constructor calls to MethodCall | Add proper support for constructor calls to MethodCall
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | ---
+++
@@ -1,4 +1,5 @@
-from thinglang.lexer.symbols.base import LexicalAccess
+from thinglang.lexer.symbols.base import LexicalAccess, LexicalIdentifier
+from thinglang.lexer.symbols.functions import LexicalClassInitialization
from thinglang.parser.tokens import BaseToken, DefinitionPairToken
from thinglang.par... |
acd84f19d8d8820aecdba62bf4d0c97a2d4bdf34 | src/source_weather/source_weather.py | src/source_weather/source_weather.py | """
Definition of a source than add dumb data
"""
from src.source import Source
class SourceMock(Source):
"""Add a funny key with a funny value in the given dict"""
def __init__(self, funny_message="Java.OutOfMemoryError"
funny_key="Who's there ?"):
self.funny_message = funny_message... | """
Definition of a source than add dumb data
"""
from src.source import Source
from . import weather
class SourceWeaver(Source):
"""
Throught Open Weather Map generates today weather and
expected weather for next days, if possible
"""
def enrichment(self, data_dict):
if default.FIELD_CO... | Access to actual or predicted weather done | Access to actual or predicted weather done
| Python | unlicense | Aluriak/24hducode2016,Aluriak/24hducode2016 | ---
+++
@@ -3,18 +3,26 @@
"""
from src.source import Source
+from . import weather
-class SourceMock(Source):
- """Add a funny key with a funny value in the given dict"""
+class SourceWeaver(Source):
+ """
+ Throught Open Weather Map generates today weather and
+ expected weather for next days, if p... |
0d6d28c437b1da4c29b2a9115c4ff8cab038eb53 | pyvac/task/__init__.py | pyvac/task/__init__.py | # -*- coding: utf-8 -*-
import sys
import yaml
from celery.signals import worker_process_init
from pyvac.helpers.sqla import create_engine
from pyvac.helpers.ldap import LdapCache
from pyvac.helpers.mail import SmtpCache
try:
from yaml import CSafeLoader as YAMLLoader
except ImportError:
from yaml import Safe... | # -*- coding: utf-8 -*-
import sys
import yaml
from celery.signals import worker_process_init
from pyvac.helpers.sqla import create_engine
from pyvac.helpers.ldap import LdapCache
from pyvac.helpers.mail import SmtpCache
try:
from yaml import CSafeLoader as YAMLLoader
except ImportError:
from yaml import Safe... | Use scoped session for celery tasks | Use scoped session for celery tasks
| Python | bsd-3-clause | sayoun/pyvac,doyousoft/pyvac,doyousoft/pyvac,sayoun/pyvac,sayoun/pyvac,doyousoft/pyvac | ---
+++
@@ -21,6 +21,6 @@
conf = yaml.load(fdesc, YAMLLoader)
# XXX Register the database
create_engine('pyvac', conf.get('databases').get('pyvac'),
- scoped=False)
+ scoped=True)
LdapCache.configure(conf.get('ldap').get('conf'))
SmtpCache.configure(conf.... |
d8e876fc60d96f0d635862e845ae565ef3e2afb9 | openpnm/models/geometry/__init__.py | openpnm/models/geometry/__init__.py | r"""
**openpnm.models.geometry**
----
This submodule contains pore-scale models that calculate geometrical properties
"""
from . import pore_size
from . import pore_seed
from . import pore_volume
from . import pore_surface_area
from . import pore_area
from . import throat_area
from . import throat_equivalent_area
... | r"""
**openpnm.models.geometry**
----
This submodule contains pore-scale models that calculate geometrical properties
"""
from . import pore_size
from . import pore_seed
from . import pore_volume
from . import pore_surface_area
from . import pore_area
from . import throat_centroid
from . import throat_area
from . ... | Update init file in models.geometry | Update init file in models.geometry | Python | mit | TomTranter/OpenPNM,PMEAL/OpenPNM | ---
+++
@@ -13,8 +13,8 @@
from . import pore_volume
from . import pore_surface_area
from . import pore_area
+from . import throat_centroid
from . import throat_area
-from . import throat_equivalent_area
from . import throat_size
from . import throat_length
from . import throat_perimeter |
e1a4839475b87e3ce02a12465b18114c7c85f31b | ueberwachungspaket/decorators.py | ueberwachungspaket/decorators.py | from flask import abort, current_app, request
from functools import wraps
from twilio.util import RequestValidator
from config import *
def validate_twilio_request(f):
@wraps(f)
def decorated_function(*args, **kwargs):
validator = RequestValidator(TWILIO_SECRET)
request_valid = validator.valid... | from flask import abort, current_app, request
from functools import wraps
from twilio.util import RequestValidator
from config import *
def validate_twilio_request(f):
@wraps(f)
def decorated_function(*args, **kwargs):
validator = RequestValidator(TWILIO_SECRET)
request_valid = validator.valid... | Convert Twilio URL to IDN. | Convert Twilio URL to IDN.
| Python | mit | AKVorrat/ueberwachungspaket.at,AKVorrat/ueberwachungspaket.at,AKVorrat/ueberwachungspaket.at | ---
+++
@@ -9,7 +9,7 @@
validator = RequestValidator(TWILIO_SECRET)
request_valid = validator.validate(
- request.url,
+ request.url.encode("idna"),
request.form,
request.headers.get("X-TWILIO-SIGNATURE", ""))
|
f7959e3f0727bcab47cdf3b8f1250bbb45788af0 | skimage/_shared/utils.py | skimage/_shared/utils.py | import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
"""Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use i... | import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
"""Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use i... | Fix doc string injection of deprecated wrapper | Fix doc string injection of deprecated wrapper
| Python | bsd-3-clause | michaelpacer/scikit-image,vighneshbirodkar/scikit-image,chintak/scikit-image,michaelaye/scikit-image,michaelpacer/scikit-image,almarklein/scikit-image,Hiyorimi/scikit-image,blink1073/scikit-image,ofgulban/scikit-image,juliusbierk/scikit-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,robintw/scikit-im... | ---
+++
@@ -27,9 +27,9 @@
alt_msg = ''
if self.alt_func is not None:
- alt_msg = ' Use `%s` instead.' % self.alt_func
+ alt_msg = ' Use ``%s`` instead.' % self.alt_func
- msg = 'Call to deprecated function `%s`.' % func.__name__
+ msg = 'Call to deprecated fun... |
41221b36a596b1253445f1e49b10bff1fc44be42 | tests/test_it.py | tests/test_it.py | import requests
def test_notifications_admin_index():
response = requests.request("GET", "http://notifications-admin.herokuapp.com/index")
assert response.status_code == 200
# assert response.content == 'Hello from notifications-admin'
| import requests
def test_notifications_admin_index():
# response = requests.request("GET", "http://localhost:6012")
response = requests.request("GET", "http://notifications-admin.herokuapp.com/")
assert response.status_code == 200
assert 'GOV.UK Notify' in response.content
| Fix test for initial registration page flow | Fix test for initial registration page flow
| Python | mit | alphagov/notifications-functional-tests,alphagov/notifications-functional-tests | ---
+++
@@ -2,6 +2,7 @@
def test_notifications_admin_index():
- response = requests.request("GET", "http://notifications-admin.herokuapp.com/index")
+ # response = requests.request("GET", "http://localhost:6012")
+ response = requests.request("GET", "http://notifications-admin.herokuapp.com/")
asse... |
b79c2567bdad69022f00536ebdd66adfcb5e6d48 | scoreboard/config_defaults.py | scoreboard/config_defaults.py | # Copyright 2016 David Tomaschik <david@systemoverlord.com>
#
# 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... | # Copyright 2016 David Tomaschik <david@systemoverlord.com>
#
# 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... | Make session cookies have secure and httponly flags by default. | Make session cookies have secure and httponly flags by default.
| Python | apache-2.0 | google/ctfscoreboard,google/ctfscoreboard,google/ctfscoreboard,google/ctfscoreboard | ---
+++
@@ -34,6 +34,8 @@
SCOREBOARD_ZEROS = True
SCORING = 'plain'
SECRET_KEY = None
+ SESSION_COOKIE_HTTPONLY = True
+ SESSION_COOKIE_SECURE = True
SYSTEM_NAME = 'root'
TEAMS = True
TEASE_HIDDEN = True |
80e8965c068ab27b18cd1db90ddedbc3dfe3c255 | templated_email/utils.py | templated_email/utils.py |
#From http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template
from django.template import Context
from django.template.loader_tags import BlockNode, ExtendsNode
class BlockNotFound(Exception):
pass
def _get_node(template, context=Context(), name='subject', block_lookups={}):
... |
#From http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template
from django.template import Context
from django.template.loader_tags import BlockNode, ExtendsNode
class BlockNotFound(Exception):
pass
def _get_node(template, context=Context(), name='subject', block_lookups={}):
... | Fix 'Template is not iterable' error | Fix 'Template is not iterable' error
| Python | mit | mypebble/django-templated-email,ScanTrust/django-templated-email,mypebble/django-templated-email,hator/django-templated-email,vintasoftware/django-templated-email,hator/django-templated-email,dpetzold/django-templated-email,vintasoftware/django-templated-email,ScanTrust/django-templated-email,dpetzold/django-templated-... | ---
+++
@@ -9,7 +9,7 @@
def _get_node(template, context=Context(), name='subject', block_lookups={}):
- for node in template:
+ for node in template.template:
if isinstance(node, BlockNode) and node.name == name:
#Rudimentary handling of extended templates, for issue #3
f... |
15cb312fd7acbb7fae67cb3953537a95274f9d40 | saleor/search/forms.py | saleor/search/forms.py | from __future__ import unicode_literals
from django import forms
from django.utils.translation import pgettext
from .backends import elasticsearch
class SearchForm(forms.Form):
q = forms.CharField(
label=pgettext('Search form label', 'Query'), required=True)
def search(self):
return elastics... | from __future__ import unicode_literals
from django import forms
from django.utils.translation import pgettext
from .backends import picker
class SearchForm(forms.Form):
q = forms.CharField(
label=pgettext('Search form label', 'Query'), required=True)
def search(self):
search = picker.pick_b... | Use backend picker in storefront search form | Use backend picker in storefront search form
| Python | bsd-3-clause | UITools/saleor,UITools/saleor,maferelo/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,mociepka/saleor,UITools/saleor,maferelo/saleor | ---
+++
@@ -2,7 +2,7 @@
from django import forms
from django.utils.translation import pgettext
-from .backends import elasticsearch
+from .backends import picker
class SearchForm(forms.Form):
@@ -10,4 +10,5 @@
label=pgettext('Search form label', 'Query'), required=True)
def search(self):
- ... |
0034c67af62807221c983c2569dfab71ba302b0e | enable/layout/utils.py | enable/layout/utils.py | #------------------------------------------------------------------------------
# Copyright (c) 2013, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
STRENGTHS = set(['required', 'strong', 'medium', 'weak'])
def add_symbolic_constraints(namesp... | #------------------------------------------------------------------------------
# Copyright (c) 2013, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
STRENGTHS = set(['required', 'strong', 'medium', 'weak'])
def add_symbolic_constraints(namesp... | Fix a typo in the contents constraints creation. | Fix a typo in the contents constraints creation.
| Python | bsd-3-clause | tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable | ---
+++
@@ -33,7 +33,7 @@
top = namespace.contents_top
bottom = namespace.contents_bottom
- namespace.contents_width = left - right
+ namespace.contents_width = right - left
namespace.contents_height = top - bottom
namespace.contents_v_center = bottom + namespace.contents_height / 2.0
... |
422a75e4b85345bd517c73760430ae773d49dc00 | var/spack/packages/arpack/package.py | var/spack/packages/arpack/package.py | from spack import *
class Arpack(Package):
"""FIXME: put a proper description of your package here."""
homepage = "http://www.caam.rice.edu/software/ARPACK/"
url = "http://www.caam.rice.edu/software/ARPACK/SRC/arpack96.tar.gz"
version('96', 'fffaa970198b285676f4156cebc8626e')
depends_on('bla... | from spack import *
class Arpack(Package):
"""A collection of Fortran77 subroutines designed to solve large scale
eigenvalue problems.
"""
homepage = "http://www.caam.rice.edu/software/ARPACK/"
url = "http://www.caam.rice.edu/software/ARPACK/SRC/arpack96.tar.gz"
version('96', 'fffaa970... | Clean up arpack build, use the Spack f77 compiler. | Clean up arpack build, use the Spack f77 compiler.
| Python | lgpl-2.1 | TheTimmy/spack,tmerrick1/spack,mfherbst/spack,lgarren/spack,iulian787/spack,lgarren/spack,skosukhin/spack,krafczyk/spack,iulian787/spack,EmreAtes/spack,mfherbst/spack,skosukhin/spack,tmerrick1/spack,matthiasdiener/spack,mfherbst/spack,skosukhin/spack,matthiasdiener/spack,LLNL/spack,krafczyk/spack,EmreAtes/spack,EmreAte... | ---
+++
@@ -1,7 +1,9 @@
from spack import *
class Arpack(Package):
- """FIXME: put a proper description of your package here."""
+ """A collection of Fortran77 subroutines designed to solve large scale
+ eigenvalue problems.
+ """
homepage = "http://www.caam.rice.edu/software/ARPACK/"
url... |
e8ca2582404d44a6bc97f455187523713c49d90f | test/test_random_seed.py | test/test_random_seed.py | from nose.tools import assert_equal
import genson
def test_gaussian_random_seed():
gson = \
"""
{
"gaussian_random_seed" : gaussian(0, 1, draws=1, random_seed=42)
}
"""
val = genson.loads(gson).next()['gaussian_random_seed']
assert_equal(val, 0.4967141530112327)
def test_gaussian... | from nose.tools import assert_equal
import genson
def test_gaussian_random_seed():
gson = \
"""
{
"gaussian_random_seed" : gaussian(0, 1, draws=2, random_seed=42)
}
"""
vals = [val['gaussian_random_seed'] for val in genson.loads(gson)]
assert_equal(vals[0], 0.4967141530112327)
... | Add RandomState to help generate different values, with test | Add RandomState to help generate different values, with test
| Python | mit | davidcox/genson | ---
+++
@@ -6,19 +6,21 @@
gson = \
"""
{
- "gaussian_random_seed" : gaussian(0, 1, draws=1, random_seed=42)
+ "gaussian_random_seed" : gaussian(0, 1, draws=2, random_seed=42)
}
"""
- val = genson.loads(gson).next()['gaussian_random_seed']
- assert_equal(val, 0.496714153011... |
1bb86e33c8862b5423d292ccc1bd74c560af2e44 | vinotes/apps/api/models.py | vinotes/apps/api/models.py | from django.db import models
class Winery(models.Model):
title = models.CharField(max_length=150)
def __str__(self):
return self.title
class Wine(models.Model):
title = models.CharField(max_length=150)
vintage = models.IntegerField()
winery = models.ForeignKey(Winery)
def __str__(sel... | from django.db import models
class Winery(models.Model):
title = models.CharField(max_length=150)
def __str__(self):
return self.title
class Wine(models.Model):
title = models.CharField(max_length=150)
vintage = models.IntegerField()
winery = models.ForeignKey(Winery)
def __str__(sel... | Update to include vintage in string representation for Wine. | Update to include vintage in string representation for Wine.
| Python | unlicense | rcutmore/vinotes-api,rcutmore/vinotes-api | ---
+++
@@ -12,7 +12,8 @@
winery = models.ForeignKey(Winery)
def __str__(self):
- return '{winery} {wine}'.format(winery=self.winery, wine=self.title)
+ return '{winery} {wine} {vintage}'.format(
+ winery=self.winery, wine=self.title, vintage=self.vintage)
class Note(models.Mod... |
10a0d12f39760d2c2d57f66bc445f0cb87cde69f | django_website/aggregator/management/commands/mark_defunct_feeds.py | django_website/aggregator/management/commands/mark_defunct_feeds.py | import urllib2
from django.core.management.base import BaseCommand
from django_website.apps.aggregator.models import Feed
class Command(BaseCommand):
"""
Mark people with 404'ing feeds as defunct.
"""
def handle(self, *args, **kwargs):
verbose = kwargs.get('verbosity')
for f in Feed.obj... | import urllib2
from django.core.management.base import BaseCommand
from django_website.apps.aggregator.models import Feed
class Command(BaseCommand):
"""
Mark people with 404'ing feeds as defunct.
"""
def handle(self, *args, **kwargs):
verbose = kwargs.get('verbosity')
for f in Feed.obj... | Set feed update timeouts in a more modern way. | Set feed update timeouts in a more modern way.
| Python | bsd-3-clause | vxvinh1511/djangoproject.com,gnarf/djangoproject.com,hassanabidpk/djangoproject.com,hassanabidpk/djangoproject.com,django/djangoproject.com,xavierdutreilh/djangoproject.com,nanuxbe/django,django/djangoproject.com,hassanabidpk/djangoproject.com,django/djangoproject.com,xavierdutreilh/djangoproject.com,gnarf/djangoprojec... | ---
+++
@@ -10,8 +10,7 @@
verbose = kwargs.get('verbosity')
for f in Feed.objects.all():
try:
- socket.setdefaulttimeout(15)
- r = urllib2.urlopen(f.feed_url)
+ r = urllib2.urlopen(f.feed_url, timeout=15)
except urllib2.HTTPError... |
450cb155d87b49a718e465d582bd2ccafb3244dd | tests/test_calculator.py | tests/test_calculator.py | import unittest
from app.calculator import Calculator
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_calculator_addition_method_returns_correct_result(self):
calc = Calculator()
result = calc.addition(2,2)
self.assertEqual(4, resu... | import unittest
from app.calculator import Calculator
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_calculator_addition_method_returns_correct_result(self):
calc = Calculator()
result = calc.addition(2,2)
self.assertEqual(4, resu... | Add new test for division | Add new test for division
| Python | apache-2.0 | kamaxeon/fap | ---
+++
@@ -17,3 +17,8 @@
calc = Calculator()
result = calc.substraction(4,2)
self.assertEqual(2, result)
+
+ def test_calculator_division_method_returns_correct_result(self):
+ calc = Calculator()
+ result = calc.division(5,2)
+ self.assertEqual(2.5, result) |
472110a92d15358aee6aeb6dd007f4d237a6fad6 | compile/06-switch.dg.py | compile/06-switch.dg.py | ..compile = import
..parse.syntax = import
compile.r.builtins !! 'else' = (self, cond, otherwise) ->
'''
a if b else c
a unless b else c
Ternary conditional.
'''
is_if, (then, cond) = parse.syntax.else_: cond
ptr = self.opcode: 'POP_JUMP_IF_TRUE' cond delta: 0 if is_if
ptr = self.op... | ..compile = import
..parse.syntax = import
compile.r.builtins !! 'else' = (self, cond, otherwise) ->
'''
a if b else c
a unless b else c
Ternary conditional.
'''
is_if, (then, cond) = parse.syntax.else_: cond
ptr = self.opcode: 'POP_JUMP_IF_FALSE' cond delta: 0 if is_if
ptr = self.op... | Swap opcodes for if-else and unless-else. | Swap opcodes for if-else and unless-else.
Oops.
| Python | mit | pyos/dg | ---
+++
@@ -12,8 +12,8 @@
'''
is_if, (then, cond) = parse.syntax.else_: cond
- ptr = self.opcode: 'POP_JUMP_IF_TRUE' cond delta: 0 if is_if
- ptr = self.opcode: 'POP_JUMP_IF_FALSE' cond delta: 0 unless is_if
+ ptr = self.opcode: 'POP_JUMP_IF_FALSE' cond delta: 0 if is_if
+ ptr = self.opcode: 'POP... |
0c3bbe815275b06729cdb52668b38f3a83e7fbac | datacommons/crawlers/zz/icij_dump.py | datacommons/crawlers/zz/icij_dump.py | from normality import slugify, stringify
from csv import DictReader
from zipfile import ZipFile
def load_file(context, zip, name):
fh = zip.open(name)
_, section, _ = name.rsplit(".", 2)
table_name = "%s_%s" % (context.crawler.name, section)
table = context.datastore[table_name]
table.drop()
r... | import io
from csv import DictReader
from zipfile import ZipFile
from normality import slugify, stringify
from dataset.chunked import ChunkedInsert
def load_file(context, zip, name):
fh = zip.open(name)
_, section, _ = name.rsplit(".", 2)
table_name = "%s_%s" % (context.crawler.name, section)
table = ... | Fix up ICIJ loader as-is | Fix up ICIJ loader as-is
| Python | mit | pudo/flexicadastre | ---
+++
@@ -1,6 +1,8 @@
-from normality import slugify, stringify
+import io
from csv import DictReader
from zipfile import ZipFile
+from normality import slugify, stringify
+from dataset.chunked import ChunkedInsert
def load_file(context, zip, name):
@@ -9,17 +11,13 @@
table_name = "%s_%s" % (context.cra... |
8f4c376a57c68636188880cd92c64b4640b1c8cc | sheared/web/entwine.py | sheared/web/entwine.py | import warnings
from dtml import tal, metal, tales, context
from sheared.python import io
class Entwiner:
def __init__(self):
self.builtins = context.BuiltIns({})
#self.context = context.Context()
#self.context.setDefaults(self.builtins)
def handle(self, request, reply, subpath):
... | import warnings
from dtml import tal, metal, tales
from sheared.python import io
class Entwiner:
def handle(self, request, reply, subpath):
self.context = {}
self.entwine(request, reply, subpath)
r = self.execute(self.page_path, throwaway=0)
reply.send(r)
def execute(self, pa... | Remove the builtins arguments to the {tal,metal}.execute calls. | Remove the builtins arguments to the {tal,metal}.execute calls.
git-svn-id: 8b0eea19d26e20ec80f5c0ea247ec202fbcc1090@107 5646265b-94b7-0310-9681-9501d24b2df7
| Python | mit | kirkeby/sheared | ---
+++
@@ -1,28 +1,22 @@
import warnings
-from dtml import tal, metal, tales, context
+from dtml import tal, metal, tales
from sheared.python import io
class Entwiner:
- def __init__(self):
- self.builtins = context.BuiltIns({})
- #self.context = context.Context()
- #self.context.set... |
a463fe25f21194744e9979840b7535f6cd765e36 | core/plugins/command.py | core/plugins/command.py | # coding: utf-8
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os
from ..quokka import ExternalProcess, PluginException
class ConsoleApplication(ExternalProce... | # coding: utf-8
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os
import shlex
from ..quokka import ExternalProcess, PluginException
class ConsoleApplication(... | Use shlex to split parameters | Use shlex to split parameters
| Python | mpl-2.0 | MozillaSecurity/quokka,drptbl/quokka | ---
+++
@@ -3,6 +3,7 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os
+import shlex
from ..quokka import ExternalProcess, PluginException
@@ -24,6 +25,6 @@
cmd = [binary]
if params:
- cm... |
a1db577312a31f73a0f1c9f04cc65871f2ef1c95 | dbaas/maintenance/admin/maintenance.py | dbaas/maintenance/admin/maintenance.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from django_services import admin
from ..models import Maintenance
from ..service.maintenance import MaintenanceService
class MaintenanceAdmin(admin.DjangoServicesAdmin):
servi... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from django_services import admin
from ..models import Maintenance
from ..service.maintenance import MaintenanceService
class MaintenanceAdmin(admin.DjangoServicesAdmin):
servi... | Change field order and customize Maintenance add_view | Change field order and customize Maintenance add_view
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -11,8 +11,8 @@
service_class = MaintenanceService
search_fields = ("scheduled_for", "description", "maximum_workers", 'status')
list_display = ("scheduled_for", "description", "maximum_workers", 'status')
- fields = ( "description", "scheduled_for","maximum_workers", 'status',
- "m... |
2d0a96403d58c4a939b17e67f8f93190839ff340 | txircd/modules/cmd_ping.py | txircd/modules/cmd_ping.py | from twisted.words.protocols import irc
from txircd.modbase import Command
class PingCommand(Command):
def onUse(self, user, data):
if data["params"]:
user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"], prefix=None)
else:
user.sendMessage(irc.ERR_NOORIGIN, ":No ... | from twisted.words.protocols import irc
from txircd.modbase import Command
class PingCommand(Command):
def onUse(self, user, data):
if data["params"]:
user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"])
else:
user.sendMessage(irc.ERR_NOORIGIN, ":No origin specif... | Send the server prefix on the line when the client sends PING | Send the server prefix on the line when the client sends PING
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd | ---
+++
@@ -4,7 +4,7 @@
class PingCommand(Command):
def onUse(self, user, data):
if data["params"]:
- user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"], prefix=None)
+ user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_nam... |
8fd62b820cb03b1dcfc3945f612ca43f916b86a2 | prettyplotlib/_eventplot.py | prettyplotlib/_eventplot.py | __author__ = 'jgosmann'
from prettyplotlib.utils import remove_chartjunk, maybe_get_ax
from prettyplotlib.colors import set2
def eventplot(*args, **kwargs):
ax, args, kwargs = maybe_get_ax(*args, **kwargs)
show_ticks = kwargs.pop('show_ticks', False)
# FIXME 1d positions
if len(args) > 0:
po... | __author__ = 'jgosmann'
from matplotlib.cbook import iterable
from prettyplotlib.utils import remove_chartjunk, maybe_get_ax
from prettyplotlib.colors import set2
def eventplot(*args, **kwargs):
ax, args, kwargs = maybe_get_ax(*args, **kwargs)
show_ticks = kwargs.pop('show_ticks', False)
if len(args) >... | Fix eventplot for 1d arguments. | Fix eventplot for 1d arguments.
| Python | mit | olgabot/prettyplotlib,olgabot/prettyplotlib | ---
+++
@@ -1,4 +1,6 @@
__author__ = 'jgosmann'
+
+from matplotlib.cbook import iterable
from prettyplotlib.utils import remove_chartjunk, maybe_get_ax
from prettyplotlib.colors import set2
@@ -8,12 +10,17 @@
ax, args, kwargs = maybe_get_ax(*args, **kwargs)
show_ticks = kwargs.pop('show_ticks', False)
... |
21cf7d8dddad631975760ea71ef4f530acecf393 | hello.py | hello.py | from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('hello.html')
| from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('hello.html')
if __name__ == '__main__':
app.run()
| Allow running the app from cli | Allow running the app from cli
| Python | mit | siavashg/tictail-heroku-flask-app,siavashg/tictail-heroku-flask-app | ---
+++
@@ -6,3 +6,6 @@
@app.route('/')
def hello():
return render_template('hello.html')
+
+if __name__ == '__main__':
+ app.run() |
f64f0b42f2d1163b2d85194e0979def539f5dca3 | Lib/fontTools/misc/intTools.py | Lib/fontTools/misc/intTools.py | __all__ = ['popCount']
def popCount(v):
"""Return number of 1 bits (population count) of an integer.
If the integer is negative, the number of 1 bits in the
twos-complement representation of the integer is returned. i.e.
``popCount(-30) == 28`` because -30 is::
1111 1111 1111 1111 1111 1111 ... | __all__ = ['popCount']
try:
bit_count = int.bit_count
except AttributeError:
def bit_count(v):
return bin(v).count('1')
"""Return number of 1 bits (population count) of the absolute value of an integer.
See https://docs.python.org/3.10/library/stdtypes.html#int.bit_count
"""
popCount = bit_count
| Consolidate bit_count / popCount methods | Consolidate bit_count / popCount methods
Fixes https://github.com/fonttools/fonttools/issues/2331
| Python | mit | googlefonts/fonttools,fonttools/fonttools | ---
+++
@@ -1,28 +1,14 @@
__all__ = ['popCount']
-def popCount(v):
- """Return number of 1 bits (population count) of an integer.
+try:
+ bit_count = int.bit_count
+except AttributeError:
+ def bit_count(v):
+ return bin(v).count('1')
- If the integer is negative, the number of 1 bits in the... |
5cb2d684ac3a0f99153cf88649b1f9d5274e4c76 | seo/escaped_fragment/app.py | seo/escaped_fragment/app.py | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escaped_fragment_="):
... | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escaped_fragment_="):
... | Enable disk cache for PhJS | Enable disk cache for PhJS
| Python | apache-2.0 | orgkhnargh/platformio-web,platformio/platformio-web,orgkhnargh/platformio-web,platformio/platformio-web,orgkhnargh/platformio-web | ---
+++
@@ -14,8 +14,10 @@
status = "500 Internal Server Error"
else:
url = "http://platformio.ikravets.com/#!" + unquote(qs[19:])
- response = check_output(["phantomjs",
- "--load-images=false", "crawler.js", url])
+ response = check_output([
+ ... |
ea887d44f7e66d48036ffa81d678311de3857271 | jsonpickle/handlers.py | jsonpickle/handlers.py | class BaseHandler(object):
"""
Abstract base class for handlers.
"""
def __init__(self, base):
"""
Initialize a new handler to handle `type`.
:Parameters:
- `base`: reference to pickler/unpickler
"""
self._base = base
def flatten(self, obj, data):... | class BaseHandler(object):
"""
Abstract base class for handlers.
"""
def __init__(self, base):
"""
Initialize a new handler to handle `type`.
:Parameters:
- `base`: reference to pickler/unpickler
"""
self._base = base
def flatten(self, obj, data):... | Remove usage of built-in 'type' name | jsonpickle.handler: Remove usage of built-in 'type' name
'type' is a built-in function so use 'cls' instead of 'type'.
Signed-off-by: David Aguilar <9de348c050f7cd1ca590883733c4e531ce610bf4@gmail.com>
| Python | bsd-3-clause | dongguangming/jsonpickle,eoghanmurray/jsonpickle_prev,dongguangming/jsonpickle,mandx/jsonpickle,mandx/jsonpickle,dongguangming/jsonpickle,mandx/jsonpickle,mandx/jsonpickle,dongguangming/jsonpickle,eoghanmurray/jsonpickle_prev | ---
+++
@@ -36,15 +36,16 @@
class Registry(object):
REGISTRY = {}
- def register(self, type, handler):
+ def register(self, cls, handler):
"""
Register handler.
:Parameters:
+ - `cls`: Object class
- `handler`: `BaseHandler` subclass
"""
- ... |
adfaff320066422734c28759688f75e3f127078c | icekit/plugins/contact_person/models.py | icekit/plugins/contact_person/models.py | import os
from django.core.urlresolvers import NoReverseMatch
from fluent_contents.models import ContentItem
from fluent_pages.urlresolvers import app_reverse, PageTypeNotMounted
from icekit.publishing.models import PublishingModel
from timezone import timezone
from django.db import models
from django.utils.encoding im... | from fluent_contents.models import ContentItem
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class ContactPerson(models.Model):
name = models.CharField(max_length=255)
title = mode... | Repair 500 viewing contact person | Repair 500 viewing contact person
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -1,18 +1,7 @@
-import os
-from django.core.urlresolvers import NoReverseMatch
from fluent_contents.models import ContentItem
-from fluent_pages.urlresolvers import app_reverse, PageTypeNotMounted
-from icekit.publishing.models import PublishingModel
-from timezone import timezone
from django.db import mo... |
79bf3254cc4690bb8c72f5214fd0c27ea8ff1c15 | pypods/loc/locdatasource.py | pypods/loc/locdatasource.py | import re
from pypods.datasource import DataSource
from pypods.loc.locchannelhandler import LocChannelHandler
class LocDataSource(DataSource):
def __init__(self):
super(LocDataSource, self).__init__()
self.channels = dict()
def create_channel(self, channel_name):
"""Creates a channel... | import re
from pypods.datasource import DataSource
from pypods.loc.locchannelhandler import LocChannelHandler
class LocDataSource(DataSource):
def __init__(self):
super(LocDataSource, self).__init__()
self.channels = dict()
def create_channel(self, channel_name):
"""Creates a channel... | Correct imports in loc package. | Correct imports in loc package.
| Python | epl-1.0 | dls-controls/PyPODS | |
92676c0e84df0e1c0d14766b339410d09c60b5fb | froide/helper/forms.py | froide/helper/forms.py | from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib.admin.widgets import ForeignKeyRawIdWidget
from taggit.forms import TagField
from taggit.utils import edit_string_for_tags
from .widgets import TagAutocompleteWidget
class TagObjectForm(forms.Form):
def __init__... | from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib.admin.widgets import ForeignKeyRawIdWidget
from taggit.forms import TagField
from taggit.utils import edit_string_for_tags
from .widgets import TagAutocompleteWidget
class TagObjectForm(forms.Form):
def __init__... | Make empty tag form valid | Make empty tag form valid | Python | mit | stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide | ---
+++
@@ -26,6 +26,7 @@
attrs={'placeholder': _('Tags')},
autocomplete_url=self.tags_autocomplete_url
),
+ required=False,
help_text=_("Comma separated and quoted")
)
|
ea20f912696974a2543a8fa15f63f0a3b64d7263 | froide/helper/utils.py | froide/helper/utils.py | from django.shortcuts import render
def get_next(request):
# This is not a view
return request.GET.get("next", request.META.get("HTTP_REFERER", "/"))
def render_code(code, request, context={}):
return render(request, "%d.html" % code, context,
status=code)
def render_400(request):
retu... | from django.shortcuts import render
def get_next(request):
# This is not a view
return request.GET.get("next", request.META.get("HTTP_REFERER", "/"))
def render_code(code, request, context={}):
return render(request, "%d.html" % code, context,
status=code)
def render_400(request):
retu... | Add utility function to get client IP from request | Add utility function to get client IP from request | Python | mit | ryankanno/froide,fin/froide,CodeforHawaii/froide,fin/froide,catcosmo/froide,LilithWittmann/froide,okfse/froide,okfse/froide,LilithWittmann/froide,ryankanno/froide,stefanw/froide,fin/froide,stefanw/froide,catcosmo/froide,okfse/froide,CodeforHawaii/froide,ryankanno/froide,stefanw/froide,catcosmo/froide,LilithWittmann/fro... | ---
+++
@@ -22,3 +22,12 @@
def render_403(request, message=''):
return render_code(403, request,
context={"message": message})
+
+
+def get_client_ip(request):
+ x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
+ if x_forwarded_for:
+ ip = x_forwarded_for.split(',')[-1].strip... |
e0385d0ba8fab48f129175123e103544574d1dac | commands.py | commands.py | #!/usr/bin/env python
from twisted.protocols import amp
from twisted.cred.error import UnauthorizedLogin
# commands to server side
class Login(amp.Command):
arguments = [("username", amp.String()), ("password", amp.String())]
response = []
errors = {UnauthorizedLogin: "UnauthorizedLogin"}
# If we set... | from twisted.protocols import amp
from twisted.cred.error import UnauthorizedLogin
# commands to server side
class Login(amp.Command):
arguments = [("username", amp.String()), ("password", amp.String())]
response = []
errors = {UnauthorizedLogin: "UnauthorizedLogin"}
# If we set requiresAnswer = False... | Remove shebang line from non-script. | Remove shebang line from non-script.
| Python | mit | dripton/ampchat | ---
+++
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-
from twisted.protocols import amp
from twisted.cred.error import UnauthorizedLogin
|
e981581e9bc1b4ac4410204dab5f7f71d1dcac79 | readthedocs/profiles/urls.py | readthedocs/profiles/urls.py | """
URLConf for Django user profile management.
Recommended usage is to use a call to ``include()`` in your project's
root URLConf to include this URLConf for any URL beginning with
'/profiles/'.
If the default behavior of the profile views is acceptable to you,
simply use a line like this in your root URLConf to set... | """
URLConf for Django user profile management.
Recommended usage is to use a call to ``include()`` in your project's
root URLConf to include this URLConf for any URL beginning with
'/profiles/'.
If the default behavior of the profile views is acceptable to you,
simply use a line like this in your root URLConf to set... | Allow periods and dashes in profile page | Allow periods and dashes in profile page
| Python | mit | dirn/readthedocs.org,nikolas/readthedocs.org,agjohnson/readthedocs.org,attakei/readthedocs-oauth,espdev/readthedocs.org,kenshinthebattosai/readthedocs.org,d0ugal/readthedocs.org,rtfd/readthedocs.org,nikolas/readthedocs.org,kenshinthebattosai/readthedocs.org,gjtorikian/readthedocs.org,davidfischer/readthedocs.org,takluy... | ---
+++
@@ -34,7 +34,7 @@
url(r'^edit/$',
views.edit_profile,
name='profiles_edit_profile'),
- url(r'^(?P<username>\w+)/$',
+ url(r'^(?P<username>[\w-.]+)/$',
views.p... |
486156f344af66fa762e6321d52e26b40c734e38 | login.py | login.py | '''
The user login module for SaltBot
'''
import requests
import os
from dotenv import load_dotenv, find_dotenv
URL_SIGNIN = 'https://www.saltybet.com/authenticate?signin=1'
def saltbot_login():
# Default the return values to None
session = None
request = None
# Start a session so we can have persist... | '''
The user login module for SaltBot
'''
import requests
import os
from dotenv import load_dotenv, find_dotenv
URL_SIGNIN = 'https://www.saltybet.com/authenticate?signin=1'
def saltbot_login():
# Default the return values to None
session = None
request = None
# Start a session so we can have persist... | Add check for Heroku before .env import | Add check for Heroku before .env import
Heroku was rightfully breaking when loadenv() was called as it already
had the proper environment variables. Add a check for Heroku before
loading the variables.
| Python | mit | Jacobinski/SaltBot | ---
+++
@@ -15,8 +15,9 @@
# Start a session so we can have persistant cookies
session = requests.session()
- # Obtain login specifics from .env
- load_dotenv(find_dotenv())
+ # Obtain login specifics from .env if running locally
+ if os.environ.get('HEROKU') is None:
+ load_dotenv(find_... |
638e9761a6a42a8ab9d8eb7996b0a19d394ad3ea | precision/accounts/urls.py | precision/accounts/urls.py | from django.conf.urls import url
from django.contrib.auth.views import login, logout, logout_then_login
from .views import SignInView
urlpatterns = [
# Authentication
# ==============
url(
regex=r'^login/$',
view=login,
name='login'
),
url(
regex=r'^logout/$',
... | from django.conf.urls import url
from django.contrib.auth.views import login, logout, logout_then_login, password_change, password_change_done
from .views import SignInView
urlpatterns = [
# Authentication
# ==============
url(
regex=r'^login/$',
view=login,
name='login'
),
... | Add password change url patterns | Add password change url patterns
| Python | mit | FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management | ---
+++
@@ -1,5 +1,5 @@
from django.conf.urls import url
-from django.contrib.auth.views import login, logout, logout_then_login
+from django.contrib.auth.views import login, logout, logout_then_login, password_change, password_change_done
from .views import SignInView
@@ -19,9 +19,23 @@
name='logout'
... |
e15029d051bbfa12dd8c01709e94e6b731b243e1 | djangopress/tests/test_templatetags.py | djangopress/tests/test_templatetags.py | """Test djangopress templatetags."""
from django.template import Template, Context
def test_archive_list_tag():
"""Test the archive_list tag."""
template_snippet = '{% load djangopress %}{% archive_list %}'
Template(template_snippet).render(Context({}))
| """Test djangopress templatetags."""
from django.template import Template, Context
from djangopress.templatetags.djangopress import archive_list
def test_archive_list_tag():
"""Test the archive_list tag."""
template_snippet = '{% load djangopress %}{% archive_list %}'
Template(template_snippet).render(Co... | Test archive_list returns a dictionary | Test archive_list returns a dictionary
| Python | mit | gilmrjc/djangopress,gilmrjc/djangopress,gilmrjc/djangopress | ---
+++
@@ -1,8 +1,16 @@
"""Test djangopress templatetags."""
from django.template import Template, Context
+
+from djangopress.templatetags.djangopress import archive_list
def test_archive_list_tag():
"""Test the archive_list tag."""
template_snippet = '{% load djangopress %}{% archive_list %}'
... |
30fa7e0137b2afae8a4b1de01fcde14bc9e7e910 | iktomi/web/shortcuts.py | iktomi/web/shortcuts.py | # -*- coding: utf-8 -*-
import json
from webob.exc import status_map
from webob import Response
from .core import cases
from . import filters
__all__ = ['redirect_to', 'http_error', 'to_json', 'Rule']
def redirect_to(endpoint, _code=303, qs=None, **kwargs):
def handle(env, data):
url = env.root.build_url(... | # -*- coding: utf-8 -*-
import json
from webob.exc import status_map
from webob import Response
from .core import cases
from . import filters
__all__ = ['redirect_to', 'http_error', 'to_json', 'Rule']
def redirect_to(endpoint, _code=303, qs=None, **kwargs):
def handle(env, data):
url = env.root.build_url(... | Fix Rule: pass convs argument to match | Fix Rule: pass convs argument to match
| Python | mit | boltnev/iktomi,oas89/iktomi,Lehych/iktomi,SmartTeleMax/iktomi,boltnev/iktomi,SlivTime/iktomi,SlivTime/iktomi,Lehych/iktomi,oas89/iktomi,oas89/iktomi,SlivTime/iktomi,Lehych/iktomi,SmartTeleMax/iktomi,boltnev/iktomi,SmartTeleMax/iktomi | ---
+++
@@ -27,7 +27,7 @@
# werkzeug-style Rule
if name is None:
name = handler.func_name
- h = filters.match(path, name)
+ h = filters.match(path, name, convs=convs)
if method is not None:
h = h | cases(filters.method(method),
http_error(405)) |
c7e65db27da59ddf221d1720362434581ef30311 | test/unit/locale/test_locale.py | test/unit/locale/test_locale.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import unittest
try:
from subprocess import check_output
except ImportError:
from subprocess import Popen, PIPE, CalledProcessError
def check_output(*popenargs, **kwargs):
"""Lifted from python 2.7 stdlib."""
if 'stdout' in kwargs:
... | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import unittest
import string
import sys
try:
from subprocess import check_output
except ImportError:
from subprocess import Popen, PIPE, CalledProcessError
def check_output(*popenargs, **kwargs):
"""Lifted from python 2.7 stdlib."""
i... | Make test_translations test our tree | Make test_translations test our tree
In order to run the correct classes, Python test framework adjusts
sys.path. However, these changes are not propagated to subprocesses.
Therefore, the test actually tries to test installed Swift, not
the one in which it is running.
The usual suggestion is to run "python setup.py d... | Python | apache-2.0 | swiftstack/swift,rackerlabs/swift,zackmdavis/swift,williamthegrey/swift,eatbyte/Swift,matthewoliver/swift,Seagate/swift,anishnarang/gswift,clayg/swift,shibaniahegde/OpenStak_swift,openstack/swift,prashanthpai/swift,matthewoliver/swift,psachin/swift,nadeemsyed/swift,AfonsoFGarcia/swift,prashanthpai/swift,smerritt/swift,... | ---
+++
@@ -3,6 +3,8 @@
import os
import unittest
+import string
+import sys
try:
from subprocess import check_output
@@ -27,15 +29,17 @@
os.environ['LC_ALL'] = 'eo'
os.environ['SWIFT_LOCALEDIR'] = os.path.dirname(__file__)
-from swift import gettext_ as _
class TestTranslations(unittest.TestCase... |
858c61a5d23685b62e590d28c896002291817bb1 | pygotham/admin/schedule.py | pygotham/admin/schedule.py | """Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = ... | """Admin for schedule-related models."""
from pygotham.admin.utils import model_view
from pygotham.schedule import models
# This line is really long because pep257 needs it to be on one line.
__all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView')
CATEGORY = 'Schedule'
DayModelView = ... | Change admin columns for slots | Change admin columns for slots
| Python | bsd-3-clause | pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,djds23/pygotham-1,djds23/pygotham-1,pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,PyGotham/pygotham,PyGotham/pygotham,pathunstrom/pygotham,pathunstrom/pygotham | ---
+++
@@ -32,6 +32,7 @@
models.Slot,
'Slots',
CATEGORY,
+ column_list=('day', 'rooms', 'kind', 'start', 'end'),
form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'),
)
|
b1a15ffe1c5f916076ac107735baf76e1da23bea | aiopg/__init__.py | aiopg/__init__.py | import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool')
__version__ = '0.3.0'
version = __version__ + ' , Python ' + sys.version
VersionI... | import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
__version__ = '0.3.0'
version = __version__ +... | Add version and version_info to exported public API | Add version and version_info to exported public API
| Python | bsd-2-clause | eirnym/aiopg,nerandell/aiopg,hyzhak/aiopg,aio-libs/aiopg,luhn/aiopg,graingert/aiopg | ---
+++
@@ -7,7 +7,8 @@
from .pool import create_pool, Pool
-__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool')
+__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
+ 'version', 'version_info')
__version__ = '0.3.0'
|
39b5378b0d52e226c410671a47934a02d18f678e | scripts/extract_pivots_from_model.py | scripts/extract_pivots_from_model.py | #!/usr/bin/env python
import sys
import numpy as np
import torch
from learn_pivots_tm import PivotLearnerModel, StraightThroughLayer
def main(args):
if len(args) < 1:
sys.stderr.write("Required arguments: <model file> [num pivots (100)]\n")
sys.exit(-1)
num_pivots = 100
if len(args) > 1:... | #!/usr/bin/env python
import sys
import numpy as np
import torch
from learn_pivots_dual_domain import PivotLearnerModel, StraightThroughLayer
def main(args):
if len(args) < 1:
sys.stderr.write("Required arguments: <model file> [num pivots (100)]\n")
sys.exit(-1)
num_pivots = 100
if len(a... | Fix import for new script location. | Fix import for new script location.
| Python | apache-2.0 | tmills/uda,tmills/uda | ---
+++
@@ -4,7 +4,7 @@
import numpy as np
import torch
-from learn_pivots_tm import PivotLearnerModel, StraightThroughLayer
+from learn_pivots_dual_domain import PivotLearnerModel, StraightThroughLayer
def main(args):
if len(args) < 1: |
8f45a3c0b5e619009984946606ea6cffec49d79d | server/mlabns/tests/test_resolver.py | server/mlabns/tests/test_resolver.py | import gflags
import unittest2
from mlabns.util import message
from mlabns.util import resolver
class ResolverTestCase(unittest2.TestCase):
def testDefaultConstructor(self):
query = resolver.LookupQuery();
self.assertEqual(None, query.tool_id)
self.assertEqual(message.POLICY_GEO, query.policy)
self... | import gflags
import unittest2
from mlabns.util import constants
from mlabns.util import message
from mlabns.util import resolver
class ResolverTestCase(unittest2.TestCase):
def testDefaultConstructor(self):
query = resolver.LookupQuery();
self.assertEqual(None, query.tool_id)
self.assertEqual(None, qu... | Update resolver tests to match new resolver | Update resolver tests to match new resolver
| Python | apache-2.0 | m-lab/mlab-ns,fernandalavalle/mlab-ns,fernandalavalle/mlab-ns,m-lab/mlab-ns,m-lab/mlab-ns,fernandalavalle/mlab-ns,fernandalavalle/mlab-ns,m-lab/mlab-ns | ---
+++
@@ -1,6 +1,7 @@
import gflags
import unittest2
+from mlabns.util import constants
from mlabns.util import message
from mlabns.util import resolver
@@ -9,14 +10,15 @@
def testDefaultConstructor(self):
query = resolver.LookupQuery();
self.assertEqual(None, query.tool_id)
- self.assertEqu... |
0173d18e2c88f4b944b3b12df2259fb0d26fee1d | drogher/shippers/dhl.py | drogher/shippers/dhl.py | from .base import Shipper
class DHL(Shipper):
barcode_pattern = r'^\d{10}$'
shipper = 'DHL'
| from .base import Shipper
class DHL(Shipper):
barcode_pattern = r'^\d{10}$'
shipper = 'DHL'
@property
def valid_checksum(self):
sequence, check_digit = self.tracking_number[:-1], self.tracking_number[-1]
return int(sequence) % 7 == int(check_digit)
| Add DHL waybill checksum validation | Add DHL waybill checksum validation
| Python | bsd-3-clause | jbittel/drogher | ---
+++
@@ -4,3 +4,8 @@
class DHL(Shipper):
barcode_pattern = r'^\d{10}$'
shipper = 'DHL'
+
+ @property
+ def valid_checksum(self):
+ sequence, check_digit = self.tracking_number[:-1], self.tracking_number[-1]
+ return int(sequence) % 7 == int(check_digit) |
a843a423e3383661a3a47da49389dbf7ec59d196 | tests/MenderAPI/__init__.py | tests/MenderAPI/__init__.py | import os
import logging
api_version = os.getenv("MENDER_API_VERSION", "0.1")
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
#logging.getLogger("paramiko").setLevel(logging.DEBUG)
logging.info("Setting api_version as: " + api_version)
import authentication
import admission
import deployments
import ar... | import os
import logging
api_version = os.getenv("MENDER_API_VERSION", "v1")
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
#logging.getLogger("paramiko").setLevel(logging.DEBUG)
logging.info("Setting api_version as: " + api_version)
import authentication
import admission
import deployments
import art... | Update integrarion tests to use new versioning schema. | MEN-963: Update integrarion tests to use new versioning schema.
Signed-off-by: Maciej Mrowiec <0c5b7bd73e5de492f16f5039ef275802502d5ce2@gmail.com>
| Python | apache-2.0 | pasinskim/integration,GregorioDiStefano/integration,GregorioDiStefano/integration,pasinskim/integration,pasinskim/integration | ---
+++
@@ -1,7 +1,7 @@
import os
import logging
-api_version = os.getenv("MENDER_API_VERSION", "0.1")
+api_version = os.getenv("MENDER_API_VERSION", "v1")
logger = logging.getLogger()
|
3ecc978421e1bcceb30635e875333e52272e07a3 | tests/providers/test_ovh.py | tests/providers/test_ovh.py | # Test for one implementation of the interface
from unittest import TestCase
from lexicon.providers.ovh import Provider
from lexicon.common.options_handler import env_auth_options
from integration_tests import IntegrationTests
# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *e... | # Test for one implementation of the interface
from unittest import TestCase
from lexicon.providers.ovh import Provider
from lexicon.common.options_handler import env_auth_options
from integration_tests import IntegrationTests
# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *e... | Select ovh-eu entrypoint for test integration | Select ovh-eu entrypoint for test integration
| Python | mit | tnwhitwell/lexicon,AnalogJ/lexicon,AnalogJ/lexicon,tnwhitwell/lexicon | ---
+++
@@ -19,5 +19,6 @@
# Override _test_options to call env_auth_options and then import auth config from env variables
def _test_options(self):
cmd_options = env_auth_options(self.provider_name)
+ cmd_options['auth_entrypoint'] = 'ovh-eu'
cmd_options['domain'] = self.domain
... |
42a6421fedadaea5f583dbccb8908b9b2df97231 | spacq/devices/lakeshore/mock/mock_tc335.py | spacq/devices/lakeshore/mock/mock_tc335.py | import random
from ...mock.mock_abstract_device import MockAbstractDevice
from ..tc335 import TC335
"""
Mock Lakeshore 335 Temperature Controller
"""
class MockTC335(MockAbstractDevice, TC335):
"""
Mock interface for Lakeshore 335 Temperature Controller.
"""
def __init__(self, *args, **kwargs):
self.mocking =... | import random
from ...mock.mock_abstract_device import MockAbstractDevice
from ..tc335 import TC335
"""
Mock Lakeshore 335 Temperature Controller
"""
class MockTC335(MockAbstractDevice, TC335):
"""
Mock interface for Lakeshore 335 Temperature Controller.
"""
def __init__(self, *args, **kwargs):
self.mocking =... | Fix a bug involving how mock_state is set | Fix a bug involving how mock_state is set
| Python | bsd-2-clause | ghwatson/SpanishAcquisitionIQC,ghwatson/SpanishAcquisitionIQC | ---
+++
@@ -15,11 +15,11 @@
def __init__(self, *args, **kwargs):
self.mocking = TC335
+ MockAbstractDevice.__init__(self, *args, **kwargs)
+
self.mock_state = {}
self.mock_state['readingstatus'] = 0
self.mock_state['read_only'] = ['temperature']
-
- MockAbstractDevice.__init__(self, *args, **kwarg... |
2c54a9eb78a1cb88ef03db97e21e376ae764a33e | errata/admin_actions.py | errata/admin_actions.py | import unicodecsv
from django.http import HttpResponse
from django.utils.encoding import smart_str
def export_as_csv_action(description="Export selected objects as CSV file",
fields=None, exclude=None, header=True):
"""
This function returns an export csv action
'fields' and 'excl... | import unicodecsv
from django.http import StreamingHttpResponse
class Echo:
"""An object that implements just the write method of the file-like
interface.
"""
def write(self, value):
"""Write the value by returning it, instead of storing in a buffer."""
return value
def export_as_csv_... | Make use of Django's StreamingHttpResponse for large CSV exports | Make use of Django's StreamingHttpResponse for large CSV exports
| Python | agpl-3.0 | Connexions/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms | ---
+++
@@ -1,7 +1,14 @@
import unicodecsv
-from django.http import HttpResponse
-from django.utils.encoding import smart_str
+from django.http import StreamingHttpResponse
+
+class Echo:
+ """An object that implements just the write method of the file-like
+ interface.
+ """
+ def write(self, value):
... |
d3c7ae5389f2fd90ae35d87f87e4f7dd01572f4a | numpy/f2py/__init__.py | numpy/f2py/__init__.py | #!/usr/bin/env python
__all__ = ['run_main','compile','f2py_testing']
import os
import sys
import commands
from info import __doc__
import f2py2e
run_main = f2py2e.run_main
main = f2py2e.main
import f2py_testing
def compile(source,
modulename = 'untitled',
extra_args = '',
verbo... | #!/usr/bin/env python
__all__ = ['run_main','compile','f2py_testing']
import os
import sys
import commands
import f2py2e
import f2py_testing
import diagnose
from info import __doc__
run_main = f2py2e.run_main
main = f2py2e.main
def compile(source,
modulename = 'untitled',
extra_args = '',
... | Add diagnose to f2py package. This makes the tests a bit easier to fix. | ENH: Add diagnose to f2py package. This makes the tests a bit easier to fix.
| Python | bsd-3-clause | ChristopherHogan/numpy,ChristopherHogan/numpy,seberg/numpy,bmorris3/numpy,njase/numpy,BabeNovelty/numpy,mhvk/numpy,tdsmith/numpy,cowlicks/numpy,MaPePeR/numpy,rmcgibbo/numpy,utke1/numpy,simongibbons/numpy,GrimDerp/numpy,shoyer/numpy,numpy/numpy-refactor,has2k1/numpy,ESSS/numpy,githubmlai/numpy,rgommers/numpy,Srisai85/nu... | ---
+++
@@ -6,12 +6,14 @@
import sys
import commands
+import f2py2e
+import f2py_testing
+import diagnose
+
from info import __doc__
-import f2py2e
run_main = f2py2e.run_main
main = f2py2e.main
-import f2py_testing
def compile(source,
modulename = 'untitled', |
bcc6d199186953b5ae05f7e93bf61c169ac89c77 | opps/archives/admin.py | opps/archives/admin.py | from django.contrib import admin
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from opps.core.admin import apply_opps_rules
from opps.contrib.multisite.admin import AdminViewPermission
from .models import File
@apply_opps_rul... | # coding: utf-8
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from opps.core.admin import apply_opps_rules
from opps.contrib.multisite.admin import AdminViewPermission
from .models import File
... | Add list_display on FileAdmin and download_link def | Add list_display on FileAdmin and download_link def
| Python | mit | YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps | ---
+++
@@ -1,3 +1,4 @@
+# coding: utf-8
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.utils import timezone
@@ -13,6 +14,7 @@
class FileAdmin(AdminViewPermission):
search_fields = ['title', 'slug']
raw_id_fields = ['user']
+ list_display = ['title', 'slu... |
71241579d678185eb315ba2658f1c7eb9ec75603 | example/django/tests.py | example/django/tests.py | from __future__ import absolute_import
from django.contrib.auth.models import User
from noseperf.testcases import DjangoPerformanceTest
class DjangoSampleTest(DjangoPerformanceTest):
def test_create_a_bunch_of_users(self):
for n in xrange(2 ** 8):
User.objects.create(username='test-%d' % n, e... | from __future__ import absolute_import
from django.core.cache import cache
from django.contrib.auth.models import User
from noseperf.testcases import DjangoPerformanceTest
class DjangoSampleTest(DjangoPerformanceTest):
def test_create_a_bunch_of_users(self):
for n in xrange(2 ** 8):
User.obje... | Add basic cache test example | Add basic cache test example
| Python | apache-2.0 | disqus/nose-performance,disqus/nose-performance | ---
+++
@@ -1,5 +1,6 @@
from __future__ import absolute_import
+from django.core.cache import cache
from django.contrib.auth.models import User
from noseperf.testcases import DjangoPerformanceTest
@@ -8,3 +9,8 @@
def test_create_a_bunch_of_users(self):
for n in xrange(2 ** 8):
User.o... |
324ce82f25c78bce7f92af52952f036ba48e72e7 | astrobin_apps_notifications/utils.py | astrobin_apps_notifications/utils.py | # Python
import simplejson
import urllib2
# Django
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
# Third party
from notification import models as notification
from persistent_messages.models import Message
def push_notification(recipients, noti... | # Python
import simplejson
import urllib2
# Django
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
# Third party
from notification import models as notification
from persistent_messages.models import Message
def push_notification(recipients, noti... | Revert "Drop extra trailing slash from notices_url" | Revert "Drop extra trailing slash from notices_url"
This reverts commit 1eb4d00e005f22ae452ce9d36b9fce69fa9b96f7.
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin | ---
+++
@@ -13,7 +13,7 @@
def push_notification(recipients, notice_type, data):
- data.update({'notices_url': settings.ASTROBIN_BASE_URL})
+ data.update({'notices_url': settings.ASTROBIN_BASE_URL + '/'})
notification.send(recipients, notice_type, data)
|
82bb5e5a6c81b2d473ec815c3b9a8e5aee154ff5 | meinberlin/apps/plans/urls.py | meinberlin/apps/plans/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<slug>[-\w_]+)/$',
views.PlanDetailView.as_view(), name='plan-detail'),
url('^export/all/$',
views.PlanExportView.as_view(), name='plan-export'),
url('^$',
views.PlanListView.as_view(), name='plan-list')... | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<slug>[-\w_]+)/$',
views.PlanDetailView.as_view(), name='plan-detail'),
url('^export/format/xslx/$',
views.PlanExportView.as_view(), name='plan-export'),
url('^$',
views.PlanListView.as_view(), name='pla... | Use format in export url | Use format in export url
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | ---
+++
@@ -5,7 +5,7 @@
urlpatterns = [
url(r'^(?P<slug>[-\w_]+)/$',
views.PlanDetailView.as_view(), name='plan-detail'),
- url('^export/all/$',
+ url('^export/format/xslx/$',
views.PlanExportView.as_view(), name='plan-export'),
url('^$',
views.PlanListView.as_view(), name=... |
2cf5041ff923fbecdcd31595d8340d12bb4d6283 | build/copy_sources.py | build/copy_sources.py | #!/usr/bin/python
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import shutil
import sys
"""Copy Sources
Copy from a source file or directory to a new file or directory. This
suppor... | #!/usr/bin/python
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import shutil
import sys
"""Copy Sources
Copy from a source file or directory to a new file or directory. This
suppor... | Add information on Copy command. | Add information on Copy command.
Adding extra information to track down mysterious mac build failures.
tbr=bradnelson@google.com
git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@9679 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2
| Python | bsd-3-clause | sbc100/native_client,nacl-webkit/native_client,sbc100/native_client,nacl-webkit/native_client,nacl-webkit/native_client,sbc100/native_client,nacl-webkit/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,nacl-webkit/native_client | ---
+++
@@ -35,6 +35,7 @@
return 1
shutil.copy(argv[1], argv[2])
+ print 'From %s to %s\n' % (argv[1], argv[2])
return 0
if __name__ == '__main__': |
efabe61cec636d5104a639b8d5cfef23eb840dd7 | apps/live/urls.py | apps/live/urls.py | # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
from .views import (AwayView, DiscussionView, EpilogueView, GameView,
NotifierView, PrologueView, StatusView)
urlpatterns = patterns('',
# Because sooner ... | # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
from .views import StatusView
urlpatterns = patterns('',
# Because sooner or later, avalonstar.tv/ will be a welcome page.
url(r'^$', name='site-home', vi... | Remove the missing view references. | Remove the missing view references.
| Python | apache-2.0 | bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv | ---
+++
@@ -3,8 +3,7 @@
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
-from .views import (AwayView, DiscussionView, EpilogueView, GameView,
- NotifierView, PrologueView, StatusView)
+from .views import StatusView
urlpatterns = patterns('', |
f64cb48d51e1bcc3879a40d308452c4e65d13439 | src/pymfony/component/system/serializer.py | src/pymfony/component/system/serializer.py | # -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
from __future__ import absolute_import;
from pickle import dumps;
from pickl... | # -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
from __future__ import absolute_import;
from pickle import dumps;
from pickl... | Use pickle protocole 2 to BC for Python2* | [System][Serializer] Use pickle protocole 2 to BC for Python2*
| Python | mit | pymfony/pymfony | ---
+++
@@ -22,9 +22,10 @@
"""
CHARSET = 'UTF-8';
+PICKLE_PROTOCOL = 2;
def serialize(obj):
- return encodebytes(dumps(obj)).decode(CHARSET).replace('\n', '');
+ return encodebytes(dumps(obj, PICKLE_PROTOCOL)).decode(CHARSET).replace('\n', '');
def unserialize(s):
return loads(decodebytes(s.encod... |
be89b2d9617fd5b837695e4322a2c98e4d4346cc | semillas_backend/users/serializers.py | semillas_backend/users/serializers.py | #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from ... | #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from ... | Add phone and email to user serializer | Add phone and email to user serializer
| Python | mit | Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform | ---
+++
@@ -16,7 +16,7 @@
class Meta:
model = User
- fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login')
+ fields = ('uuid', 'name', 'picture', 'location', 'username', 'last_login', 'email', 'phone')
class UpdateUserSerializer(serializers.ModelSerializer):
|
4cdf5be2a3c01e1b16a5e49bdf770f9d8573e16e | icekit/utils/testing.py | icekit/utils/testing.py | # USEFUL FUNCTIONS DESIGNED FOR TESTS ##############################################################
import glob
import os
import uuid
from django.core.files.base import ContentFile
from PIL import Image
from StringIO import StringIO
def new_test_image():
"""
Creates an automatically generated test image.
... | # USEFUL FUNCTIONS DESIGNED FOR TESTS ##############################################################
import glob
import os
import uuid
from PIL import Image
from django.core.files.base import ContentFile
from django.utils import six
def new_test_image():
"""
Creates an automatically generated test image.
... | Update StringIO import for Python3 compat | Update StringIO import for Python3 compat
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -2,9 +2,11 @@
import glob
import os
import uuid
+
+from PIL import Image
+
from django.core.files.base import ContentFile
-from PIL import Image
-from StringIO import StringIO
+from django.utils import six
def new_test_image():
@@ -21,7 +23,7 @@
:return: Image name and image content file.
... |
b6e393271971426506557a208be93d8b79d55cc3 | examples/image_captioning/download.py | examples/image_captioning/download.py | import argparse
import os
from six.moves.urllib import request
import zipfile
"""Download the MSCOCO dataset (images and captions)."""
urls = [
'http://images.cocodataset.org/zips/train2014.zip',
'http://images.cocodataset.org/zips/val2014.zip',
'http://images.cocodataset.org/annotations/annotations_tra... | import argparse
import os
from six.moves.urllib import request
import zipfile
"""Download the MSCOCO dataset (images and captions)."""
urls = [
'http://images.cocodataset.org/zips/train2014.zip',
'http://images.cocodataset.org/zips/val2014.zip',
'http://images.cocodataset.org/annotations/annotations_tra... | Fix error type for Python 2 | Fix error type for Python 2
| Python | mit | chainer/chainer,ktnyt/chainer,hvy/chainer,aonotas/chainer,wkentaro/chainer,tkerola/chainer,chainer/chainer,keisuke-umezawa/chainer,niboshi/chainer,okuta/chainer,niboshi/chainer,ktnyt/chainer,rezoo/chainer,jnishi/chainer,okuta/chainer,hvy/chainer,jnishi/chainer,wkentaro/chainer,hvy/chainer,wkentaro/chainer,jnishi/chaine... | ---
+++
@@ -21,8 +21,8 @@
try:
os.makedirs(args.out)
- except FileExistsError:
- raise FileExistsError(
+ except OSError:
+ raise OSError(
"'{}' already exists, delete it and try again".format(args.out))
for url in urls: |
9eec48753b2643d25d3ce1e143125b29351e0804 | features/environment.py | features/environment.py | import os
import tempfile
from flask import json
import tsserver
# If set to True, each time the test is run, new database is created as a
# temporary file. If the value is equal to False, tests will be using SQLite
# in-memory database.
USE_DB_TEMP_FILE = False
def before_scenario(context, scenario):
if USE_... | import os
import tempfile
from flask import json
import tsserver
# If set to True, each time the test is run, new database is created as a
# temporary file. If the value is equal to False, tests will be using SQLite
# in-memory database.
USE_DB_TEMP_FILE = False
def before_scenario(context, scenario):
if USE_... | Add support for arguments in request() in tests | Add support for arguments in request() in tests
| Python | mit | m4tx/techswarm-server | ---
+++
@@ -26,7 +26,7 @@
tsserver.db.create_all()
context.app = tsserver.app.test_client()
- def request(url, method='GET'):
+ def request(url, method='GET', *args, **kwargs):
"""
Wrapper over Flask.open function that parses returned data as JSON
@@ -34,7 +34,7 @@
:para... |
2d15ff38abb68335daa8bb2b94aaeff91ed829a2 | photoshell/__main__.py | photoshell/__main__.py | import os
import sys
import yaml
from photoshell import ui
config_path = os.path.join(os.environ['HOME'], '.photoshell.yaml')
with open(config_path, 'r') as config_file:
config = yaml.load(config_file)
print('Libray path is {0}'.format(config['library']))
# Open photo viewer
ui.render(config['library'])
| import os
import sys
import yaml
from photoshell import ui
config_path = os.path.join(os.environ['HOME'], '.photoshell.yaml')
config = dict(
{
'library': os.path.join(os.environ['HOME'], 'Pictures/Photoshell')
}
)
if os.path.isfile(config_path):
with open(config_path, 'r') as config_file:
... | Create default config if one doesn't exist | Create default config if one doesn't exist
Fixes #20
| Python | mit | photoshell/photoshell,SamWhited/photoshell,campaul/photoshell | ---
+++
@@ -5,11 +5,19 @@
from photoshell import ui
-
config_path = os.path.join(os.environ['HOME'], '.photoshell.yaml')
-with open(config_path, 'r') as config_file:
- config = yaml.load(config_file)
+config = dict(
+ {
+ 'library': os.path.join(os.environ['HOME'], 'Pictures/Photoshell')
+ }
+... |
20a801255ab505641e1ec0d449a4b36411c673bc | indra/tests/test_tas.py | indra/tests/test_tas.py | from nose.plugins.attrib import attr
from indra.sources.tas import process_from_web
@attr('slow')
def test_processor():
tp = process_from_web(affinity_class_limit=10)
assert tp
assert tp.statements
num_stmts = len(tp.statements)
# This is the total number of statements about human genes
assert... | from nose.plugins.attrib import attr
from indra.sources.tas import process_from_web
@attr('slow')
def test_processor():
tp = process_from_web(affinity_class_limit=10)
assert tp
assert tp.statements
num_stmts = len(tp.statements)
# This is the total number of statements about human genes
assert... | Update test for current evidence aggregation | Update test for current evidence aggregation
| Python | bsd-2-clause | sorgerlab/indra,sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,bgyori/indra,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,johnbachman/indra,johnbachman/indra,bgyori/indra | ---
+++
@@ -9,6 +9,6 @@
assert tp.statements
num_stmts = len(tp.statements)
# This is the total number of statements about human genes
- assert num_stmts == 1601159, num_stmts
- assert all(len(s.evidence) == 1 for s in tp.statements), \
- "Some statements lack evidence, or have extra evide... |
5c7c2f87330aae72e4b30be7f4a9867e51793cf6 | foosball/games/forms.py | foosball/games/forms.py | from django import forms
from django_select2.forms import ModelSelect2MultipleWidget
from django_superform import ModelFormField, SuperForm
from .models import Team, Game
from .utils import clean_team_forms
from foosball.users.models import User
class MultiPlayerWidget(ModelSelect2MultipleWidget):
model = User
... | from django import forms
from django_select2.forms import ModelSelect2MultipleWidget
from django_superform import ModelFormField, SuperForm
from .models import Team, Game
from .utils import clean_team_forms
from foosball.users.models import User
class MultiPlayerWidget(ModelSelect2MultipleWidget):
model = User
... | Change Game form score input to select | Change Game form score input to select
| Python | mit | andersinno/foosball,andersinno/foosball,andersinno/foosball,andersinno/foosball | ---
+++
@@ -30,7 +30,8 @@
model = Team
fields = ('score', 'players')
widgets = {
- 'players': MultiPlayerWidget
+ 'players': MultiPlayerWidget,
+ 'score': forms.Select(choices=((i, i) for i in range(11)))
}
|
9c1354c0d14599872e3f87ddc4eaac7dc2d8e760 | plugins/buddy/buddy.py | plugins/buddy/buddy.py | import time
import random
crontable = []
outputs = []
buddies = ["tim.jenks", "mark.simpson", "scott", "malcolm.brown", "ian.hutchinson", "jonty", "oliver.norton", "vimarsh.raina", "paul.harris", "john.bell"]
cursor = -1
def usage():
return "usage: :cow: buddy"
def commandname():
return "buddy"
def process... | import time
import random
crontable = []
outputs = []
buddies = ["tim.jenks", "mark.simpson", "scott", "malcolm.brown", "ian.hutchinson", "jonty.dawson", "oliver.norton", "vimarsh.raina", "paul.harris", "john.bell"]
cursor = -1
def usage():
return "usage: :cow: buddy"
def commandname():
return "buddy"
def ... | Update slack username for JD | Update slack username for JD
| Python | mit | eegeo/python-rtmbot | ---
+++
@@ -4,7 +4,7 @@
crontable = []
outputs = []
-buddies = ["tim.jenks", "mark.simpson", "scott", "malcolm.brown", "ian.hutchinson", "jonty", "oliver.norton", "vimarsh.raina", "paul.harris", "john.bell"]
+buddies = ["tim.jenks", "mark.simpson", "scott", "malcolm.brown", "ian.hutchinson", "jonty.dawson", "oliv... |
cfc15200ff6c96762379ddeef1aeda9e73a48c12 | pollers/alarmpoller.py | pollers/alarmpoller.py | import domotica.alarm as alarm
import logging
from poller import Poller
import s7
class AlarmPoller(Poller):
def __init__(self):
self._wasArmed = None
self._wasTriggered = None
def poll(self, s7conn):
a = alarm.Alarm(s7conn)
isArmed = a.isArmed()
logging.debug("Alarm a... | import domotica.alarm as alarm
import logging
from poller import Poller
import s7
class AlarmPoller(Poller):
def __init__(self):
self._wasArmed = None
self._wasTriggered = None
def onStateChange(self, s7conn, isArmed):
if isArmed:
logging.info("Alarm activated")
els... | Move the notification code to separate methods | Move the notification code to separate methods
Dealing with state changes is likely to become a significant bit of
code, so move it out into separate methods.
Right now we only log these events, but at least the 'alarm becomes
triggered' one is going to need to do active notification to the user(s).
| Python | bsd-2-clause | kprovost/domotica,kprovost/domotica | ---
+++
@@ -8,6 +8,23 @@
self._wasArmed = None
self._wasTriggered = None
+ def onStateChange(self, s7conn, isArmed):
+ if isArmed:
+ logging.info("Alarm activated")
+ else:
+ logging.info("Alarm deactivated")
+
+ def onTriggered(self, s7conn):
+ ala... |
f0e71bdeca1a553c05228b57366a46c25db3d632 | threema/gateway/util.py | threema/gateway/util.py | """
Utility functions.
"""
from threema.gateway.key import Key
__all__ = ('read_key_or_key_file',)
def read_key_or_key_file(key, expected_type):
# Read key file (if any)
try:
with open(key) as file:
key = file.readline().strip()
except IOError:
pass
# Convert to key insta... | """
Utility functions.
"""
from threema.gateway.key import Key
__all__ = ('read_key_or_key_file',)
def read_key_or_key_file(key, expected_type):
"""
Decode a hex-encoded key or read it from a file.
Arguments:
- `key`: A hex-encoded key or the name of a file which contains
a key.
... | Add missing docstring for read_key_or_key_file | Add missing docstring for read_key_or_key_file
| Python | mit | lgrahl/threema-msgapi-sdk-python,threema-ch/threema-msgapi-sdk-python | ---
+++
@@ -7,6 +7,17 @@
def read_key_or_key_file(key, expected_type):
+ """
+ Decode a hex-encoded key or read it from a file.
+
+ Arguments:
+ - `key`: A hex-encoded key or the name of a file which contains
+ a key.
+ - `expected_type`: One of the types of :class:`Key.Type`.
+
+... |
fcb86792af4738ade1422f996397d8b96f0c54c5 | scripts/mc_add_observation.py | scripts/mc_add_observation.py | #! /usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2017 the HERA Collaboration
# Licensed under the 2-clause BSD license.
import os
import numpy as np
from astropy.time import Time
from pyuvdata import UVData
from hera_mc import mc
a = mc.get_mc_argument_parser()
a.description = """Read the ob... | #! /usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2017 the HERA Collaboration
# Licensed under the 2-clause BSD license.
import numpy as np
from astropy.time import Time
from pyuvdata import UVData
from hera_mc import mc
a = mc.get_mc_argument_parser()
a.description = """Read the obsid from a... | Fix flake8 issue and fix up documentation | Fix flake8 issue and fix up documentation
| Python | bsd-2-clause | HERA-Team/hera_mc,HERA-Team/hera_mc,HERA-Team/Monitor_and_Control | ---
+++
@@ -3,7 +3,6 @@
# Copyright 2017 the HERA Collaboration
# Licensed under the 2-clause BSD license.
-import os
import numpy as np
from astropy.time import Time
@@ -14,7 +13,7 @@
a = mc.get_mc_argument_parser()
a.description = """Read the obsid from a file and create a record in M&C."""
a.add_argumen... |
70441c75eacd3e71c5e3a0f4db1cc0712729e50f | Python/pizza/pizza_roulette.py | Python/pizza/pizza_roulette.py | #!/usr/bin/env python
import codecs
import random
import os
dirname = os.path.dirname(os.path.realpath(__file__))
MIN_INGRED = 2
MAX_INGRED = 8
filename = dirname + "/vegetarian"
with open(filename) as ingredients:
content = ingredients.read().splitlines()
roulette_result = []
roulette_tries = random.randin... | #!/usr/bin/env python
import codecs
import random
import os
import sys
dirname = os.path.dirname(os.path.realpath(__file__))
MIN_INGRED = 2
MAX_INGRED = 8
filename = dirname + "/vegetarian"
with open(filename) as ingredients:
content = ingredients.read().splitlines()
if "meat" in sys.argv :
filename = d... | Add option to get meat | Add option to get meat
| Python | mit | hjorthjort/scripts,hjorthjort/scripts | ---
+++
@@ -3,6 +3,7 @@
import codecs
import random
import os
+import sys
dirname = os.path.dirname(os.path.realpath(__file__))
MIN_INGRED = 2
@@ -11,6 +12,11 @@
filename = dirname + "/vegetarian"
with open(filename) as ingredients:
content = ingredients.read().splitlines()
+
+if "meat" in sys.argv ... |
70a997c2991ea306a40054be8e2e93361ef9c702 | src/globus_sdk/services/gcs/errors.py | src/globus_sdk/services/gcs/errors.py | from typing import Any, List, Optional, Union
import requests
from globus_sdk import exc
class GCSAPIError(exc.GlobusAPIError):
"""
Error class for the GCS Manager API client
"""
def __init__(self, r: requests.Response) -> None:
self.detail_data_type: Optional[str] = None
self.detai... | from typing import Any, List, Optional, Union
import requests
from globus_sdk import exc
class GCSAPIError(exc.GlobusAPIError):
"""
Error class for the GCS Manager API client
"""
def __init__(self, r: requests.Response) -> None:
self.detail_data_type: Optional[str] = None
self.detai... | Add a missing isinstance check to pacify pyright | Add a missing isinstance check to pacify pyright
pyright (correctly) complains that we use `detail["DATA_TYPE"]` in GCS
error parsing without knowing that `detail` is a type which supports
strings in `__getitem__`.
Check if `detail` is a dict before indexing into it.
| Python | apache-2.0 | globus/globus-sdk-python,globus/globus-sdk-python,sirosen/globus-sdk-python | ---
+++
@@ -29,5 +29,5 @@
# detail can be a full document, so fetch, then look for a DATA_TYPE
# and expose it as a top-level attribute for easy access
self.detail = data.get("detail")
- if self.detail and "DATA_TYPE" in self.detail:
+ if isinstance(self.detail, dict) and "DAT... |
13ffdb0cb455bf32a10d055e6e972c0ca725557a | src/mmw/apps/home/views.py | src/mmw/apps/home/views.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from rest_framework import serializers, viewsets
# Serializers define the API representatio... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.template.context_processors import csrf
from rest_framework import serializers, v... | Return a csrf token on the homepage. | Return a csrf token on the homepage.
We were not setting a CSRF token on the homepage. This meant that requests to
API endpoints did not have a token available. This change sets the token
immediatley as part of the cookie. Ajax calls can then use this value.
| Python | apache-2.0 | WikiWatershed/model-my-watershed,kdeloach/model-my-watershed,kdeloach/model-my-watershed,mmcfarland/model-my-watershed-1,lewfish/model-my-watershed,WikiWatershed/model-my-watershed,lliss/model-my-watershed,lewfish/model-my-watershed,mmcfarland/model-my-watershed-1,lewfish/model-my-watershed,WikiWatershed/model-my-water... | ---
+++
@@ -5,6 +5,7 @@
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
+from django.template.context_processors import csrf
from rest_framework import serializers, viewsets
@@ -22,7 +23,10 @@
def home_page(request):
- return render_to_response('home/home.h... |
a1a312dc71cd7b32a0d39f85a9b2fe45ee57892c | setup.py | setup.py | import os
from setuptools import setup
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='pykismet3',
version='0.1.0',
description='A Python 3 module for the Akismet spam comment-spam-dete... | import os
from setuptools import setup
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='pykismet3',
version='0.1.0',
description='A Python 3 module for the Akismet spam comment-spam-dete... | Add dependency on requets module. | Add dependency on requets module. | Python | mit | grundleborg/pykismet3 | ---
+++
@@ -29,4 +29,5 @@
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
+ install_requires=[ "requests", ],
) |
14ea1e8ade33d42497d6ca9d11ca9b1c2b00614b | setup.py | setup.py | #!/usr/bin/env python
from __future__ import with_statement
from setuptools import setup, find_packages
from buildkit import *
META = get_metadata('neuemux/version.py')
setup(
name='neuemux',
version=META['version'],
description='EPP reverse proxy daemons',
long_description=read('README'),
url... | #!/usr/bin/env python
from __future__ import with_statement
from setuptools import setup, find_packages
from buildkit import *
META = get_metadata('neuemux/version.py')
setup(
name='neuemux',
version=META['version'],
description='EPP reverse proxy daemons',
long_description=read('README'),
url... | Add missing entry points and classifiers. | Add missing entry points and classifiers.
| Python | mit | kgaughan/neuemux | ---
+++
@@ -23,13 +23,20 @@
entry_points={
'console_scripts': [
+ 'epp-proxyd = neuemux.proxyd:main',
+ 'epp-muxd = neuemux.muxd:main',
],
},
classifiers=[
+ 'Development Status :: 2 - Pre-Alpha',
+ 'Environment :: No Input/Output (Daemon)',
+ ... |
247419dce957ad1fa8c1c61a0e13d857b0d8f038 | setup.py | setup.py | #!/usr/bin/python
try:
from setuptools import setup, Extension
has_setuptools = True
except ImportError:
from distutils.core import setup, Extension
has_setuptools = False
version_string = '0.0.1'
setup_kwargs = {}
# Requirements
install_requires = [
# PyPi
# Non PyPi
]
dependency_links = ... | #!/usr/bin/python
try:
from setuptools import setup, Extension
has_setuptools = True
except ImportError:
from distutils.core import setup, Extension
has_setuptools = False
version_string = '0.0.1'
setup_kwargs = {}
# Requirements
install_requires = [
# PyPi
# Non PyPi
]
dependency_links = ... | Change PyPi name to giturlparse.py | Change PyPi name to giturlparse.py
| Python | apache-2.0 | FriendCode/giturlparse.py,yakky/giturlparse.py,yakky/giturlparse | ---
+++
@@ -21,7 +21,7 @@
dependency_links = [
]
-setup(name='giturlparse',
+setup(name='giturlparse.py',
description='A Git URL parsing module (supports parsing and rewriting)',
keywords='git url parse ssh github bitbucket',
version=version_string, |
ed731480d0266b0158232bd1c7acda97d4f43ba7 | setup.py | setup.py | from setuptools import setup
setup(
name='django-directed-edge',
version='2.0.1',
packages=(
'django_directed_edge',
),
url='https://chris-lamb.co.uk/projects/django-directed-edge',
author="Chris Lamb",
author_email="chris@chris-lamb.co.uk",
description="Helpful Django-oriented ... | from setuptools import setup
setup(
name='django-directed-edge',
version='2.0.1',
packages=(
'django_directed_edge',
),
url='https://chris-lamb.co.uk/projects/django-directed-edge',
author="Chris Lamb",
author_email="chris@chris-lamb.co.uk",
description="Helpful Django-oriented ... | Update Django requirement to latest LTS | Update Django requirement to latest LTS
| Python | bsd-3-clause | lamby/django-directed-edge | ---
+++
@@ -10,4 +10,8 @@
author="Chris Lamb",
author_email="chris@chris-lamb.co.uk",
description="Helpful Django-oriented sugar around around DirectedEdge's Python API",
+
+ install_requires=(
+ 'Django>=1.8',
+ ),
) |
b887ce4b8ffdd25f4a8d3dc4f81bc7fa340272ae | setup.py | setup.py | # 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 applica... | # 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 applica... | Fix a https url issue | Fix a https url issue
Change-Id: I2d2794209620c823f0aef9549f8ee43aa4c91dff
| Python | apache-2.0 | openstack/senlin,openstack/senlin,openstack/senlin,stackforge/senlin,stackforge/senlin | ---
+++
@@ -18,7 +18,7 @@
# In python < 2.7.4, a lazy loading of package `pbr` will break
# setuptools if some other modules registered functions in `atexit`.
-# solution from: http://bugs.python.org/issue15881#msg170215
+# solution from: https://bugs.python.org/issue15881#msg170215
try:
import multiprocess... |
6fd16f646712d3648b52c7b1c3ca3380e29d87fd | setup.py | setup.py | #!/usr/bin/python
from setuptools import setup
setup(name='libhxl',
version='2.7',
description='Python support for the Humanitarian Exchange Language (HXL).',
author='David Megginson',
author_email='contact@megginson.com',
url='http://hxlproject.org',
install_requires=['python-date... | #!/usr/bin/python
from setuptools import setup
setup(name='libhxl',
version='2.7.1',
description='Python support for the Humanitarian Exchange Language (HXL).',
author='David Megginson',
author_email='contact@megginson.com',
url='http://hxlproject.org',
install_requires=['python-da... | Make sure we install the csv file, still. | Make sure we install the csv file, still.
| Python | unlicense | HXLStandard/libhxl-python,HXLStandard/libhxl-python | ---
+++
@@ -3,13 +3,15 @@
from setuptools import setup
setup(name='libhxl',
- version='2.7',
+ version='2.7.1',
description='Python support for the Humanitarian Exchange Language (HXL).',
author='David Megginson',
author_email='contact@megginson.com',
url='http://hxlproject.o... |
0f881802b7ce7e19a16b70b88b480eeb30a0affd | setup.py | setup.py | #!/usr/bin/env python2
from setuptools import setup
setup(name="sagbescheid",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["sagbescheid", "sagbescheid.notifiers"],
package_dir={"sagbescheid": "sagbescheid"},
download_url="https://github.com/mineo/sagbescheid/ta... | #!/usr/bin/env python2
from setuptools import setup
setup(name="sagbescheid",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["sagbescheid", "sagbescheid.notifiers"],
package_dir={"sagbescheid": "sagbescheid"},
download_url="https://github.com/mineo/sagbescheid/ta... | Install six for Python 2 & 3 compatibility | Install six for Python 2 & 3 compatibility
| Python | mit | mineo/sagbescheid,mineo/sagbescheid | ---
+++
@@ -23,7 +23,8 @@
"automat==0.7.0",
"zope.interface==4.6.0",
"systemd-python==234",
- "enum34==1.1.6;python_version<'3.4'"],
+ "enum34==1.1.6;python_version<'3.4'",
+ ... |
a5b7416eed78cb708b1139f1e21d0b193d8a0623 | setup.py | setup.py | from setuptools import setup
setup(name='MaxwellBloch',
version='0.3.0.dev',
description='A Python package for solving the Maxwell-Bloch equations.',
url='http://github.com/tommyogden/maxwellbloch',
author='Thomas P Ogden',
author_email='t@ogden.eu',
license='MIT',
packages=['... | from setuptools import setup
import subprocess
# Semantic versioning
MAJOR = 0
MINOR = 3
PATCH = 0
IS_RELEASED = False
VERSION = '{0}.{1}.{2}'.format(MAJOR, MINOR, PATCH)
def git_short_hash():
""" Returns the short hash of the latest git commit as a string. """
git_str = subprocess.check_output(['git', 'log... | Add git short hash to unreleased version numbers | Add git short hash to unreleased version numbers
| Python | mit | tommyogden/maxwellbloch,tommyogden/maxwellbloch | ---
+++
@@ -1,7 +1,27 @@
from setuptools import setup
+import subprocess
+
+# Semantic versioning
+MAJOR = 0
+MINOR = 3
+PATCH = 0
+IS_RELEASED = False
+
+VERSION = '{0}.{1}.{2}'.format(MAJOR, MINOR, PATCH)
+
+def git_short_hash():
+ """ Returns the short hash of the latest git commit as a string. """
+
+ git_... |
80e0b7eb034794120518f29932ab23c67047559a | setup.py | setup.py | from setuptools import setup
setup(
name='tangled.session',
version='0.1a3.dev0',
description='Tangled session integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.session/tags',
author='Wyatt Bald... | from setuptools import setup
setup(
name='tangled.session',
version='0.1a3.dev0',
description='Tangled session integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.session/tags',
author='Wyatt Bald... | Upgrade Beaker 1.6.4 => 1.8.1 | Upgrade Beaker 1.6.4 => 1.8.1
| Python | mit | TangledWeb/tangled.session | ---
+++
@@ -16,8 +16,8 @@
'tangled.session.tests',
],
install_requires=[
- 'Beaker>=1.6.4',
'tangled>=0.1a9',
+ 'Beaker>=1.8.1',
],
extras_require={
'dev': [ |
006380832d1f45c6c1c4ffad9356e7ed2399d681 | setup.py | setup.py | #!/usr/bin/env python
import io
from setuptools import setup, Extension
with io.open('README.rst', encoding='utf8') as readme:
long_description = readme.read()
setup(
name="pyspamsum",
version="1.0.5",
description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
long_description=long... | #!/usr/bin/env python
import io
from setuptools import setup, Extension
with io.open('README.rst', encoding='utf8') as readme:
long_description = readme.read()
setup(
name="pyspamsum",
version="1.0.5",
description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
long_description=long... | Add a content type description to keep twine happy. | Add a content type description to keep twine happy.
| Python | bsd-3-clause | freakboy3742/pyspamsum,freakboy3742/pyspamsum | ---
+++
@@ -13,6 +13,7 @@
version="1.0.5",
description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
long_description=long_description,
+ long_description_content_type='text/x-rst',
author="Russell Keith-Magee",
author_email="russell@keith-magee.com",
url='http://github.... |
650d6c72054ac5cd406af8a37e45d0349cf521dc | students/psbriant/final_project/test_clean_data.py | students/psbriant/final_project/test_clean_data.py | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data.py as cd
import io
| Add organizational structure and import calls to clean_data.py and io. | Add organizational structure and import calls to clean_data.py and io.
| Python | unlicense | weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016 | ---
+++
@@ -0,0 +1,12 @@
+"""
+Name: Paul Briant
+Date: 12/11/16
+Class: Introduction to Python
+Assignment: Final Project
+
+Description:
+Tests for Final Project
+"""
+
+import clean_data.py as cd
+import io | |
276f22927890051f66976468585d8351c0ccf5b9 | sum-of-multiples/sum_of_multiples.py | sum-of-multiples/sum_of_multiples.py | def sum_of_multiples(limit, factors):
return sum(filter(lambda n: n < limit,
{f*i for i in range(1, limit) for f in factors}))
| def sum_of_multiples(limit, factors):
return sum({n for f in factors for n in range(f, limit, f)})
| Use more optimal method of getting multiples | Use more optimal method of getting multiples
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,3 +1,2 @@
def sum_of_multiples(limit, factors):
- return sum(filter(lambda n: n < limit,
- {f*i for i in range(1, limit) for f in factors}))
+ return sum({n for f in factors for n in range(f, limit, f)}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.