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 |
|---|---|---|---|---|---|---|---|---|---|---|
a2d3c2e0391d2deeb1d6729567c2d8812ad7e7df | exam/asserts.py | exam/asserts.py | irrelevant = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', irrelevant)
self.expected_after = kwargs.pop('after', irrelevant)
def __... | IRRELEVANT = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', IRRELEVANT)
self.expected_after = kwargs.pop('after', IRRELEVANT)
def __... | Make the irrelevant object a constant | Make the irrelevant object a constant
| Python | mit | Fluxx/exam,gterzian/exam,Fluxx/exam,gterzian/exam | ---
+++
@@ -1,4 +1,4 @@
-irrelevant = object()
+IRRELEVANT = object()
class ChangeWatcher(object):
@@ -7,20 +7,20 @@
self.thing = thing
self.args = args
self.kwargs = kwargs
- self.expected_before = kwargs.pop('before', irrelevant)
- self.expected_after = kwargs.pop('afte... |
ba13537cf18b8bced21544866fcdcc887e1d290d | latex/exc.py | latex/exc.py | import os
from .errors import parse_log
class LatexError(Exception):
pass
class LatexBuildError(LatexError):
"""LaTeX call exception."""
def __init__(self, logfn=None):
if os.path.exists(logfn):
self.log = open(logfn).read()
else:
self.log = None
def __str_... | import os
from .errors import parse_log
class LatexError(Exception):
pass
class LatexBuildError(LatexError):
"""LaTeX call exception."""
def __init__(self, logfn=None):
if os.path.exists(logfn):
# the binary log is probably latin1 or utf8?
# utf8 throws errors occasiona... | Fix latexs output encoding to latin1. | Fix latexs output encoding to latin1.
| Python | bsd-3-clause | mbr/latex | ---
+++
@@ -12,7 +12,11 @@
def __init__(self, logfn=None):
if os.path.exists(logfn):
- self.log = open(logfn).read()
+ # the binary log is probably latin1 or utf8?
+ # utf8 throws errors occasionally, so we try with latin1
+ # and ignore invalid chars
+ ... |
1cdb773f0d20dcdb1a66a4a6a52eff35398b1296 | getBlocks.py | getBlocks.py | #!/usr/bin/python
import subprocess
import argparse
def readArguments():
parser = argparse.ArgumentParser()
parser.add_argument('-f','--file', action="store", dest="file", required=True, help="File to shred")
args = parser.parse_args()
return args
def checkFile(file):
'''
Check if file exist in HDFS
''... | #!/usr/bin/python
import subprocess
import shlex
import argparse
def readArguments():
parser = argparse.ArgumentParser()
parser.add_argument('-f','--file', action="store", dest="file", required=True, help="File to shred")
args = parser.parse_args()
return args
def checkFile(file):
'''
Check if file exist... | Use shlex to split command line | Use shlex to split command line
| Python | apache-2.0 | monolive/hdfs-shred | ---
+++
@@ -1,6 +1,7 @@
#!/usr/bin/python
import subprocess
+import shlex
import argparse
def readArguments():
@@ -14,8 +15,9 @@
Check if file exist in HDFS
'''
command = "hdfs fsck -stat " + file
- subprocess.check_call(command)
-
+ cmd = shlex.split(command)
+ print cmd
+ subprocess.check_call(... |
fc1cb951991cc9b4b0cdb9d533127d26eb21ea57 | rave/__main__.py | rave/__main__.py | import argparse
import sys
from os import path
def parse_arguments():
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parse... | import argparse
import sys
from os import path
def parse_arguments():
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parse... | Remove -d command line argument in favour of __debug__. | rave: Remove -d command line argument in favour of __debug__.
| Python | bsd-2-clause | rave-engine/rave | ---
+++
@@ -7,7 +7,6 @@
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parser.add_argument('-B', '--game-bootstrapper',... |
cb2db952d3a6c651dac5a285e8b0dc01a5e12a4b | rules/arm-toolchain.py | rules/arm-toolchain.py | import xyz
class ArmToolchain(xyz.BuildProtocol):
group_only = True
pkg_name = 'arm-toolchain'
supported_targets = ['arm-none-eabi']
deps = [('gcc', {'target': 'arm-none-eabi'}),
('binutils', {'target': 'arm-none-eabi'})]
rules = ArmToolchain()
| import xyz
class ArmToolchain(xyz.BuildProtocol):
group_only = True
pkg_name = 'arm-toolchain'
supported_targets = ['arm-none-eabi']
deps = [('gcc', {'target': 'arm-none-eabi'}),
('binutils', {'target': 'arm-none-eabi'}),
('gdb', {'target': 'arm-none-eabi'})
]
rules... | Add gdb to the toolchain | Add gdb to the toolchain
| Python | mit | BreakawayConsulting/xyz | ---
+++
@@ -5,6 +5,8 @@
pkg_name = 'arm-toolchain'
supported_targets = ['arm-none-eabi']
deps = [('gcc', {'target': 'arm-none-eabi'}),
- ('binutils', {'target': 'arm-none-eabi'})]
+ ('binutils', {'target': 'arm-none-eabi'}),
+ ('gdb', {'target': 'arm-none-eabi'})
+ ... |
545171378864d4d80aeef52bd036ed99f18aadfc | tests/testdata/amazon.py | tests/testdata/amazon.py |
AWS_SECRET_ACCESS_KEY = 'A8+6AN5TSUZ3vysJg68Rt\A9E7duMlfKODwb3ZD8'
|
AWS_SECRET_ACCESS_KEY = r'A8+6AN5TSUZ3vysJg68Rt\A9E7duMlfKODwb3ZD8'
| Fix deprecation warnings due to invalid escape sequences. | Fix deprecation warnings due to invalid escape sequences.
| Python | mit | landscapeio/dodgy | ---
+++
@@ -1,2 +1,2 @@
-AWS_SECRET_ACCESS_KEY = 'A8+6AN5TSUZ3vysJg68Rt\A9E7duMlfKODwb3ZD8'
+AWS_SECRET_ACCESS_KEY = r'A8+6AN5TSUZ3vysJg68Rt\A9E7duMlfKODwb3ZD8' |
da3599ac6ed29e750d28834a8c0c0f39e9b57702 | src/acquisition/covid_hosp/state_daily/network.py | src/acquisition/covid_hosp/state_daily/network.py | # first party
from delphi.epidata.acquisition.covid_hosp.common.network import Network as BaseNetwork
class Network(BaseNetwork):
DATASET_ID = '823dd0e-c8c4-4206-953e-c6d2f451d6ed'
def fetch_metadata(*args, **kwags):
"""Download and return metadata.
See `fetch_metadata_for_dataset`.
"""
return... | # first party
from delphi.epidata.acquisition.covid_hosp.common.network import Network as BaseNetwork
class Network(BaseNetwork):
DATASET_ID = '7823dd0e-c8c4-4206-953e-c6d2f451d6ed'
def fetch_metadata(*args, **kwags):
"""Download and return metadata.
See `fetch_metadata_for_dataset`.
"""
retur... | Update state daily dataset ID | Update state daily dataset ID
| Python | mit | cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata | ---
+++
@@ -4,7 +4,7 @@
class Network(BaseNetwork):
- DATASET_ID = '823dd0e-c8c4-4206-953e-c6d2f451d6ed'
+ DATASET_ID = '7823dd0e-c8c4-4206-953e-c6d2f451d6ed'
def fetch_metadata(*args, **kwags):
"""Download and return metadata. |
29cc59bc478c4c6bc936141d19a3386468ff8f07 | tests/test_general_attributes.py | tests/test_general_attributes.py | # -*- coding: utf-8 -*-
from jawa.attribute import get_attribute_classes
def test_mandatory_attributes():
for parser_class in get_attribute_classes().values():
assert hasattr(parser_class, 'ADDED_IN'), (
'Attribute parser missing mandatory ADDED_IN property'
)
assert hasattr(pa... | # -*- coding: utf-8 -*-
from jawa.attribute import get_attribute_classes
def test_mandatory_attributes():
required_properities = ['ADDED_IN', 'MINIMUM_CLASS_VERSION']
for name, class_ in get_attribute_classes().items():
for p in required_properities:
assert hasattr(class_, p), (
... | Add a simple test for Attribuet class naming conventions. | Add a simple test for Attribuet class naming conventions.
| Python | mit | TkTech/Jawa,TkTech/Jawa | ---
+++
@@ -3,11 +3,23 @@
def test_mandatory_attributes():
- for parser_class in get_attribute_classes().values():
- assert hasattr(parser_class, 'ADDED_IN'), (
- 'Attribute parser missing mandatory ADDED_IN property'
+ required_properities = ['ADDED_IN', 'MINIMUM_CLASS_VERSION']
+ for... |
3be25f88352ff20a3239b0647f437c45f4903008 | robotpy_ext/control/button_debouncer.py | robotpy_ext/control/button_debouncer.py | import wpilib
class ButtonDebouncer:
'''Useful utility class for debouncing buttons'''
def __init__(self, joystick, buttonnum, period=0.5):
'''
:param joystick: Joystick object
:type joystick: :class:`wpilib.Joystick`
:param buttonnum: Number of button to retrieve
... | import wpilib
class ButtonDebouncer:
'''Useful utility class for debouncing buttons'''
def __init__(self, joystick, buttonnum, period=0.5):
'''
:param joystick: Joystick object
:type joystick: :class:`wpilib.Joystick`
:param buttonnum: Number of button to retrieve
... | Add __bool__ redirect to buttondebounce | Add __bool__ redirect to buttondebounce
| Python | bsd-3-clause | robotpy/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities | ---
+++
@@ -34,3 +34,5 @@
self.latest = now
return True
return False
+
+ __bool__ = get |
d8dd87f6f5bd1bdead9f2b77ec9271035d05a378 | snappybouncer/admin.py | snappybouncer/admin.py | from django.contrib import admin
from snappybouncer.models import Conversation, UserAccount, Ticket
admin.site.register(Conversation)
admin.site.register(UserAccount)
admin.site.register(Ticket)
| from django.contrib import admin
from snappybouncer.models import Conversation, UserAccount, Ticket
from control.actions import export_select_fields_csv_action
class TicketAdmin(admin.ModelAdmin):
actions = [export_select_fields_csv_action(
"Export selected objects as CSV file",
fields = [
... | Add download to snappy bouncer | Add download to snappy bouncer
| Python | bsd-3-clause | praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control | ---
+++
@@ -1,6 +1,21 @@
from django.contrib import admin
from snappybouncer.models import Conversation, UserAccount, Ticket
+from control.actions import export_select_fields_csv_action
+
+class TicketAdmin(admin.ModelAdmin):
+ actions = [export_select_fields_csv_action(
+ "Export selected objects as CSV ... |
c9284e4d36026b837f1a43a58100b434e7a57337 | 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 = ... | Use version of slots admin already in production | Use version of slots admin already in production
While building the schedule for the conference, the admin view for
`schedule.models.Slot` was changed in production* to figure out what
implementation made the most sense. This formalizes it as the preferred
version.
Closes #111
*Don't do this at home.
| Python | bsd-3-clause | djds23/pygotham-1,PyGotham/pygotham,djds23/pygotham-1,PyGotham/pygotham,djds23/pygotham-1,PyGotham/pygotham,PyGotham/pygotham,pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,pathunstrom/pygotham,pathunstrom/pygotham,pathunstrom/pygotham,pathunstrom/pygotham,djds23/pygotham-1 | ---
+++
@@ -33,7 +33,11 @@
'Slots',
CATEGORY,
column_default_sort='start',
- column_list=('day', 'rooms', 'kind', 'start', 'end'),
+ column_filters=('day',),
+ column_list=(
+ 'day', 'rooms', 'kind', 'start', 'end', 'presentation',
+ 'content_override',
+ ),
form_columns=... |
c84f14d33f9095f2d9d8919a9b6ba11e17acd4ca | txspinneret/test/util.py | txspinneret/test/util.py | from twisted.web import http
from twisted.web.test.requesthelper import DummyRequest
class InMemoryRequest(DummyRequest):
"""
In-memory `IRequest`.
"""
def redirect(self, url):
self.setResponseCode(http.FOUND)
self.setHeader(b'location', url)
| from twisted.web import http
from twisted.web.http_headers import Headers
from twisted.web.test.requesthelper import DummyRequest
class InMemoryRequest(DummyRequest):
"""
In-memory `IRequest`.
"""
def __init__(self, *a, **kw):
DummyRequest.__init__(self, *a, **kw)
# This was only adde... | Make `InMemoryRequest` work on Twisted<14.0.0 | Make `InMemoryRequest` work on Twisted<14.0.0
| Python | mit | jonathanj/txspinneret,mithrandi/txspinneret | ---
+++
@@ -1,4 +1,5 @@
from twisted.web import http
+from twisted.web.http_headers import Headers
from twisted.web.test.requesthelper import DummyRequest
@@ -7,6 +8,13 @@
"""
In-memory `IRequest`.
"""
+ def __init__(self, *a, **kw):
+ DummyRequest.__init__(self, *a, **kw)
+ # Th... |
be670eb5830a873d21e4e8587600a75018f01939 | collection_pipelines/__init__.py | collection_pipelines/__init__.py | from collection_pipelines.http import http
from collection_pipelines.json import *
class cat(CollectionPipelineProcessor):
def __init__(self, fname):
self.fname = fname
self.source(self.make_generator)
def make_generator(self):
with open(self.fname, 'r') as f:
for line in ... | from collection_pipelines.http import http
from collection_pipelines.json import *
class cat(CollectionPipelineProcessor):
def __init__(self, fname):
self.fname = fname
self.source(self.make_generator)
def make_generator(self):
with open(self.fname, 'r') as f:
for line in ... | Update out() processor to extend CollectionPipelineOutput class | Update out() processor to extend CollectionPipelineOutput class
| Python | mit | povilasb/pycollection-pipelines | ---
+++
@@ -23,12 +23,9 @@
self.receiver.send(item)
-class out(CollectionPipelineProcessor):
+class out(CollectionPipelineOutput):
def process(self, item):
print(item)
-
- def source(self, start_source):
- start_source()
class count(CollectionPipelineProcessor): |
915370a5950bcaee4b7037196ef02621e518dcd9 | rcamp/lib/views.py | rcamp/lib/views.py | from django.shortcuts import render_to_response
from django.shortcuts import render
from django.template import RequestContext
from django.shortcuts import redirect
def handler404(request):
return render(request, '404.html', {}, status=404)
def handler500(request):
return render(request, '500.html', {}, sta... | from django.shortcuts import render_to_response
from django.shortcuts import render
from django.template import RequestContext
from django.shortcuts import redirect
def handler404(request, exception=None):
return render(request, '404.html', {}, status=404)
def handler500(request):
return render(request, '50... | Fix 404 handler not handling exception argument | Fix 404 handler not handling exception argument
| Python | mit | ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP | ---
+++
@@ -4,7 +4,7 @@
from django.shortcuts import redirect
-def handler404(request):
+def handler404(request, exception=None):
return render(request, '404.html', {}, status=404)
|
d07722c8e7cc2efa0551830ca424d2db2bf734f3 | app/__init__.py | app/__init__.py | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from config import config
bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
l... | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from helpers.text import slugify
from config import config
bootstrap = Bootstrap()
db = SQLAlchemy(... | Add slugify to the jinja2's globals scope | Add slugify to the jinja2's globals scope
| Python | mit | finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is | ---
+++
@@ -3,6 +3,8 @@
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
+
+from helpers.text import slugify
from config import config
@@ -15,6 +17,7 @@
def create_app(config_name):
app = Flask(__name__)... |
6067e96b0c5462f9d3e9391cc3193a28ba7ad808 | DebianChangesBot/mailparsers/security_announce.py | DebianChangesBot/mailparsers/security_announce.py |
from DebianChangesBot import MailParser
class SecurityAnnounce(MailParser):
def parse(self, msg):
if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>':
return False
fmt = SecurityAnnounceFormatter()
data = {
'dsa_number' : None,
... |
from DebianChangesBot import MailParser
class SecurityAnnounce(MailParser):
def parse(self, msg):
if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>':
return None
fmt = SecurityAnnounceFormatter()
m = re.match(r'^\[SECURITY\] \[DSA ([-\d]+)\]... | Make formatter example more realistic | Make formatter example more realistic
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
| Python | agpl-3.0 | lamby/debian-devel-changes-bot,lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,sebastinas/debian-devel-changes-bot,lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot | ---
+++
@@ -5,34 +5,18 @@
def parse(self, msg):
if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>':
- return False
+ return None
fmt = SecurityAnnounceFormatter()
-
- data = {
- 'dsa_number' : None,
- 'pack... |
2c1d40030f19356bdac6117d1df6dc35a475e480 | vcr_unittest/testcase.py | vcr_unittest/testcase.py | from __future__ import absolute_import, unicode_literals
import inspect
import logging
import os
import unittest
import vcr
logger = logging.getLogger(__name__)
class VCRTestCase(unittest.TestCase):
vcr_enabled = True
def setUp(self):
super(VCRTestCase, self).setUp()
if self.vcr_enabled:
... | from __future__ import absolute_import, unicode_literals
import inspect
import logging
import os
import unittest
import vcr
logger = logging.getLogger(__name__)
class VCRTestCase(unittest.TestCase):
vcr_enabled = True
def setUp(self):
super(VCRTestCase, self).setUp()
if self.vcr_enabled:
... | Add .yaml extension on default cassette name. | Add .yaml extension on default cassette name.
| Python | mit | agriffis/vcrpy-unittest | ---
+++
@@ -32,5 +32,5 @@
return os.path.join(testdir, 'cassettes')
def _get_cassette_name(self):
- return '{0}.{1}'.format(self.__class__.__name__,
- self._testMethodName)
+ return '{0}.{1}.yaml'.format(self.__class__.__name__,
+ ... |
8e7c64e0e9868b9bbc3156c70f6c368cad427f1f | egoio/__init__.py | egoio/__init__.py | import numpy
from psycopg2.extensions import register_adapter, AsIs
def adapt_numpy_int64(numpy_int64):
""" Adapting numpy.int64 type to SQL-conform int type using psycopg extension, see [1]_ for more info.
References
----------
.. [1] http://initd.org/psycopg/docs/advanced.html#adapting-new-python-t... | Add register_adapter to have type adaptions | Add register_adapter to have type adaptions
| Python | agpl-3.0 | openego/ego.io,openego/ego.io | ---
+++
@@ -0,0 +1,15 @@
+import numpy
+from psycopg2.extensions import register_adapter, AsIs
+
+
+def adapt_numpy_int64(numpy_int64):
+ """ Adapting numpy.int64 type to SQL-conform int type using psycopg extension, see [1]_ for more info.
+
+ References
+ ----------
+ .. [1] http://initd.org/psycopg/doc... | |
939d76ec219b3bff45dceaef59aee08a82a76f87 | virtool/labels/models.py | virtool/labels/models.py | from sqlalchemy import Column, String, Sequence, Integer
from virtool.postgres import Base
class Label(Base):
__tablename__ = 'labels'
id = Column(Integer, Sequence('labels_id_seq'), primary_key=True)
name = Column(String, unique=True)
color = Column(String(length=7))
description = Column(String... | from sqlalchemy import Column, String, Sequence, Integer
from virtool.postgres import Base
class Label(Base):
__tablename__ = 'labels'
id = Column(Integer, primary_key=True)
name = Column(String, unique=True)
color = Column(String(length=7))
description = Column(String)
def __repr__(self):
... | Simplify label model serial ID | Simplify label model serial ID
| Python | mit | virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool | ---
+++
@@ -6,7 +6,7 @@
class Label(Base):
__tablename__ = 'labels'
- id = Column(Integer, Sequence('labels_id_seq'), primary_key=True)
+ id = Column(Integer, primary_key=True)
name = Column(String, unique=True)
color = Column(String(length=7))
description = Column(String) |
e67849ca91d5d7405cd2c666516b92d2db513963 | runners/trytls/__init__.py | runners/trytls/__init__.py | from .testenv import testenv
__version__ = "0.1.1"
__all__ = ["testenv"]
| from .testenv import testenv
__version__ = "0.2.0"
__all__ = ["testenv"]
| Update init to latest version number | Update init to latest version number | Python | mit | ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls | ---
+++
@@ -1,5 +1,5 @@
from .testenv import testenv
-__version__ = "0.1.1"
+__version__ = "0.2.0"
__all__ = ["testenv"] |
ed33050bf503a1f8c9a009411f2cbbd4e2f78e4a | datastore/services/__init__.py | datastore/services/__init__.py | """Portal Service Layer
The service layer provides an API on top of Django models to build useful outputs for consumers such as views. This layer helps keep views thin, encourages reusability across views, simplifies testing, and eases separation of concerns for models.
Have a look at this example on SO for a high-le... | """Portal Service Layer
The service layer provides an API on top of Django models to build useful outputs for consumers such as views. This layer helps keep views thin, encourages reusability across views, simplifies testing, and eases separation of concerns for models.
Have a look at this example on SO for a high-le... | Fix imports to work with Python3 | Fix imports to work with Python3
| Python | mit | impactlab/oeem-energy-datastore,impactlab/oeem-energy-datastore,impactlab/oeem-energy-datastore | ---
+++
@@ -36,5 +36,5 @@
"""
-from overview import overview
-from meterruns_export import meterruns_export
+from .overview import overview
+from .meterruns_export import meterruns_export |
d5b744d358e2e2bd3e6f85e0fbae487e2ee64c64 | bot/logger/logger.py | bot/logger/logger.py | import time
from bot.action.util.textformat import FormattedText
from bot.logger.message_sender import MessageSender
LOG_ENTRY_FORMAT = "{time} [{tag}] {text}"
class Logger:
def __init__(self, sender: MessageSender):
self.sender = sender
def log(self, tag, text):
text = self._get_text_to_s... | import time
from bot.action.util.textformat import FormattedText
from bot.logger.message_sender import MessageSender
LOG_ENTRY_FORMAT = "{time} [{tag}] {text}"
TEXT_SEPARATOR = " | "
class Logger:
def __init__(self, sender: MessageSender):
self.sender = sender
def log(self, tag, *texts):
t... | Improve Logger to support variable text params | Improve Logger to support variable text params
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -5,26 +5,29 @@
LOG_ENTRY_FORMAT = "{time} [{tag}] {text}"
+TEXT_SEPARATOR = " | "
class Logger:
def __init__(self, sender: MessageSender):
self.sender = sender
- def log(self, tag, text):
- text = self._get_text_to_send(tag, text)
+ def log(self, tag, *texts):
+ ... |
90a3b5c66a050f22df56e39dc6fb4f32490df4cb | st2reactor/st2reactor/container/base.py | st2reactor/st2reactor/container/base.py | from datetime import timedelta
import eventlet
import logging
import sys
from threading import Thread
import time
# Constants
SUCCESS_EXIT_CODE = 0
eventlet.monkey_patch(
os=True,
select=True,
socket=True,
thread=False if '--use-debugger' in sys.argv else True,
time=True
)
LOG = logging.getLogger... | from datetime import timedelta
import eventlet
import sys
from threading import Thread
import time
from st2common import log as logging
# Constants
SUCCESS_EXIT_CODE = 0
eventlet.monkey_patch(
os=True,
select=True,
socket=True,
thread=False if '--use-debugger' in sys.argv else True,
time=True
)
... | Use st2common log and not logging | Fix: Use st2common log and not logging
| Python | apache-2.0 | StackStorm/st2,Plexxi/st2,grengojbo/st2,Itxaka/st2,nzlosh/st2,armab/st2,grengojbo/st2,dennybaa/st2,alfasin/st2,emedvedev/st2,peak6/st2,tonybaloney/st2,jtopjian/st2,lakshmi-kannan/st2,tonybaloney/st2,nzlosh/st2,StackStorm/st2,Itxaka/st2,pixelrebel/st2,pixelrebel/st2,Itxaka/st2,Plexxi/st2,punalpatel/st2,alfasin/st2,tonyb... | ---
+++
@@ -1,9 +1,10 @@
from datetime import timedelta
import eventlet
-import logging
import sys
from threading import Thread
import time
+
+from st2common import log as logging
# Constants
SUCCESS_EXIT_CODE = 0 |
aca834449910cd358ea59a73984f895cbfc67030 | examples/index.py | examples/index.py | import random
import tables
print 'tables.__version__', tables.__version__
nrows=10000-1
class Distance(tables.IsDescription):
frame = tables.Int32Col(pos=0)
distance = tables.Float64Col(pos=1)
h5file = tables.openFile('index.h5', mode='w')
table = h5file.createTable(h5file.root, 'distance_table', Distance,
... | import random
import tables
print 'tables.__version__', tables.__version__
nrows=10000-1
class Distance(tables.IsDescription):
frame = tables.Int32Col(pos=0)
distance = tables.Float64Col(pos=1)
h5file = tables.openFile('index.h5', mode='w')
table = h5file.createTable(h5file.root, 'distance_table', Distance,
... | Fix keyword names in example code | Fix keyword names in example code
| Python | bsd-3-clause | PyTables/PyTables,jennolsen84/PyTables,jack-pappas/PyTables,FrancescAlted/PyTables,dotsdl/PyTables,tp199911/PyTables,jennolsen84/PyTables,joonro/PyTables,joonro/PyTables,rabernat/PyTables,dotsdl/PyTables,rabernat/PyTables,cpcloud/PyTables,mohamed-ali/PyTables,avalentino/PyTables,jennolsen84/PyTables,tp199911/PyTables,j... | ---
+++
@@ -19,7 +19,7 @@
r.append()
table.flush()
-table.cols.frame.createIndex(optlevel=9, testmode=True, verbose=True)
+table.cols.frame.createIndex(optlevel=9, _testmode=True, _verbose=True)
#table.cols.frame.optimizeIndex(level=5, verbose=1)
results = [r.nrow for r in table.where('frame < 2')] |
02076f919e56503c76a41e78feed8a6720c65c19 | robot/robot/src/autonomous/timed_shoot.py | robot/robot/src/autonomous/timed_shoot.py | try:
import wpilib
except ImportError:
from pyfrc import wpilib
from common.autonomous_helper import StatefulAutonomous, timed_state
class TimedShootAutonomous(StatefulAutonomous):
'''
Tunable autonomous mode that does dumb time-based shooting
decisions. Works consistently.
'... | try:
import wpilib
except ImportError:
from pyfrc import wpilib
from common.autonomous_helper import StatefulAutonomous, timed_state
class TimedShootAutonomous(StatefulAutonomous):
'''
Tunable autonomous mode that does dumb time-based shooting
decisions. Works consistently.
'... | Add comments for timed shoot | Add comments for timed shoot
| Python | bsd-3-clause | frc1418/2014 | ---
+++
@@ -34,14 +34,17 @@
@timed_state(duration=1.2, next_state='drive', first=True)
def drive_wait(self, tm, state_tm):
+ '''Wait some period before we start driving'''
pass
@timed_state(duration=1.4, next_state='launch')
def drive(self, tm, state_tm):
+ '''St... |
dddfbf8970f22d44eac7805c3e325fd1684673d7 | word-count/word_count.py | word-count/word_count.py | def word_count(s):
words = strip_punc(s.lower()).split()
return {word: words.count(word) for word in set(words)}
def strip_punc(s):
return "".join(ch if ch.isalnum() else " " for ch in s)
| def word_count(s):
words = strip_punc(s).lower().split()
return {word: words.count(word) for word in set(words)}
def strip_punc(s):
return "".join(ch if ch.isalnum() else " " for ch in s)
| Move .lower() method call for readability | Move .lower() method call for readability
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,5 +1,5 @@
def word_count(s):
- words = strip_punc(s.lower()).split()
+ words = strip_punc(s).lower().split()
return {word: words.count(word) for word in set(words)}
|
4f34ec163d00e16df7150d58274a4a0135c90b04 | bugimporters/main.py | bugimporters/main.py | #!/usr/bin/env python
import argparse
import sys
def main(raw_arguments):
parser = argparse.ArgumentParser(description='Simple oh-bugimporters crawl program')
parser.add_argument('-i', action="store", dest="input")
parser.add_argument('-o', action="store", dest="output")
args = parser.parse_args(raw_... | #!/usr/bin/env python
import argparse
import sys
import json
import mock
import bugimporters.trac
def dict2obj(d):
class Trivial(object):
def get_base_url(self):
return self.base_url
ret = Trivial()
for thing in d:
setattr(ret, thing, d[thing])
ret.old_trac = False # FIXME, ... | Add enough hackish machinery for the CLI downloader to download one bug | Add enough hackish machinery for the CLI downloader to download one bug
| Python | agpl-3.0 | openhatch/oh-bugimporters,openhatch/oh-bugimporters,openhatch/oh-bugimporters | ---
+++
@@ -1,15 +1,67 @@
#!/usr/bin/env python
import argparse
import sys
+import json
+import mock
+import bugimporters.trac
+
+def dict2obj(d):
+ class Trivial(object):
+ def get_base_url(self):
+ return self.base_url
+ ret = Trivial()
+ for thing in d:
+ setattr(ret, thing, d[... |
5ea8993f76477c3cb6f35c26b38d82eda8a9478f | tests_django/integration_tests/test_output_adapter_integration.py | tests_django/integration_tests/test_output_adapter_integration.py | from django.test import TestCase
from chatterbot.ext.django_chatterbot.models import Statement
class OutputIntegrationTestCase(TestCase):
"""
Tests to make sure that output adapters
function correctly when using Django.
"""
def test_output_adapter(self):
from chatterbot.output import Outp... | from django.test import TestCase
from chatterbot.ext.django_chatterbot.models import Statement
class OutputIntegrationTestCase(TestCase):
"""
Tests to make sure that output adapters
function correctly when using Django.
"""
def test_output_adapter(self):
from chatterbot.output import Outp... | Remove confidence parameter in django test case | Remove confidence parameter in django test case
| Python | bsd-3-clause | vkosuri/ChatterBot,Reinaesaya/OUIRL-ChatBot,Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,davizucon/ChatterBot,gunthercox/ChatterBot,Gustavo6046/ChatterBot | ---
+++
@@ -14,6 +14,6 @@
adapter = OutputAdapter()
statement = Statement(text='_')
- result = adapter.process_response(statement, confidence=1)
+ result = adapter.process_response(statement)
self.assertEqual(result.text, '_') |
19c2f919c6deb11331e927ad3f794424905fc4f3 | self-post-stream/stream.py | self-post-stream/stream.py | import praw
import argparse
parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.')
parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')')
parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', typ... | import praw
import argparse
parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.')
parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')')
parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', typ... | Add value check for -limit | Add value check for -limit
| Python | mit | kshvmdn/reddit-bots | ---
+++
@@ -4,7 +4,9 @@
parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.')
parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')')
parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', typ... |
a643cb510429d9fcf4de43e64b04480419c5500b | mscgen/setup.py | mscgen/setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='mscgen',
version='0.3'... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
... | Change package name to sphinxcontrib-mscgen | mscgen: Change package name to sphinxcontrib-mscgen
| Python | bsd-2-clause | sphinx-contrib/spelling,sphinx-contrib/spelling | ---
+++
@@ -12,7 +12,7 @@
requires = ['Sphinx>=0.6']
setup(
- name='mscgen',
+ name='sphinxcontrib-mscgen',
version='0.3',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/mscgen', |
cbfbc7482a19b5d7ddcdb3980bfdf5d1d8487141 | Google_Code_Jam/2010_Africa/Qualification_Round/B/reverse_words.py | Google_Code_Jam/2010_Africa/Qualification_Round/B/reverse_words.py | #!/usr/bin/python -tt
"""Solves problem B from Google Code Jam Qualification Round Africa 2010
(https://code.google.com/codejam/contest/351101/dashboard#s=p1)
"Reverse Words"
"""
import sys
def main():
"""Reads problem data from stdin and prints answers to stdout.
Args:
None
Returns:
No... | #!/usr/bin/python -tt
"""Solves problem B from Google Code Jam Qualification Round Africa 2010
(https://code.google.com/codejam/contest/351101/dashboard#s=p1)
"Reverse Words"
"""
import sys
def main():
"""Reads problem data from stdin and prints answers to stdout.
Args:
None
Returns:
No... | Add description of assertions raised | Add description of assertions raised | Python | cc0-1.0 | mschruf/python | ---
+++
@@ -15,6 +15,10 @@
Returns:
Nothing
+
+ Raises:
+ AssertionError: on invalid input (claimed number of test cases
+ does not match actual number)
"""
lines = sys.stdin.read().splitlines() |
504f46a7dd56d78538547bb74515dd55ac1668fb | myhdl/_delay.py | myhdl/_delay.py | # This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003-2008 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by t... | # This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003-2008 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by t... | Fix a typo in an error message | Fix a typo in an error message
integeer -> integer | Python | lgpl-2.1 | myhdl/myhdl,myhdl/myhdl,josyb/myhdl,myhdl/myhdl,josyb/myhdl,josyb/myhdl | ---
+++
@@ -18,7 +18,7 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Module that provides the delay class."""
-_errmsg = "arg of delay constructor should be a natural integeer"
+_errmsg = "arg of delay constructor should be a natural integer"
class delay(object): |
407f3dfc9f2d87942908c23e6c4db938ac4d94dc | run_migrations.py | run_migrations.py | """
Run all migrations
"""
import imp
import os
import sys
import pymongo
from os.path import join
import logging
logging.basicConfig(level=logging.DEBUG)
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
def load_config(env):
config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config')
fp = No... | """
Run all migrations
"""
import imp
import os
import sys
import pymongo
from os.path import join
import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
def load_config(env):
config_path = os.path.join(ROOT_PATH, 'backdro... | Make migration logging more verbose | Make migration logging more verbose
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | ---
+++
@@ -9,6 +9,7 @@
import logging
logging.basicConfig(level=logging.DEBUG)
+log = logging.getLogger(__name__)
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
@@ -48,4 +49,5 @@
database = get_database(config)
for migration in get_migrations():
+ log.info("Running migration %s" %... |
4b0b85a54208625c7a2753d8ba9b96818f1411d0 | denorm/__init__.py | denorm/__init__.py |
from denorm.fields import denormalized
from denorm.dependencies import depend_on_related,depend_on_q
|
from denorm.fields import denormalized
from denorm.dependencies import depend_on_related, depend_on_q
__all__ = ["denormalized", "depend_on_related", "depend_on_q"]
| Use __all__ to make it not overwrite .models randomly. | Use __all__ to make it not overwrite .models randomly.
| Python | bsd-3-clause | heinrich5991/django-denorm,miracle2k/django-denorm,Chive/django-denorm,anentropic/django-denorm,simas/django-denorm,catalanojuan/django-denorm,victorvde/django-denorm,initcrash/django-denorm,PetrDlouhy/django-denorm,gerdemb/django-denorm,kennknowles/django-denorm,Eksmo/django-denorm,alex-mcleod/django-denorm,mjtamlyn/d... | ---
+++
@@ -1,3 +1,5 @@
from denorm.fields import denormalized
-from denorm.dependencies import depend_on_related,depend_on_q
+from denorm.dependencies import depend_on_related, depend_on_q
+
+__all__ = ["denormalized", "depend_on_related", "depend_on_q"] |
4799fbb78503e16095b72e39fa243dcbaeef94b2 | lib/rapidsms/tests/test_backend_irc.py | lib/rapidsms/tests/test_backend_irc.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import unittest
from harness import MockRouter
class TestLog(unittest.TestCase):
def test_backend_irc (self):
router = MockRouter()
try:
import irclib
from rapidsms.backends.irc import Backend
backend = Backend(... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import unittest
from harness import MockRouter
class TestBackendIRC(unittest.TestCase):
def test_backend_irc (self):
router = MockRouter()
try:
import irclib
from rapidsms.backends.irc import Backend
backend = B... | Rename test class (sloppy cut n' paste job) | Rename test class (sloppy cut n' paste job)
| Python | bsd-3-clause | dimagi/rapidsms-core-dev,dimagi/rapidsms-core-dev,unicefuganda/edtrac,unicefuganda/edtrac,ken-muturi/rapidsms,catalpainternational/rapidsms,caktus/rapidsms,rapidsms/rapidsms-core-dev,ehealthafrica-ci/rapidsms,peterayeni/rapidsms,peterayeni/rapidsms,dimagi/rapidsms,catalpainternational/rapidsms,lsgunth/rapidsms,dimagi/r... | ---
+++
@@ -4,7 +4,7 @@
import unittest
from harness import MockRouter
-class TestLog(unittest.TestCase):
+class TestBackendIRC(unittest.TestCase):
def test_backend_irc (self):
router = MockRouter()
try: |
6771b83ec65f015fa58191694ad068063f61672b | amazon.py | amazon.py | from osv import osv, fields
import time
import datetime
import inspect
import xmlrpclib
import netsvc
import os
import logging
import urllib2
import base64
from tools.translate import _
import httplib, ConfigParser, urlparse
from xml.dom.minidom import parse, parseString
from lxml import etree
from xml.etree.ElementTre... | from osv import osv, fields
class amazon_instance(osv.osv):
_inherit = 'amazon.instance'
def create_orders(self, cr, uid, instance_obj, shop_id, results):
return super(amazon_instance, self).create_orders(cr, uid, instance_obj, shop_id, results, defaults={
"payment_channel": "amazon",
... | Simplify defaulting the sale and payment channels for Amazon sales. | Simplify defaulting the sale and payment channels for Amazon sales.
| Python | agpl-3.0 | ryepdx/sale_channels | ---
+++
@@ -1,41 +1,12 @@
from osv import osv, fields
-import time
-import datetime
-import inspect
-import xmlrpclib
-import netsvc
-import os
-import logging
-import urllib2
-import base64
-from tools.translate import _
-import httplib, ConfigParser, urlparse
-from xml.dom.minidom import parse, parseString
-from l... |
66461c43b3a0229d02c58ad7aae4653bb638715c | students/crobison/session03/mailroom.py | students/crobison/session03/mailroom.py | # Charles Robison
# 2016.10.16
# Mailroom Lab
#!/usr/bin/env python
donors = {
'Smith':[100, 125, 100],
'Galloway':[50],
'Williams':[22, 43, 40, 3.25],
'Cruz':[101],
'Maples':[1.50, 225]
}
def print_report():
print("This will print a report")
... | # Charles Robison
# 2016.10.16
# Mailroom Lab
#!/usr/bin/env python
donors = {
'Smith':[100, 125, 100],
'Galloway':[50],
'Williams':[22, 43, 40, 3.25],
'Cruz':[101],
'Maples':[1.50, 225]
}
donations = {}
for k, v in donors.items():
donations[k]... | Add function to list donors and total donations. | Add function to list donors and total donations.
| Python | unlicense | UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,Baumelbi/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,Baumelbi/IntroPython2016,UWPCE-PythonCert/IntroPython2016 | ---
+++
@@ -12,10 +12,14 @@
'Maples':[1.50, 225]
}
+donations = {}
+for k, v in donors.items():
+ donations[k] = sum(v)
+
def print_report():
print("This will print a report")
- for i in donors.values():
- print(sum(i))
+ for i in donations:
+ print(i, donations[i... |
bb8d9aa91b6d1bf2a765113d5845402c059e6969 | IPython/core/payloadpage.py | IPython/core/payloadpage.py | # encoding: utf-8
"""A payload based version of page."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from IPython.core.getipython import get_ipython
#-----------------------------------------------------------------------------
# Classes and functions
#-------... | # encoding: utf-8
"""A payload based version of page."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from IPython.core.getipython import get_ipython
#-----------------------------------------------------------------------------
# Classes and functions
#-------... | Remove leftover text key from our own payload creation | Remove leftover text key from our own payload creation
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -37,7 +37,6 @@
payload = dict(
source='page',
data=data,
- text=strng,
start=start,
screen_lines=screen_lines,
) |
39e561b2675649279cbff4aa457216d12072160b | paws/request.py | paws/request.py | from Cookie import SimpleCookie
from urlparse import parse_qs
from utils import MultiDict, cached_property
class Request(object):
def __init__(self, event, context):
self.event = event
self.context = context
@property
def method(self):
return self.event['httpMethod']
@proper... | from Cookie import SimpleCookie
from urlparse import parse_qs
from utils import MultiDict, cached_property
class Request(object):
def __init__(self, event, context):
self.event = event
self.context = context
@property
def method(self):
return self.event['httpMethod']
@proper... | Use more sensible name for post data | Use more sensible name for post data
| Python | bsd-3-clause | funkybob/paws | ---
+++
@@ -18,7 +18,7 @@
return self.event['queryStringParameters']
@cached_property
- def post(self):
+ def form(self):
return MultiDict(parse_qs(self.event.get('body', '') or ''))
@cached_property |
4b863a659e36b1fa9887847e9dbb133b1852cf9b | examples/miniapps/bundles/run.py | examples/miniapps/bundles/run.py | """Run 'Bundles' example application."""
import sqlite3
import boto3
from dependency_injector import containers
from dependency_injector import providers
from bundles.users import Users
from bundles.photos import Photos
class Core(containers.DeclarativeContainer):
"""Core container."""
config = providers.... | """Run 'Bundles' example application."""
import sqlite3
import boto3
from dependency_injector import containers
from dependency_injector import providers
from bundles.users import Users
from bundles.photos import Photos
class Core(containers.DeclarativeContainer):
"""Core container."""
config = providers.... | Update bundles example after configuration provider refactoring | Update bundles example after configuration provider refactoring
| Python | bsd-3-clause | ets-labs/dependency_injector,ets-labs/python-dependency-injector,rmk135/objects,rmk135/dependency_injector | ---
+++
@@ -23,8 +23,7 @@
if __name__ == '__main__':
# Initializing containers
- core = Core()
- core.config.update({'database': {'dsn': ':memory:'},
+ core = Core(config={'database': {'dsn': ':memory:'},
'aws': {'access_key_id': 'KEY',
'secre... |
d9c005669c65d65a18b0bd8527918c5dd3fa688c | manage/fabfile/ci.py | manage/fabfile/ci.py | from fabric.api import *
@task
@role('ci')
def install():
sudo("apt-get install git")
sudo("apt-get install maven2") # TODO: maven3
sudo("apt-get install groovy") # TODO: groovy-1.8, or gradle...
configure_groovy_grapes()
sudo("apt-get install python-dev")
sudo("apt-get install python-pip")
... | from fabric.api import *
@task
@roles('ci')
def install():
sudo("apt-get install git")
sudo("apt-get install maven2") # TODO: maven3
sudo("apt-get install groovy") # TODO: groovy-1.8, or gradle...
configure_groovy_grapes()
sudo("apt-get install python-dev")
sudo("apt-get install python-pip")
... | Fix typo in fab script | Fix typo in fab script
| Python | bsd-2-clause | rinfo/rdl,rinfo/rdl,rinfo/rdl,rinfo/rdl,rinfo/rdl,rinfo/rdl | ---
+++
@@ -1,7 +1,7 @@
from fabric.api import *
@task
-@role('ci')
+@roles('ci')
def install():
sudo("apt-get install git")
sudo("apt-get install maven2") # TODO: maven3 |
1ed7d695eff134557990d8b1a5dffa51b6d1d2f6 | distarray/run_tests.py | distarray/run_tests.py | # encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""... | # encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""... | Return returncode from shell command. | Return returncode from shell command. | Python | bsd-3-clause | enthought/distarray,RaoUmer/distarray,RaoUmer/distarray,enthought/distarray | ---
+++
@@ -31,7 +31,7 @@
while True:
char = proc.stdout.read(1).decode()
if not char:
- break
+ return proc.wait()
else:
print(char, end="")
sys.stdout.flush()
@@ -40,8 +40,8 @@
def test():
"""Run all DistArray tests."""
cmd =... |
e0cfd055540b5647b0bd5a4cfffb9c1a3399c721 | tests/commands/load/test_load_coverage_qc_report_cmd.py | tests/commands/load/test_load_coverage_qc_report_cmd.py | # -*- coding: utf-8 -*-
import os
from scout.demo import coverage_qc_report
from scout.commands import cli
def test_load_coverage_qc_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(coverage_qc_r... | # -*- coding: utf-8 -*-
import os
from scout.demo import coverage_qc_report
from scout.commands import cli
def test_load_coverage_qc_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(coverage_qc_re... | Fix code style issues with Black | Fix code style issues with Black
| Python | bsd-3-clause | Clinical-Genomics/scout,Clinical-Genomics/scout,Clinical-Genomics/scout | ---
+++
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import os
-from scout.demo import coverage_qc_report
+from scout.demo import coverage_qc_report
from scout.commands import cli
|
b6a8c71be9595c1f2e8c76e9b9bbc49c73a9ec5c | backend/api-server/warehaus_api/auth/__init__.py | backend/api-server/warehaus_api/auth/__init__.py | from datetime import timedelta
from logging import getLogger
from flask import request
from flask_jwt import JWT
from .models import User
from .roles import roles
from .roles import user_required
from .roles import admin_required
from .login import validate_user
logger = getLogger(__name__)
def authenticate(username,... | from datetime import datetime
from datetime import timedelta
from logging import getLogger
from flask import request
from flask import current_app
from flask_jwt import JWT
from .models import User
from .roles import roles
from .roles import user_required
from .roles import admin_required
from .login import validate_us... | Fix payload_handler in api-server to generate proper JWTs | Fix payload_handler in api-server to generate proper JWTs
| Python | agpl-3.0 | warehaus/warehaus,labsome/labsome,warehaus/warehaus,labsome/labsome,labsome/labsome,warehaus/warehaus | ---
+++
@@ -1,6 +1,8 @@
+from datetime import datetime
from datetime import timedelta
from logging import getLogger
from flask import request
+from flask import current_app
from flask_jwt import JWT
from .models import User
from .roles import roles
@@ -25,8 +27,16 @@
return None
return User.query.... |
9cbfed00905fb8b360b60cce1afc293b71a2aced | check_access.py | check_access.py | #!/usr/bin/env python
import os
import sys
from parse_docker_args import parse_mount
def can_access(path, perm):
mode = None
if perm == 'r':
mode = os.R_OK
elif perm == 'w':
mode = os.W_OK
else:
return False
return os.access(path, mode)
if __name__ == '__main__':
if len(sys.argv) < 2:
exi... | #!/usr/bin/env python
import os
import sys
from parse_docker_args import parse_mount
def can_access(path, perm):
mode = None
if perm == 'r':
mode = os.R_OK
elif perm == 'w':
mode = os.W_OK
else:
return False
return os.access(path, mode)
if __name__ == '__main__':
if len(sys.argv) < 2:
pri... | Print usage if not enough args | Print usage if not enough args
| Python | mit | Duke-GCB/docker-wrapper,Duke-GCB/docker-wrapper | ---
+++
@@ -16,7 +16,9 @@
if __name__ == '__main__':
if len(sys.argv) < 2:
- exit
+ print "USAGE: {} <docker volume spec>".format(sys.argv[0])
+ print "e.g. {} /data/somelab:/input:rw".format(sys.argv[0])
+ exit(1)
volume_spec = sys.argv[1]
path, perm = parse_mount(volume_spec)
uid = os.get... |
f4dfcf91c11fd06b5b71135f888b6979548a5147 | conveyor/__main__.py | conveyor/__main__.py | from __future__ import absolute_import
from .core import Conveyor
def main():
Conveyor().run()
if __name__ == "__main__":
main()
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from .core import Conveyor
def main():
Conveyor().run()
if __name__ == "__main__":
main()
| Bring the standard __future__ imports over | Bring the standard __future__ imports over
| Python | bsd-2-clause | crateio/carrier | ---
+++
@@ -1,4 +1,6 @@
from __future__ import absolute_import
+from __future__ import division
+from __future__ import unicode_literals
from .core import Conveyor
@@ -6,5 +8,6 @@
def main():
Conveyor().run()
+
if __name__ == "__main__":
main() |
fca88336777b9c47404e7b397d39ef8d3676b7b5 | src/zone_iterator/__main__.py | src/zone_iterator/__main__.py | import gzip
import sys
from . import zone_iterator, zone_dict_to_str, ZONE_FMT_STR
try:
from colorama import Fore, init as colorama_init
except ImportError:
HAS_COLOR = False
else:
HAS_COLOR = True
def main():
if HAS_COLOR:
colors = [Fore.GREEN, Fore.MAGENTA, Fore.BLUE, Fore.CYAN, Fore.YELLO... | import argparse
import gzip
import sys
from . import zone_iterator, zone_dict_to_str, ZONE_FMT_STR
try:
from colorama import Fore, init as colorama_init
except ImportError:
HAS_COLOR = False
else:
HAS_COLOR = True
def maybe_compressed_file(filename):
if filename[-2:] == 'gz':
our_open = gzip... | Switch to using argparse for the main script. | Switch to using argparse for the main script.
| Python | agpl-3.0 | maxrp/zone_normalize | ---
+++
@@ -1,3 +1,4 @@
+import argparse
import gzip
import sys
@@ -11,7 +12,20 @@
HAS_COLOR = True
+def maybe_compressed_file(filename):
+ if filename[-2:] == 'gz':
+ our_open = gzip.open
+ else:
+ our_open = open
+
+ return our_open(filename, mode='rt')
+
+
def main():
+ pars... |
c1756ab481f3bf72ab33465c8eb1d5a3e729ce4e | model_logging/migrations/0003_data_migration.py | model_logging/migrations/0003_data_migration.py | # -*- coding: utf-8 -*-
from django.db import migrations
app = 'model_logging'
model = 'LogEntry'
def move_data(apps, schema_editor):
LogEntry = apps.get_model(app, model)
for entry in LogEntry.objects.all():
entry.data_temp = entry.data
entry.save()
class Migration(migrations.Migration):
... | # -*- coding: utf-8 -*-
from django.db import migrations
app = 'model_logging'
model = 'LogEntry'
def move_data(apps, schema_editor):
try:
from pgcrypto.fields import TextPGPPublicKeyField
except ImportError:
raise ImportError('Please install django-pgcrypto-fields to perform migration')
... | Add try, catch statement to ensure data migration can be performed. | Add try, catch statement to ensure data migration can be performed.
| Python | bsd-2-clause | incuna/django-model-logging | ---
+++
@@ -6,6 +6,11 @@
def move_data(apps, schema_editor):
+ try:
+ from pgcrypto.fields import TextPGPPublicKeyField
+ except ImportError:
+ raise ImportError('Please install django-pgcrypto-fields to perform migration')
+
LogEntry = apps.get_model(app, model)
for entry in LogEnt... |
ba57b3c016ed3bc3c8db9ccc3c637c2c58de1e1d | reddit/admin.py | reddit/admin.py | from django.contrib import admin
from reddit.models import RedditUser,Submission,Comment,Vote
# Register your models here.
class SubmissionInline(admin.TabularInline):
model = Submission
max_num = 10
class CommentsInline(admin.StackedInline):
model = Comment
max_num = 10
class SubmissionAdmin(admin.M... | from django.contrib import admin
from reddit.models import RedditUser,Submission,Comment,Vote
# Register your models here.
class SubmissionInline(admin.TabularInline):
model = Submission
max_num = 10
class CommentsInline(admin.StackedInline):
model = Comment
max_num = 10
class SubmissionAdmin(admin.M... | Remove commentsInLine for RedditUser because there is no longer foreignKey from Comment to RedditUser | Remove commentsInLine for RedditUser because there is no longer foreignKey from Comment to RedditUser
| Python | apache-2.0 | Nikola-K/django_reddit,Nikola-K/django_reddit,Nikola-K/django_reddit | ---
+++
@@ -17,7 +17,6 @@
class RedditUserAdmin(admin.ModelAdmin):
inlines = [
SubmissionInline,
- CommentsInline
]
admin.site.register(RedditUser, RedditUserAdmin) |
5c0a64eb2f580225c07f09494ac723da16b38d18 | openedx/features/job_board/views.py | openedx/features/job_board/views.py | from django.views.generic.list import ListView
from edxmako.shortcuts import render_to_response
from .models import Job
class JobListView(ListView):
model = Job
context_object_name = 'jobs_list'
paginate_by = 10
template_name = 'features/job_board/job_list.html'
ordering = ['-created']
temp... | from django.views.generic.list import ListView
from edxmako.shortcuts import render_to_response
from .models import Job
class JobListView(ListView):
model = Job
context_object_name = 'job_list'
paginate_by = 10
template_name = 'features/job_board/job_list.html'
ordering = ['-created']
templ... | Change jobs_list object name to job_list | Change jobs_list object name to job_list
| Python | agpl-3.0 | philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform | ---
+++
@@ -8,7 +8,7 @@
class JobListView(ListView):
model = Job
- context_object_name = 'jobs_list'
+ context_object_name = 'job_list'
paginate_by = 10
template_name = 'features/job_board/job_list.html'
ordering = ['-created'] |
dd75314f203b907f25a7b7e158c7e5d988a5b6ae | neo/test/rawiotest/test_openephysbinaryrawio.py | neo/test/rawiotest/test_openephysbinaryrawio.py | import unittest
from neo.rawio.openephysbinaryrawio import OpenEphysBinaryRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
class TestOpenEphysBinaryRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = OpenEphysBinaryRawIO
entities_to_download = [
'openephysbinary'
]
entit... | import unittest
from neo.rawio.openephysbinaryrawio import OpenEphysBinaryRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
class TestOpenEphysBinaryRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = OpenEphysBinaryRawIO
entities_to_download = [
'openephysbinary'
]
entit... | Add new OE test folder | Add new OE test folder
| Python | bsd-3-clause | apdavison/python-neo,JuliaSprenger/python-neo,NeuralEnsemble/python-neo,INM-6/python-neo | ---
+++
@@ -13,6 +13,7 @@
'openephysbinary/v0.5.3_two_neuropixels_stream',
'openephysbinary/v0.4.4.1_with_video_tracking',
'openephysbinary/v0.5.x_two_nodes',
+ 'openephysbinary/v0.6.x_neuropixels_multiexp_multistream',
]
|
7c9d2ace7de2727c43b0ee00f8f2280d8a465301 | Python/brewcaskupgrade.py | Python/brewcaskupgrade.py | #! /usr/bin/env python
# -*- coding: utf8 -*-
import argparse
import shutil
from subprocess import check_output, run
parser = argparse.ArgumentParser(description='Update every entries found in cask folder.')
parser.add_argument('--pretend', dest='pretend', action='store_true',
help='Pretend to ta... | #! /usr/bin/env python
# -*- coding: utf8 -*-
import argparse
import shutil
from subprocess import check_output, run
parser = argparse.ArgumentParser(description='Update every entries found in cask folder.')
parser.add_argument('--pretend', dest='pretend', action='store_true',
help='Pretend to ta... | Check version for latest cask behaviour changed | Check version for latest cask behaviour changed
| Python | cc0-1.0 | boltomli/MyMacScripts,boltomli/MyMacScripts | ---
+++
@@ -32,11 +32,17 @@
cask
]
try:
- install_status = check_output(info_command).decode()
+ install_status = str.splitlines(check_output(info_command).decode())
except:
install_status = 'Not installed'
- if 'Not installed' in install_status:
+ version = str.... |
703e61104317332d60bd0bde49652b8618cd0e6b | var/spack/packages/mrnet/package.py | var/spack/packages/mrnet/package.py | from spack import *
class Mrnet(Package):
"""The MRNet Multi-Cast Reduction Network."""
homepage = "http://paradyn.org/mrnet"
url = "ftp://ftp.cs.wisc.edu/paradyn/mrnet/mrnet_4.0.0.tar.gz"
versions = { '4.0.0' : 'd00301c078cba57ef68613be32ceea2f', }
parallel = False
def install(self, spe... | from spack import *
class Mrnet(Package):
"""The MRNet Multi-Cast Reduction Network."""
homepage = "http://paradyn.org/mrnet"
url = "ftp://ftp.cs.wisc.edu/paradyn/mrnet/mrnet_4.0.0.tar.gz"
versions = { '4.0.0' : 'd00301c078cba57ef68613be32ceea2f', }
parallel = False
depends_on("boost")
... | Make mrnet depend on boost. | Make mrnet depend on boost.
| Python | lgpl-2.1 | mfherbst/spack,iulian787/spack,tmerrick1/spack,LLNL/spack,mfherbst/spack,TheTimmy/spack,krafczyk/spack,LLNL/spack,krafczyk/spack,TheTimmy/spack,mfherbst/spack,TheTimmy/spack,krafczyk/spack,tmerrick1/spack,skosukhin/spack,EmreAtes/spack,lgarren/spack,matthiasdiener/spack,EmreAtes/spack,iulian787/spack,EmreAtes/spack,mat... | ---
+++
@@ -8,6 +8,8 @@
versions = { '4.0.0' : 'd00301c078cba57ef68613be32ceea2f', }
parallel = False
+ depends_on("boost")
+
def install(self, spec, prefix):
configure("--prefix=%s" %prefix, "--enable-shared")
@@ -17,5 +19,7 @@
# TODO: copy configuration header files to includ... |
9504529dd4b9140be0026d0b30a0e88e5dea5e25 | rtrss/config.py | rtrss/config.py | import os
import logging
import importlib
# All configuration defaults are set in this module
TRACKER_HOST = 'rutracker.org'
# Timeone for the tracker times
TZNAME = 'Europe/Moscow'
LOGLEVEL = logging.INFO
LOG_FORMAT_LOGENTRIES = '%(levelname)s %(name)s %(message)s'
LOG_FORMAT_BRIEF = '%(asctime)s %(levelname)s %(... | import os
import logging
import importlib
# All configuration defaults are set in this module
TRACKER_HOST = 'rutracker.org'
# Timeone for the tracker times
TZNAME = 'Europe/Moscow'
LOGLEVEL = logging.INFO
LOG_FORMAT_LOGENTRIES = '%(levelname)s %(name)s %(message)s'
LOG_FORMAT_BRIEF = '%(asctime)s %(levelname)s %(... | Add default IP and PORT | Add default IP and PORT
| Python | apache-2.0 | notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss | ---
+++
@@ -26,6 +26,9 @@
if not APP_ENVIRONMENT:
raise EnvironmentError('RTRSS_ENVIRONMENT must be set')
+IP = '0.0.0.0'
+PORT = 8080
+
_mod = importlib.import_module('rtrss.config_{}'.format(APP_ENVIRONMENT))
_envconf = {k: v for k, v in _mod.__dict__.items() if k == k.upper()}
globals().update(_envconf) |
87df9686444c46796475da06c67eeca01c4a46cc | scikits/audiolab/pysndfile/__init__.py | scikits/audiolab/pysndfile/__init__.py | from pysndfile import formatinfo, sndfile
from pysndfile import supported_format, supported_endianness, \
supported_encoding
from pysndfile import PyaudioException, PyaudioIOError
from _sndfile import Sndfile, Format, available_file_formats, available_encodings
| from _sndfile import Sndfile, Format, available_file_formats, available_encodings
from compat import formatinfo, sndfile, PyaudioException, PyaudioIOError
from pysndfile import supported_format, supported_endianness, \
supported_encoding
| Use compat module instead of ctypes-based implementation. | Use compat module instead of ctypes-based implementation.
| Python | lgpl-2.1 | cournape/audiolab,cournape/audiolab,cournape/audiolab | ---
+++
@@ -1,5 +1,4 @@
-from pysndfile import formatinfo, sndfile
+from _sndfile import Sndfile, Format, available_file_formats, available_encodings
+from compat import formatinfo, sndfile, PyaudioException, PyaudioIOError
from pysndfile import supported_format, supported_endianness, \
... |
c767ee0b4392c519335a6055f64bbbb5a500e997 | api_tests/base/test_pagination.py | api_tests/base/test_pagination.py | # -*- coding: utf-8 -*-
from nose.tools import * # flake8: noqa
from tests.base import ApiTestCase
from api.base.pagination import MaxSizePagination
class TestMaxPagination(ApiTestCase):
def test_no_query_param_alters_page_size(self):
assert_is_none(MaxSizePagination.page_size_query_param)
| # -*- coding: utf-8 -*-
from nose.tools import * # flake8: noqa
from tests.base import ApiTestCase
from api.base.pagination import MaxSizePagination
class TestMaxPagination(ApiTestCase):
def test_no_query_param_alters_page_size(self):
assert MaxSizePagination.page_size_query_param is None, 'Adding varia... | Add error message for future breakers-of-tests | Add error message for future breakers-of-tests
| Python | apache-2.0 | HalcyonChimera/osf.io,DanielSBrown/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,crcresearch/osf.io,crcresearch/osf.io,alexschiller/osf.io,hmoco/osf.io,rdhyee/osf.io,caneruguz/osf.io,SSJohns/osf.io,laurenrevere/osf.io,icereval/osf.io,sloria/osf.io,emetsger/osf.io,felliott/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,l... | ---
+++
@@ -7,4 +7,5 @@
class TestMaxPagination(ApiTestCase):
def test_no_query_param_alters_page_size(self):
- assert_is_none(MaxSizePagination.page_size_query_param)
+ assert MaxSizePagination.page_size_query_param is None, 'Adding variable page sizes to the paginator ' +\
+ 'requir... |
d531ea281b546d31724c021011a7145d3095dbf8 | SoftLayer/tests/CLI/modules/import_test.py | SoftLayer/tests/CLI/modules/import_test.py | """
SoftLayer.tests.CLI.modules.import_test
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
from SoftLayer.tests import unittest
from SoftLayer.CLI.modules import get_module_list
from importlib import import_module
class TestImportCLIModules(unittest.TestCase):
... | """
SoftLayer.tests.CLI.modules.import_test
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
"""
from SoftLayer.tests import unittest
from SoftLayer.CLI.modules import get_module_list
from importlib import import_module
class TestImportCLIModules(unittest.TestCase):
... | Print modules being imported (for easier debugging) | Print modules being imported (for easier debugging)
| Python | mit | allmightyspiff/softlayer-python,underscorephil/softlayer-python,cloudify-cosmo/softlayer-python,iftekeriba/softlayer-python,skraghu/softlayer-python,kyubifire/softlayer-python,nanjj/softlayer-python,Neetuj/softlayer-python,softlayer/softlayer-python,briancline/softlayer-python | ---
+++
@@ -16,5 +16,5 @@
modules = get_module_list()
for module in modules:
module_path = 'SoftLayer.CLI.modules.' + module
-
+ print("Importing %s" % module_path)
import_module(module_path) |
39a743463f55c3cfbbea05b4d471d01f66dd93f8 | permamodel/tests/test_perma_base.py | permamodel/tests/test_perma_base.py | """
test_perma_base.py
tests of the perma_base component of permamodel
"""
from permamodel.components import frost_number
import os
import numpy as np
from .. import permamodel_directory, data_directory, examples_directory
def test_directory_names_are_set():
assert(permamodel_directory is not None)
| """
test_perma_base.py
tests of the perma_base component of permamodel
"""
import os
from nose.tools import assert_true
from .. import (permamodel_directory, data_directory,
examples_directory, tests_directory)
def test_permamodel_directory_is_set():
assert(permamodel_directory is not None)
d... | Add unit tests for all package directories | Add unit tests for all package directories
| Python | mit | permamodel/permamodel,permamodel/permamodel | ---
+++
@@ -3,11 +3,39 @@
tests of the perma_base component of permamodel
"""
-from permamodel.components import frost_number
import os
-import numpy as np
-from .. import permamodel_directory, data_directory, examples_directory
+from nose.tools import assert_true
+from .. import (permamodel_directory, data_di... |
1cdcacb8ab8e78c9b325f454382d591da10b06fd | senlin_dashboard/enabled/_50_senlin.py | senlin_dashboard/enabled/_50_senlin.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | Change senlin dashboard to not be the default dashboard | Change senlin dashboard to not be the default dashboard
Change-Id: I81d492bf8998e74f5bf53b0226047a070069b060
Closes-Bug: #1754183
| Python | apache-2.0 | stackforge/senlin-dashboard,stackforge/senlin-dashboard,openstack/senlin-dashboard,openstack/senlin-dashboard,openstack/senlin-dashboard,stackforge/senlin-dashboard,openstack/senlin-dashboard | ---
+++
@@ -17,7 +17,7 @@
'senlin_dashboard',
'senlin_dashboard.cluster'
]
-DEFAULT = True
+DEFAULT = False
AUTO_DISCOVER_STATIC_FILES = True
ADD_ANGULAR_MODULES = ['horizon.cluster']
ADD_SCSS_FILES = [ |
82217bab5263984c3507a68c1b94f9d315bafc63 | src/masterfile/__init__.py | src/masterfile/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from ._metadata import version as __version__, author as __author__, email as __email__
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
from ._metadata import version as __version__, author as __author__, email as __email__
__package_version__ = 'masterfile {}'.format(__version__)
| Add __package_version__ for version description | Add __package_version__ for version description
Example: "masterfile 0.1.0dev" | Python | mit | njvack/masterfile | ---
+++
@@ -3,3 +3,5 @@
from __future__ import absolute_import
from ._metadata import version as __version__, author as __author__, email as __email__
+
+__package_version__ = 'masterfile {}'.format(__version__) |
8525465c4f428cc0df02df7eb4fca165a9af6bdc | knowledge_repo/utils/registry.py | knowledge_repo/utils/registry.py | from abc import ABCMeta
import logging
logger = logging.getLogger(__name__)
class SubclassRegisteringABCMeta(ABCMeta):
def __init__(cls, name, bases, dct):
super(SubclassRegisteringABCMeta, cls).__init__(name, bases, dct)
if not hasattr(cls, '_registry'):
cls._registry = {}
... | from abc import ABCMeta
import logging
logger = logging.getLogger(__name__)
class SubclassRegisteringABCMeta(ABCMeta):
def __init__(cls, name, bases, dct):
super(SubclassRegisteringABCMeta, cls).__init__(name, bases, dct)
if not hasattr(cls, '_registry'):
cls._registry = {}
... | Update a string with the latest formatting approach | Update a string with the latest formatting approach
| Python | apache-2.0 | airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo | ---
+++
@@ -16,7 +16,8 @@
if registry_keys:
for key in registry_keys:
if key in cls._registry and cls.__name__ != cls._registry[key].__name__:
- logger.info("Ignoring attempt by class `{}` to register key '{}', which is already registered for class `{}`.".form... |
b3b216a95c4254302776fdbb67bab948ba12d3d3 | ddsc_worker/tasks.py | ddsc_worker/tasks.py | from __future__ import absolute_import
from ddsc_worker.celery import celery
@celery.task
def add(x, y):
return x + y
@celery.task
def mul(x, y):
return x + y
| from __future__ import absolute_import
from ddsc_worker.celery import celery
import time
@celery.task
def add(x, y):
time.sleep(10)
return x + y
@celery.task
def mul(x, y):
time.sleep(2)
return x * y
| Add sleep to simulate work | Add sleep to simulate work
| Python | mit | ddsc/ddsc-worker | ---
+++
@@ -1,12 +1,15 @@
from __future__ import absolute_import
from ddsc_worker.celery import celery
+import time
@celery.task
def add(x, y):
+ time.sleep(10)
return x + y
@celery.task
def mul(x, y):
- return x + y
+ time.sleep(2)
+ return x * y |
ee5cd9196fc273c74fce29e4ac9c3726d3da03b6 | deployer/__init__.py | deployer/__init__.py | __version__ = '0.1.6'
__author__ = 'sukrit'
import logging
from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL
logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE, level=LOG_ROOT_LEVEL)
| __version__ = '0.1.7'
__author__ = 'sukrit'
import logging
from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL
logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE, level=LOG_ROOT_LEVEL)
| Change development version to 0.1.7 | Change development version to 0.1.7 | Python | mit | totem/cluster-deployer,totem/cluster-deployer,totem/cluster-deployer | ---
+++
@@ -1,4 +1,4 @@
-__version__ = '0.1.6'
+__version__ = '0.1.7'
__author__ = 'sukrit'
import logging |
73344151ce39ebc093b7915d6625096ddc2a125d | git_update/__main__.py | git_update/__main__.py | #!/usr/bin/env python
"""Script for updating a directory of repositories."""
import logging
import os
import click
from .actions import update_repo
@click.command()
@click.option('-d', '--debug', help='Set DEBUG level logging.', is_flag=True)
@click.argument('dir', default='.')
def main(**kwargs):
"""Update rep... | #!/usr/bin/env python
"""Script for updating a directory of repositories."""
import logging
import os
import click
from .actions import update_repo
@click.command()
@click.option('-d', '--debug', help='Set DEBUG level logging.', is_flag=True)
@click.argument('dir', default='.')
def main(**kwargs):
"""Update rep... | Fix bux when using Git directory | main: Fix bux when using Git directory
If a Git directory is passed in, it needs to be in a list of one.
| Python | mit | e4r7hbug/git_update | ---
+++
@@ -34,7 +34,7 @@
# Git directory was passed in, not a directory of Git directories
if '.git' in dir_list:
- dir_list = kwargs['dir']
+ dir_list = [kwargs['dir']]
for directory in dir_list:
update_repo(os.path.join(main_dir, directory)) |
2dc56ab04ea17bea05654eaec12bb27b48b0b225 | robotd/cvcapture.py | robotd/cvcapture.py | import threading
from robotd.native import _cvcapture
class CaptureDevice(object):
def __init__(self, path=None):
if path is not None:
argument_c = _cvcapture.ffi.new(
'char[]',
path.encode('utf-8'),
)
else:
argument_c = _cvcaptur... | import threading
from robotd.native import _cvcapture
class CaptureDevice(object):
def __init__(self, path=None):
if path is not None:
argument_c = _cvcapture.ffi.new(
'char[]',
path.encode('utf-8'),
)
else:
argument_c = _cvcaptur... | Raise a `RuntimeError` if the device cannot be opened | Raise a `RuntimeError` if the device cannot be opened
| Python | mit | sourcebots/robotd,sourcebots/robotd | ---
+++
@@ -12,6 +12,8 @@
else:
argument_c = _cvcapture.ffi.NULL
self.instance = _cvcapture.lib.cvopen(argument_c)
+ if self.instance == _cvcapture.ffi.NULL:
+ raise RuntimeError("Unable to open capture device")
self.lock = threading.Lock()
def capture(... |
5b88a7068a6b245d99ef5998bbf659480fb85199 | cbc/environment.py | cbc/environment.py | import os
from .exceptions import IncompleteEnv
from tempfile import TemporaryDirectory
import time
class Environment(object):
def __init__(self, *args, **kwargs):
self.environ = os.environ.copy()
self.config = {}
self.cbchome = None
if 'CBC_HOME' in kwargs:
... | import os
from .exceptions import IncompleteEnv
from tempfile import TemporaryDirectory
import time
class Environment(object):
def __init__(self, *args, **kwargs):
self.environ = os.environ.copy()
self.config = {}
self.cbchome = None
if 'CBC_HOME' in kwargs:
... | Remove temp directory creation... not worth it | Remove temp directory creation... not worth it
| Python | bsd-3-clause | jhunkeler/cbc,jhunkeler/cbc,jhunkeler/cbc | ---
+++
@@ -12,6 +12,9 @@
if 'CBC_HOME' in kwargs:
self.cbchome = kwargs['CBC_HOME']
+
+ # I want the local user environment to override what is
+ # passed to the class.
if 'CBC_HOME' in self.environ:
self.cbchome = self.environ['CBC_HOME']
... |
c05ec7f6a869712ec49c2366016b325cf18f7433 | tests/test_no_broken_links.py | tests/test_no_broken_links.py | # -*- encoding: utf-8
"""
This test checks that all the internal links in the site (links that point to
other pages on the site) are pointing at working pages.
"""
from http_crawler import crawl
def test_no_links_are_broken():
responses = []
for rsp in crawl('http://0.0.0.0:5757/', follow_external_links=Fals... | # -*- encoding: utf-8
"""
This test checks that all the internal links in the site (links that point to
other pages on the site) are pointing at working pages.
"""
from http_crawler import crawl
def test_no_links_are_broken(baseurl):
responses = []
for rsp in crawl(baseurl, follow_external_links=False):
... | Use the pytest fixture for the URL | Use the pytest fixture for the URL
| Python | mit | alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net | ---
+++
@@ -7,9 +7,9 @@
from http_crawler import crawl
-def test_no_links_are_broken():
+def test_no_links_are_broken(baseurl):
responses = []
- for rsp in crawl('http://0.0.0.0:5757/', follow_external_links=False):
+ for rsp in crawl(baseurl, follow_external_links=False):
responses.append(rs... |
c1473e77a9b92c9bdf292017cb2f46bf8695dfd5 | afnumpy/lib/shape_base.py | afnumpy/lib/shape_base.py | import afnumpy
import arrayfire
import numpy
from .. import private_utils as pu
def tile(A, reps):
try:
tup = tuple(reps)
except TypeError:
tup = (reps,)
if(len(tup) > 4):
raise NotImplementedError('Only up to 4 dimensions are supported')
d = len(tup)
shape = list(A.shape)
... | import afnumpy
import arrayfire
import numpy
from IPython.core.debugger import Tracer
from .. import private_utils as pu
def tile(A, reps):
try:
tup = tuple(reps)
except TypeError:
tup = (reps,)
if(len(tup) > 4):
raise NotImplementedError('Only up to 4 dimensions are supported')
... | Make sure to cast to int as this does not work on old numpy versions | Make sure to cast to int as this does not work on old numpy versions
| Python | bsd-2-clause | FilipeMaia/afnumpy,daurer/afnumpy | ---
+++
@@ -1,6 +1,7 @@
import afnumpy
import arrayfire
import numpy
+from IPython.core.debugger import Tracer
from .. import private_utils as pu
def tile(A, reps):
@@ -26,6 +27,6 @@
if (d < 4):
tup = (1,)*(4-d) + tup
tup = pu.c2f(tup)
- s = arrayfire.tile(A.d_array, tup[0], tup[1], tup[2... |
8f188022d3e1ede210cfac2177dd924c9afe8f23 | tests/runalldoctests.py | tests/runalldoctests.py | import doctest
import glob
import pkg_resources
try:
pkg_resources.require('OWSLib')
except (ImportError, pkg_resources.DistributionNotFound):
pass
testfiles = glob.glob('*.txt')
for file in testfiles:
doctest.testfile(file)
| import doctest
import getopt
import glob
import sys
import pkg_resources
try:
pkg_resources.require('OWSLib')
except (ImportError, pkg_resources.DistributionNotFound):
pass
def run(pattern):
if pattern is None:
testfiles = glob.glob('*.txt')
else:
testfiles = glob.glob(pattern)
fo... | Add option to pick single test file from the runner | Add option to pick single test file from the runner
git-svn-id: 150a648d6f30c8fc6b9d405c0558dface314bbdd@620 b426a367-1105-0410-b9ff-cdf4ab011145
| Python | bsd-3-clause | kwilcox/OWSLib,bird-house/OWSLib,ocefpaf/OWSLib,b-cube/OWSLib,geographika/OWSLib,jaygoldfinch/OWSLib,tomkralidis/OWSLib,datagovuk/OWSLib,mbertrand/OWSLib,gfusca/OWSLib,KeyproOy/OWSLib,daf/OWSLib,dblodgett-usgs/OWSLib,geopython/OWSLib,jaygoldfinch/OWSLib,daf/OWSLib,kalxas/OWSLib,Jenselme/OWSLib,jachym/OWSLib,QuLogic/OWS... | ---
+++
@@ -1,5 +1,8 @@
import doctest
+import getopt
import glob
+import sys
+
import pkg_resources
try:
@@ -7,8 +10,23 @@
except (ImportError, pkg_resources.DistributionNotFound):
pass
-testfiles = glob.glob('*.txt')
+def run(pattern):
+ if pattern is None:
+ testfiles = glob.glob('*.txt')
+... |
acb10d5bf03be9681b222951c1accb6d419f9b32 | inboxen/tests/utils.py | inboxen/tests/utils.py | ##
# Copyright (C) 2014 Jessica Tallon & Matt Molyneaux
#
# This file is part of Inboxen.
#
# Inboxen is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | ##
# Copyright (C) 2014 Jessica Tallon & Matt Molyneaux
#
# This file is part of Inboxen.
#
# Inboxen is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | Update MockRequest to work with Django 1.9's session validation | Update MockRequest to work with Django 1.9's session validation
touch #124
| Python | agpl-3.0 | Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen | ---
+++
@@ -25,7 +25,7 @@
class MockRequest(HttpRequest):
"""Mock up a request object"""
- def __init__(self, user, session_id=1):
+ def __init__(self, user, session_id="12345678"):
super(MockRequest, self).__init__()
self.user = user
session = SessionMiddleware() |
7b5896700a6c7408d0b25bb4dde4942eaa9032bb | solum/tests/base.py | solum/tests/base.py | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Noorul Islam K M
#
# 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 applic... | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Noorul Islam K M
#
# 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 applic... | Support testscenarios by default in BaseTestCase | Support testscenarios by default in BaseTestCase
This allows one to use the scenario framework easily
from any test class.
Change-Id: Ie736138fe2d1e1d38f225547dde54df3f4b21032
| Python | apache-2.0 | devdattakulkarni/test-solum,gilbertpilz/solum,gilbertpilz/solum,stackforge/solum,openstack/solum,ed-/solum,ed-/solum,gilbertpilz/solum,openstack/solum,stackforge/solum,ed-/solum,ed-/solum,devdattakulkarni/test-solum,gilbertpilz/solum | ---
+++
@@ -15,11 +15,12 @@
# under the License.
from oslo.config import cfg
+import testscenarios
from solum.openstack.common import test
-class BaseTestCase(test.BaseTestCase):
+class BaseTestCase(testscenarios.WithScenarios, test.BaseTestCase):
"""Test base class."""
def setUp(self): |
8c10646768818a56ee89ff857318463da838f813 | connect_ffi.py | connect_ffi.py | from cffi import FFI
ffi = FFI()
#Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h
with open("spotify.processed.h") as file:
header = file.read()
ffi.cdef(header)
ffi.cdef("""
void *malloc(size_t size);
void exit(int status);
""")
C = ffi.dlopen(None)
l... | import os
from cffi import FFI
ffi = FFI()
library_name = "spotify.processed.h"
library_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), libraryName)
#Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h
with open(library_path) as file:
heade... | Add complete path of spotify.processed.h | Add complete path of spotify.processed.h
Add complete path of spotify.processed.h so it points to the same directory where is the file | Python | apache-2.0 | chukysoria/spotify-connect-web,chukysoria/spotify-connect-web,chukysoria/spotify-connect-web,chukysoria/spotify-connect-web | ---
+++
@@ -1,8 +1,12 @@
+import os
from cffi import FFI
ffi = FFI()
+library_name = "spotify.processed.h"
+
+library_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), libraryName)
#Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h
-with o... |
ede7158c611bf618ee03989d33c5fe6a091b7d66 | tests/testapp/models.py | tests/testapp/models.py | from __future__ import absolute_import
import sys
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
import rules
@python_2_unicode_compatible
class Book(models.Model):
isbn = models.CharField(max_length=50, unique=True)
title = model... | from __future__ import absolute_import
import sys
from django.conf import settings
from django.db import models
try:
from django.utils.encoding import python_2_unicode_compatible
except ImportError:
def python_2_unicode_compatible(c):
return c
import rules
@python_2_unicode_compatible
class Book(m... | Add shim for python_2_unicode_compatible in tests | Add shim for python_2_unicode_compatible in tests
| Python | mit | dfunckt/django-rules,dfunckt/django-rules,ticosax/django-rules,ticosax/django-rules,dfunckt/django-rules,ticosax/django-rules | ---
+++
@@ -4,7 +4,12 @@
from django.conf import settings
from django.db import models
-from django.utils.encoding import python_2_unicode_compatible
+
+try:
+ from django.utils.encoding import python_2_unicode_compatible
+except ImportError:
+ def python_2_unicode_compatible(c):
+ return c
import... |
0f546ce883bffa52d81ebfdc6eba005d6f2eca22 | build.py | build.py | #!/usr/bin/env python
import os
import subprocess
import sys
def build(pkgpath):
os.chdir(pkgpath)
targets = [
'build',
'package',
'install',
'clean',
'clean-depends',
]
for target in targets:
p = subprocess.Popen(
['bmake', target],
... | #!/usr/bin/env python
import os
import subprocess
import sys
def build(pkgpath):
os.chdir(pkgpath)
targets = [
'build',
'package',
'install',
'clean',
'clean-depends',
]
for target in targets:
p = subprocess.Popen(
['bmake', target],
... | Use more explicit variable names. | Use more explicit variable names.
| Python | isc | eliteraspberries/minipkg,eliteraspberries/minipkg | ---
+++
@@ -35,9 +35,9 @@
lines = sys.stdin.readlines()
pkgs = [line.rstrip('\n') for line in lines]
- pkgs = [pkg.split(' ')[0] for pkg in pkgs]
- for pkg in pkgs:
- print pkg
+ pkgpaths = [pkg.split(' ')[0] for pkg in pkgs]
+ for pkgpath in pkgpaths:
+ print pkgpath
os... |
fa85cbfe499599e8a0d667f25acae7fedcc13fb2 | invocations/testing.py | invocations/testing.py | from invoke import ctask as task
@task(help={
'module': "Just runs tests/STRING.py.",
'runner': "Use STRING to run tests instead of 'spec'."
})
def test(ctx, module=None, runner='spec'):
"""
Run a Spec or Nose-powered internal test suite.
"""
# Allow selecting specific submodule
specific_m... | from invoke import ctask as task
@task(help={
'module': "Just runs tests/STRING.py.",
'runner': "Use STRING to run tests instead of 'spec'.",
'opts': "Extra flags for the test runner",
})
def test(ctx, module=None, runner='spec', opts=None):
"""
Run a Spec or Nose-powered internal test suite.
... | Add flag passthrough for 'test' | Add flag passthrough for 'test'
| Python | bsd-2-clause | singingwolfboy/invocations,pyinvoke/invocations,mrjmad/invocations,alex/invocations | ---
+++
@@ -3,14 +3,17 @@
@task(help={
'module': "Just runs tests/STRING.py.",
- 'runner': "Use STRING to run tests instead of 'spec'."
+ 'runner': "Use STRING to run tests instead of 'spec'.",
+ 'opts': "Extra flags for the test runner",
})
-def test(ctx, module=None, runner='spec'):
+def test(ctx,... |
2fa2a2741a4f8e48d92d476859f73d46dc84a19a | apps/curia_vista/testing/test_council.py | apps/curia_vista/testing/test_council.py | from django.test import TestCase
from apps.curia_vista.models import Council
class TestCouncil(TestCase):
def setUp(self):
self.T = Council(id=1, updated='2010-12-26T13:07:49Z', abbreviation='NR', code='RAT_1_', type='N',
name='Nationalrat')
self.T.save()
def test___... | from django.test import TestCase
from apps.curia_vista.models import Council
class TestCouncil(TestCase):
def setUp(self):
self.T = Council(id=1, updated='2010-12-26T13:07:49Z', abbreviation='NR', code='RAT_1_', type='N',
name='Nationalrat')
self.T.save()
def test___... | Make the testing coverage great again | Make the testing coverage great again
| Python | agpl-3.0 | rettichschnidi/politkarma,rettichschnidi/politkarma,rettichschnidi/politkarma,rettichschnidi/politkarma | ---
+++
@@ -10,7 +10,7 @@
self.T.save()
def test___str__(self):
- self.assertEqual('Nationalrat', self.T.name)
+ self.assertEqual('Nationalrat', str(self.T))
def test_name_translation(self):
from django.utils import translation |
7f711f7da0003cf6f0335f33fb358e91d4e91cf7 | simpleadmindoc/management/commands/docgenapp.py | simpleadmindoc/management/commands/docgenapp.py | from django.core.management.base import AppCommand
class Command(AppCommand):
help = "Generate sphinx documentation skeleton for given apps."
def handle_app(self, app, **options):
# check if simpleadmindoc directory is setup
from django.db import models
from simpleadmindoc.generat... | from optparse import make_option
from django.core.management.base import AppCommand
class Command(AppCommand):
help = "Generate sphinx documentation skeleton for given apps."
option_list = AppCommand.option_list + (
make_option('--locale', '-l', default=None, dest='locale',
help='... | Add option to set locale for created documentation | Add option to set locale for created documentation
| Python | bsd-3-clause | bmihelac/django-simpleadmindoc,bmihelac/django-simpleadmindoc | ---
+++
@@ -1,11 +1,22 @@
+from optparse import make_option
+
from django.core.management.base import AppCommand
class Command(AppCommand):
help = "Generate sphinx documentation skeleton for given apps."
+ option_list = AppCommand.option_list + (
+ make_option('--locale', '-l', default=None, ... |
e858be9072b175545e17631ccd838f9f7d8a7e21 | tensorflow_datasets/dataset_collections/longt5/longt5.py | tensorflow_datasets/dataset_collections/longt5/longt5.py | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
#
# 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 appl... | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
#
# 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 appl... | Add homepage to LongT5 dataset collection | Add homepage to LongT5 dataset collection
PiperOrigin-RevId: 479013251
| Python | apache-2.0 | tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets | ---
+++
@@ -32,6 +32,7 @@
release_notes={
"1.0.0": "Initial release",
},
+ homepage="https://github.com/google-research/longt5",
)
@property |
af10508437be2001e9e12a369c4e8a973fd50ee8 | astral/api/handlers/node.py | astral/api/handlers/node.py | from astral.api.handlers.base import BaseHandler
from astral.models.node import Node
from astral.api.client import NodesAPI
import sys
import logging
log = logging.getLogger(__name__)
class NodeHandler(BaseHandler):
def delete(self, node_uuid=None):
"""Remove the requesting node from the list of known n... | from astral.api.handlers.base import BaseHandler
from astral.models.node import Node
from astral.api.client import NodesAPI
import logging
log = logging.getLogger(__name__)
class NodeHandler(BaseHandler):
def delete(self, node_uuid=None):
"""Remove the requesting node from the list of known nodes,
... | Clean up Node delete handler. | Clean up Node delete handler.
| Python | mit | peplin/astral | ---
+++
@@ -1,8 +1,6 @@
from astral.api.handlers.base import BaseHandler
from astral.models.node import Node
from astral.api.client import NodesAPI
-import sys
-
import logging
log = logging.getLogger(__name__)
@@ -14,36 +12,16 @@
unregistering the from the network.
"""
- if node_uui... |
75536b58ab934b3870236f2124dfb505e0a9299f | dvox/models/types.py | dvox/models/types.py | from bloop import String
class Position(String):
""" stores [2, 3, 4] as '2:3:4' """
def dynamo_load(self, value):
values = value.split(":")
return list(map(int, values))
def dynamo_dump(self, value):
return ":".join(map(str, value))
| from bloop import String
class Position(String):
""" stores [2, 3, 4] as '2:3:4' """
def dynamo_load(self, value):
values = value.split(":")
return list(map(int, values))
def dynamo_dump(self, value):
return ":".join(map(str, value))
class StringEnum(String):
"""Store an enu... | Add type for storing enums | Add type for storing enums
| Python | mit | numberoverzero/dvox | ---
+++
@@ -9,3 +9,18 @@
def dynamo_dump(self, value):
return ":".join(map(str, value))
+
+
+class StringEnum(String):
+ """Store an enum by the names of its values"""
+ def __init__(self, enum):
+ self.enum = enum
+ super().__init__()
+
+ def dynamo_load(self, value):
+ ... |
46259730666b967675336e7bda5014b17419614d | test/parse_dive.py | test/parse_dive.py | #! /usr/bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.get... | #! /usr/bin/python
import argparse
from xml.dom import minidom
O2=21
H2=0
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
ga... | Change the xml parser to output gas mixture content | Change the xml parser to output gas mixture content
| Python | isc | AquaBSD/libbuhlmann,AquaBSD/libbuhlmann,AquaBSD/libbuhlmann | ---
+++
@@ -1,6 +1,9 @@
#! /usr/bin/python
import argparse
from xml.dom import minidom
+
+O2=21
+H2=0
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
@@ -9,6 +12,16 @@
args = parser.parse_args()
path = args.path
doc = minidom.par... |
091b543fd8668d6f53bf126492aaaf47251d0672 | src/ggrc_basic_permissions/roles/ProgramEditor.py | src/ggrc_basic_permissions/roles/ProgramEditor.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "Private Program"
description = """
A user with authorization to edit mapping objects related to an access
controlled program.<br/><br/>When a person has this role they can map and
unmap object... | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "Private Program"
description = """
A user with authorization to edit mapping objects related to an access
controlled program.<br/><br/>When a person has this role they can map and
unmap object... | Add support for program editor to create and update snapshots | Add support for program editor to create and update snapshots
| Python | apache-2.0 | selahssea/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core | ---
+++
@@ -20,6 +20,7 @@
],
"create": [
"Audit",
+ "Snapshot",
"ObjectDocument",
"ObjectObjective",
"ObjectPerson",
@@ -29,6 +30,7 @@
"__GGRC_ALL__"
],
"update": [
+ "Snapshot",
"ObjectDocument",
"ObjectObjective",
... |
6876b6584cd90cca60fc21a53967dc1dfee6f2b4 | testing/models/test_epic.py | testing/models/test_epic.py | import pytest
from k2catalogue import models
@pytest.fixture
def epic():
return models.EPIC(epic_id=12345, ra=12.345, dec=67.894,
mag=None, campaign_id=1)
def test_repr(epic):
assert repr(epic) == '<EPIC: 12345>'
| import pytest
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue import models
@pytest.fixture
def epic():
return models.EPIC(epic_id=12345, ra=12.345, dec=67.894,
mag=None, campaign_id=1)
def test_repr(epic):
assert repr(epic) == '<EPIC: 12345>'
... | Add test for simbad query | Add test for simbad query
| Python | mit | mindriot101/k2catalogue | ---
+++
@@ -1,4 +1,8 @@
import pytest
+try:
+ from unittest import mock
+except ImportError:
+ import mock
from k2catalogue import models
@@ -12,3 +16,8 @@
def test_repr(epic):
assert repr(epic) == '<EPIC: 12345>'
+
+@mock.patch('k2catalogue.models.Simbad')
+def test_simbad_query(Simbad, epic):
+ ... |
94eecbd714e82ce179ca9985f9dd89dc72995070 | seleniumbase/fixtures/page_utils.py | seleniumbase/fixtures/page_utils.py | """
This module contains useful utility methods.
"""
def jq_format(code):
"""
Use before throwing raw code such as 'div[tab="advanced"]' into jQuery.
Selectors with quotes inside of quotes would otherwise break jQuery.
This is similar to "json.dumps(value)", but with one less layer of quotes.
"""
... | """
This module contains useful utility methods.
"""
def jq_format(code):
"""
Use before throwing raw code such as 'div[tab="advanced"]' into jQuery.
Selectors with quotes inside of quotes would otherwise break jQuery.
This is similar to "json.dumps(value)", but with one less layer of quotes.
"""
... | Add a method to extract the domain url from a full url | Add a method to extract the domain url from a full url
| Python | mit | ktp420/SeleniumBase,mdmintz/SeleniumBase,possoumous/Watchers,seleniumbase/SeleniumBase,mdmintz/seleniumspot,possoumous/Watchers,mdmintz/SeleniumBase,possoumous/Watchers,ktp420/SeleniumBase,ktp420/SeleniumBase,mdmintz/SeleniumBase,ktp420/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/Selen... | ---
+++
@@ -14,3 +14,11 @@
code = code.replace('\v', '\\v').replace('\a', '\\a').replace('\f', '\\f')
code = code.replace('\b', '\\b').replace('\u', '\\u').replace('\r', '\\r')
return code
+
+
+def get_domain_url(url):
+ url_header = url.split('://')[0]
+ simple_url = url.split('://')[1]
+ bas... |
3492ae03c9cfc8322ba60522779c7c0eeb642dd3 | server/models/event_subscription.py | server/models/event_subscription.py | """This module contains the SQLAlchemy EventSubscription class definition."""
from server.models.db import db
class EventSubscription(db.Model):
"""SQLAlchemy EventSubscription class definition."""
__tablename__ = 'event_subscriptions'
user_id = db.Column(
'user_id', db.Integer, db.ForeignKey('u... | """This module contains the SQLAlchemy EventSubscription class definition."""
from server.models.db import db
class EventSubscription(db.Model):
"""SQLAlchemy EventSubscription class definition."""
__tablename__ = 'event_subscriptions'
user_id = db.Column(
'user_id', db.Integer, db.ForeignKey('u... | Fix issue with deleting event subscriptions | Fix issue with deleting event subscriptions
| Python | mit | bnotified/api,bnotified/api | ---
+++
@@ -12,10 +12,6 @@
event_id = db.Column(
'event_id', db.Integer, db.ForeignKey('events.id'), primary_key=True)
- event = db.relationship('Event', backref=db.backref('event_subscriptions'))
-
- user = db.relationship('User', backref=db.backref('event_subscriptions'))
-
def __init__(s... |
7ad80225cd593689b33c59db0b8eb3e9cfd6e763 | tests/noreferences_tests.py | tests/noreferences_tests.py | """Test noreferences bot module."""
#
# (C) Pywikibot team, 2018-2020
#
# Distributed under the terms of the MIT license.
#
import pywikibot
from scripts.noreferences import NoReferencesBot
from tests.aspects import TestCase, unittest
class TestAddingReferences(TestCase):
"""Test adding references to section.""... | """Test noreferences bot module."""
#
# (C) Pywikibot team, 2018-2021
#
# Distributed under the terms of the MIT license.
#
import pywikibot
from scripts.noreferences import NoReferencesBot
from tests.aspects import TestCase, unittest
class TestAddingReferences(TestCase):
"""Test adding references to section.""... | Remove deprecated "gen" parameter of NoReferencesBot | [tests] Remove deprecated "gen" parameter of NoReferencesBot
Change-Id: I8140117cfc2278cfec751164a6d1d8f12bcaef84
| Python | mit | wikimedia/pywikibot-core,wikimedia/pywikibot-core | ---
+++
@@ -1,6 +1,6 @@
"""Test noreferences bot module."""
#
-# (C) Pywikibot team, 2018-2020
+# (C) Pywikibot team, 2018-2021
#
# Distributed under the terms of the MIT license.
#
@@ -20,7 +20,7 @@
def test_add(self):
"""Test adding references section."""
page = pywikibot.Page(self.site,... |
f14b1aa56b838469f63cec22c87e2e8c0c3f17c6 | csp.py | csp.py | csp = {
'default-src': '\'self\'',
'style-src': [
'\'self\'',
'\'unsafe-inline\''
],
'script-src': [
'\'self\'',
'cdn.httparchive.org',
'www.google-analytics.com',
'use.fontawesome.com',
'cdn.speedcurve.com',
'spdcrv.global.ssl.fastly.net',... | csp = {
'default-src': '\'self\'',
'style-src': [
'\'self\'',
'\'unsafe-inline\''
],
'script-src': [
'\'self\'',
'cdn.httparchive.org',
'www.google-analytics.com',
'use.fontawesome.com',
'cdn.speedcurve.com',
'spdcrv.global.ssl.fastly.net',... | Allow more discourse hostnames to fix CSP error | Allow more discourse hostnames to fix CSP error
| Python | apache-2.0 | HTTPArchive/beta.httparchive.org,HTTPArchive/beta.httparchive.org,HTTPArchive/beta.httparchive.org | ---
+++
@@ -36,7 +36,7 @@
'www.google.com',
's.g.doubleclick.net',
'stats.g.doubleclick.net',
- 'sjc3.discourse-cdn.com',
+ '*.discourse-cdn.com',
'res.cloudinary.com'
]
} |
a1d8a81bbd25404b1109688bded9bea923ba6771 | formly/tests/urls.py | formly/tests/urls.py | from django.conf.urls import include, url
urlpatterns = [
url(r"^", include("formly.urls", namespace="formly")),
]
| from django.conf.urls import include, url
from django.views.generic import TemplateView
urlpatterns = [
url(r"^home/", TemplateView.as_view(template_name="no-ie.html"), name="home"),
url(r"^", include("formly.urls", namespace="formly")),
]
| Add "home" url for testing | Add "home" url for testing
| Python | bsd-3-clause | eldarion/formly,eldarion/formly | ---
+++
@@ -1,5 +1,7 @@
from django.conf.urls import include, url
+from django.views.generic import TemplateView
urlpatterns = [
+ url(r"^home/", TemplateView.as_view(template_name="no-ie.html"), name="home"),
url(r"^", include("formly.urls", namespace="formly")),
] |
765864250faba841a2ee8f2fa669f57a25661737 | testapp/testapp/urls.py | testapp/testapp/urls.py | """testapp 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-bas... | """testapp 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-bas... | Add PDFDisplay view to the test app | Add PDFDisplay view to the test app
| Python | isc | hobarrera/django-afip,hobarrera/django-afip | ---
+++
@@ -23,6 +23,11 @@
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(
+ r'^invoices/pdfdisplay/(?P<pk>\d+)$',
+ views.ReceiptPDFDisplayView.as_view(),
+ name='receipt_pdf_view',
+ ),
+ url(
r'^invoices/pdf/(?P<pk>\d+)$',
views.ReceiptPDFView.as_view(... |
e3d3893bf4cb8aa782efb05771339a0d59451fe9 | xbrowse_server/base/management/commands/list_projects.py | xbrowse_server/base/management/commands/list_projects.py | from django.core.management.base import BaseCommand
from xbrowse_server.base.models import Project
class Command(BaseCommand):
"""Command to generate a ped file for a given project"""
def handle(self, *args, **options):
projects = Project.objects.all()
for project in projects:
ind... | from django.core.management.base import BaseCommand
from xbrowse_server.base.models import Project
class Command(BaseCommand):
"""Command to print out basic stats on some or all projects. Optionally takes a list of project_ids. """
def handle(self, *args, **options):
if args:
projects = [... | Print additional stats for each projects | Print additional stats for each projects
| Python | agpl-3.0 | ssadedin/seqr,macarthur-lab/seqr,macarthur-lab/seqr,ssadedin/seqr,ssadedin/seqr,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/xbrowse,macarthur-lab/xbrowse,ssadedin/seqr,ssadedin/seqr,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/xbrowse | ---
+++
@@ -3,14 +3,22 @@
from xbrowse_server.base.models import Project
class Command(BaseCommand):
- """Command to generate a ped file for a given project"""
+ """Command to print out basic stats on some or all projects. Optionally takes a list of project_ids. """
def handle(self, *args, **options)... |
870600482bd7d2b77542c169f78f125c17cec677 | editorsnotes/api/serializers/activity.py | editorsnotes/api/serializers/activity.py | from rest_framework import serializers
from editorsnotes.main.models.auth import (LogActivity, ADDITION, CHANGE,
DELETION)
VERSION_ACTIONS = {
ADDITION: 'added',
CHANGE: 'changed',
DELETION: 'deleted'
}
# TODO: make these fields nested, maybe
class ActivitySeria... | from rest_framework import serializers
from editorsnotes.main.models.auth import (LogActivity, ADDITION, CHANGE,
DELETION)
VERSION_ACTIONS = {
ADDITION: 'added',
CHANGE: 'changed',
DELETION: 'deleted'
}
# TODO: make these fields nested, maybe
class ActivitySeria... | Fix bug in action serializer | Fix bug in action serializer
Don't try to get URL of items that have been deleted
| Python | agpl-3.0 | editorsnotes/editorsnotes,editorsnotes/editorsnotes | ---
+++
@@ -21,6 +21,9 @@
model = LogActivity
fields = ('user', 'project', 'time', 'type', 'url', 'title', 'action',)
def get_object_url(self, obj):
- return None if obj.action == DELETION else obj.content_object.get_absolute_url()
+ if obj.action == DELETION or obj.content_object... |
d5820bef80ea4bdb871380dbfe41db12290fc5f8 | functest/opnfv_tests/features/odl_sfc.py | functest/opnfv_tests/features/odl_sfc.py | #!/usr/bin/python
#
# Copyright (c) 2016 All rights reserved
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import functest.core.feature_base... | #!/usr/bin/python
#
# Copyright (c) 2016 All rights reserved
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import functest.core.feature_base... | Make SFC test a python call to main() | Make SFC test a python call to main()
Instead of python -> bash -> python, call
the SFC test using the execute() method that
is inherited from FeatureBase and it's a bash
call by default.
With this change, we call the SFC test using main()
of run_tests.py of SFC repo and will have
real time output.
Change-Id: I6d5982... | Python | apache-2.0 | mywulin/functest,opnfv/functest,mywulin/functest,opnfv/functest | ---
+++
@@ -8,6 +8,7 @@
# http://www.apache.org/licenses/LICENSE-2.0
#
import functest.core.feature_base as base
+from sfc.tests.functest import run_tests
class OpenDaylightSFC(base.FeatureBase):
@@ -16,5 +17,6 @@
super(OpenDaylightSFC, self).__init__(project='sfc',
... |
6fa0db63d12f11f0d11a77c2d0799cd506196b5b | chatterbot/utils/clean.py | chatterbot/utils/clean.py | import re
def clean_whitespace(text):
"""
Remove any extra whitespace and line breaks as needed.
"""
# Replace linebreaks with spaces
text = text.replace("\n", " ").replace("\r", " ").replace("\t", " ")
# Remove any leeding or trailing whitespace
text = text.strip()
# Remove consecut... | import re
def clean_whitespace(text):
"""
Remove any extra whitespace and line breaks as needed.
"""
# Replace linebreaks with spaces
text = text.replace("\n", " ").replace("\r", " ").replace("\t", " ")
# Remove any leeding or trailing whitespace
text = text.strip()
# Remove consecut... | Update python3 html parser depricated method. | Update python3 html parser depricated method.
| Python | bsd-3-clause | Reinaesaya/OUIRL-ChatBot,gunthercox/ChatterBot,Gustavo6046/ChatterBot,Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,davizucon/ChatterBot,vkosuri/ChatterBot | ---
+++
@@ -36,9 +36,8 @@
parser = HTMLParser()
text = parser.unescape(text)
else:
- import html.parser
- parser = html.parser.HTMLParser()
- text = parser.unescape(text)
+ import html
+ text = html.unescape(text)
# Normalize unicode characters
# '... |
36deb1b445ba631666a0e4870f4e46c566d3ea78 | sms_939/controllers/sms_notification_controller.py | sms_939/controllers/sms_notification_controller.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | CHANGE mnc route to POST message | CHANGE mnc route to POST message
| Python | agpl-3.0 | eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland | ---
+++
@@ -15,7 +15,7 @@
class RestController(http.Controller):
- @http.route('/sms/mnc/', type='http', auth='public', methods=['GET'],
+ @http.route('/sms/mnc/', type='http', auth='public', methods=['POST'],
csrf=False)
def sms_notification(self, **parameters):
sms = reques... |
6e0e2a1e38506e85302197d4f700a924a609390c | pandas/compat/openpyxl_compat.py | pandas/compat/openpyxl_compat.py | """
Detect incompatible version of OpenPyXL
GH7169
"""
from distutils.version import LooseVersion
start_ver = '1.6.1'
stop_ver = '2.0.0'
def is_compat():
"""Detect whether the installed version of openpyxl is supported.
Returns
-------
compat : bool
``True`` if openpyxl is installed and is... | """
Detect incompatible version of OpenPyXL
GH7169
"""
from distutils.version import LooseVersion
start_ver = '1.6.1'
stop_ver = '2.0.0'
def is_compat():
"""Detect whether the installed version of openpyxl is supported.
Returns
-------
compat : bool
``True`` if openpyxl is installed and is... | Fix mismatched logic error in compatibility check | BUG: Fix mismatched logic error in compatibility check
| Python | bsd-3-clause | pratapvardhan/pandas,nmartensen/pandas,cbertinato/pandas,jmmease/pandas,kdebrab/pandas,Winand/pandas,DGrady/pandas,MJuddBooth/pandas,jorisvandenbossche/pandas,jreback/pandas,jmmease/pandas,harisbal/pandas,DGrady/pandas,harisbal/pandas,gfyoung/pandas,jorisvandenbossche/pandas,jreback/pandas,jreback/pandas,cbertinato/pan... | ---
+++
@@ -21,4 +21,4 @@
"""
import openpyxl
ver = LooseVersion(openpyxl.__version__)
- return LooseVersion(start_ver) < ver <= LooseVersion(stop_ver)
+ return LooseVersion(start_ver) <= ver < LooseVersion(stop_ver) |
a36e63037ce279d07a04074baf8c9f756dd8128a | wmtexe/cmi/make.py | wmtexe/cmi/make.py | import argparse
import yaml
from .bocca import make_project, ProjectExistsError
def main():
parser = argparse.ArgumentParser()
parser.add_argument('file', help='Project description file')
args = parser.parse_args()
try:
with open(args.file, 'r') as fp:
make_project(yaml.load(fp... | import argparse
import yaml
from .bocca import make_project, ProjectExistsError
def main():
parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'),
help='Project description file')
args = parser.parse_args()
try:
make_project(yaml... | Read input file from stdin. | Read input file from stdin.
| Python | mit | csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe | ---
+++
@@ -7,13 +7,13 @@
def main():
parser = argparse.ArgumentParser()
- parser.add_argument('file', help='Project description file')
+ parser.add_argument('file', type=argparse.FileType('r'),
+ help='Project description file')
args = parser.parse_args()
try:
- ... |
62c3fcd65b4c7d3cc4732885cf81640607a04480 | marty/commands/remotes.py | marty/commands/remotes.py | import datetime
import arrow
from marty.commands import Command
from marty.printer import printer
class Remotes(Command):
""" Show the list of configured remotes.
"""
help = 'Show the list of configured remotes'
def run(self, args, config, storage, remotes):
table_lines = [('<b>NAME</b>',... | import datetime
import arrow
from marty.commands import Command
from marty.printer import printer
class Remotes(Command):
""" Show the list of configured remotes.
"""
help = 'Show the list of configured remotes'
def run(self, args, config, storage, remotes):
table_lines = [('<b>NAME</b>',... | Clean useless format string in remote command | Clean useless format string in remote command
| Python | mit | NaPs/Marty | ---
+++
@@ -24,7 +24,7 @@
if remote.scheduler is not None:
next_date_text = '<color fg=yellow>now</color>'
else:
- latest_date_text = '%s' % latest_backup.start_date.humanize()
+ latest_date_text = latest_backup.start_date.humanize()
... |
24a6519b7d6a9e961adff1b23a3d64231fc9d233 | frappe/integrations/doctype/social_login_key/test_social_login_key.py | frappe/integrations/doctype/social_login_key/test_social_login_key.py | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
from frappe.integrations.doctype.social_login_key.social_login_key import BaseUrlNotSetError
import unittest
class TestSocialLoginKey(unittest.TestCase):
def test... | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
from frappe.integrations.doctype.social_login_key.social_login_key import BaseUrlNotSetError
import unittest
class TestSocialLoginKey(unittest.TestCase):
def test... | Add missing method required for test | test: Add missing method required for test
- backported create_or_update_social_login_key from v13
| Python | mit | vjFaLk/frappe,vjFaLk/frappe,vjFaLk/frappe,vjFaLk/frappe | ---
+++
@@ -22,3 +22,17 @@
kwargs["provider_name"] = "Test OAuth2 Provider"
doc = frappe.get_doc(kwargs)
return doc
+
+def create_or_update_social_login_key():
+ # used in other tests (connected app, oauth20)
+ try:
+ social_login_key = frappe.get_doc("Social Login Key", "frappe")
+ except frappe.DoesNotExist... |
2363cf9733006f08f2dc1061562bc29788206f21 | fabfile.py | fabfile.py | from fabric.api import cd, env, run, task
try:
import fabfile_local
_pyflakes = fabfile_local
except ImportError:
pass
@task
def update():
with cd("~/vagrant-installers"):
run("git pull")
@task
def all():
"Run the task against all hosts."
for _, value in env.roledefs.iteritems():
... | from fabric.api import cd, env, run, task
try:
import fabfile_local
_pyflakes = fabfile_local
except ImportError:
pass
@task
def update():
"Updates the installer generate code on the host."
with cd("~/vagrant-installers"):
run("git pull")
@task
def build():
"Builds the installer."
... | Add fab task to build | Add fab task to build
| Python | mit | redhat-developer-tooling/vagrant-installers,mitchellh/vagrant-installers,chrisroberts/vagrant-installers,redhat-developer-tooling/vagrant-installers,chrisroberts/vagrant-installers,chrisroberts/vagrant-installers,mitchellh/vagrant-installers,redhat-developer-tooling/vagrant-installers,chrisroberts/vagrant-installers,ch... | ---
+++
@@ -8,8 +8,15 @@
@task
def update():
+ "Updates the installer generate code on the host."
with cd("~/vagrant-installers"):
run("git pull")
+
+@task
+def build():
+ "Builds the installer."
+ with cd("~/vagrant-installers"):
+ run("rake")
@task
def all(): |
6c74b18372d3945f909ad63f6f58e11e7658282a | openacademy/model/openacademy_session.py | openacademy/model/openacademy_session.py | # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
instruct... | # -*- coding: utf-8 -*-
from openerp import fields, models
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(required=True)
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
instruct... | Add domain or and ilike | [REF] openacademy: Add domain or and ilike
| Python | apache-2.0 | deivislaya/openacademy-project | ---
+++
@@ -8,7 +8,11 @@
start_date = fields.Date()
duration = fields.Float(digits=(6, 2), help="Duration in days")
seats = fields.Integer(string="Number of seats")
- instructor_id = fields.Many2one('res.partner', string="Instructor")
+ instructor_id = fields.Many2one('res.partner', string="Instructor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.