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 |
|---|---|---|---|---|---|---|---|---|---|---|
656780b827202fc08992321ec2a98e91cb02da3b | utilities/__init__.py | utilities/__init__.py | #! /usr/bin/env python
from subprocess import Popen, PIPE
def _popen(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
| #! /usr/bin/env python
from subprocess import Popen, PIPE
def launch(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
def get_stdout(cmd):
"""
Fork the specified command, returning stdout
... | Add a wrapper to get just stdout back | Add a wrapper to get just stdout back
| Python | mit | IanLee1521/utilities | ---
+++
@@ -3,8 +3,15 @@
from subprocess import Popen, PIPE
-def _popen(cmd):
+def launch(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
+
+
+def get_stdout(cmd):
+ """
+ Fork the spec... |
de3809a00703c5eaaaec856b152a2418debbb6c6 | plugins/Tools/MirrorTool/__init__.py | plugins/Tools/MirrorTool/__init__.py | from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object'
},
}
def register(app):
return MirrorTool.MirrorTool()
| from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object',
'icon': 'mirror.png'
},
}
def register(app):
return ... | Use the right icon for the mirror tool | Use the right icon for the mirror tool
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -8,7 +8,8 @@
},
'tool': {
'name': 'Mirror',
- 'description': 'Mirror Object'
+ 'description': 'Mirror Object',
+ 'icon': 'mirror.png'
},
}
|
1724d05226a301bcedfebe963006818461c1b457 | vispy/app/__init__.py | vispy/app/__init__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the modul... | # -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the modul... | Fix for the tests, not complaining allowed about set_interactive not being used. | Fix for the tests, not complaining allowed about set_interactive not being used.
| Python | bsd-3-clause | bollu/vispy,sbtlaarzc/vispy,michaelaye/vispy,jay3sh/vispy,ghisvail/vispy,dchilds7/Deysha-Star-Formation,Eric89GXL/vispy,QuLogic/vispy,dchilds7/Deysha-Star-Formation,jdreaver/vispy,RebeccaWPerry/vispy,hronoses/vispy,bollu/vispy,jdreaver/vispy,inclement/vispy,sbtlaarzc/vispy,QuLogic/vispy,julienr/vispy,michaelaye/vispy,E... | ---
+++
@@ -13,6 +13,6 @@
from .application import Application # noqa
from ._default_app import use_app, create, run, quit, process_events # noqa
from .canvas import Canvas, MouseEvent, KeyEvent # noqa
-from .inputhook import set_interactive
+from .inputhook import set_interactive #noqa
from .timer import Time... |
0daa2132c071cb667aca5dbc416872a278e91a2b | pycoin/coins/groestlcoin/hash.py | pycoin/coins/groestlcoin/hash.py | import hashlib
import groestlcoin_hash
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
| import hashlib
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
try:
import groestlcoin_hash
except ImportError:
t = 'Groestlcoin requires the groestlc... | Raise ImportError when GRS is used without dependency | Raise ImportError when GRS is used without dependency
| Python | mit | richardkiss/pycoin,richardkiss/pycoin | ---
+++
@@ -1,6 +1,4 @@
import hashlib
-
-import groestlcoin_hash
from pycoin.encoding.hexbytes import bytes_as_revhex
@@ -11,4 +9,11 @@
def groestlHash(data):
"""Groestl-512 compound hash."""
+ try:
+ import groestlcoin_hash
+ except ImportError:
+ t = 'Groestlcoin requires the groe... |
b1b8e06b2b0ae6c79b94bd8e7b0b49721b7bdc13 | web/attempts/tests.py | web/attempts/tests.py | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from rest_framework.test import APIClient
from users.models import User
# Create your tests here.
class TokenLoginTestCase(TestCase):
fixtures = ['users.json']
def testAttemptSubmit(self):
user = User.objects.get(username='matija')
client = APIClient()
... | Add simple Attempt submit test | Add simple Attempt submit test
| Python | agpl-3.0 | matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo | ---
+++
@@ -1,3 +1,33 @@
from django.test import TestCase
+from rest_framework.test import APIClient
+from users.models import User
+
# Create your tests here.
+class TokenLoginTestCase(TestCase):
+ fixtures = ['users.json']
+
+ def testAttemptSubmit(self):
+ user = User.objects.get(username='matija'... |
4ed701a7afad4c8c3c04097e449e930cc4545e0d | mendel/admin.py | mendel/admin.py | from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
pass
class CategoryAdmin(ImportExportModelAdmin):
pass
class Docum... | from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
list_display = ('id', 'name')
pass
class CategoryAdmin(ImportExportM... | Add list_displays for Admin views | Add list_displays for Admin views
| Python | agpl-3.0 | Architizer/mendel,Architizer/mendel,Architizer/mendel,Architizer/mendel | ---
+++
@@ -6,22 +6,27 @@
class KeywordAdmin(ImportExportModelAdmin):
+ list_display = ('id', 'name')
pass
class CategoryAdmin(ImportExportModelAdmin):
+ list_display = ('id', 'name')
pass
class DocumentAdmin(ImportExportModelAdmin):
+ list_display = ('id', 'title', 'description')
... |
d879c6338449cd0c2f3c9a84162b3de688a55105 | webdiff/gitwebdiff.py | webdiff/gitwebdiff.py | #!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any... | #!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any... | Exit cleanly from 'git webdiff' | Exit cleanly from 'git webdiff'
- Don't allow a KeyboardInterrupt/sigint exception propagate up
to the user when exiting webdiff with Ctrl-C
| Python | apache-2.0 | daytonb/webdiff,danvk/webdiff,daytonb/webdiff,daytonb/webdiff,danvk/webdiff,danvk/webdiff,danvk/webdiff,daytonb/webdiff,danvk/webdiff | ---
+++
@@ -17,9 +17,12 @@
# "git webdiff <sha>". This allows special treatment (e.g. for
# staging diffhunks).
os.environ['WEBDIFF_FROM_HEAD'] = 'yes'
-
- sys.exit(subprocess.call(
- 'git difftool -d -x webdiff'.split(' ') + sys.argv[1:]))
+
+ try:
+ subprocess.call... |
a06f586ba95148643561122f051087db7b63fecb | registries/views.py | registries/views.py | from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organizatio... | from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organizatio... | Add prefetch to reduce queries on province_state | Add prefetch to reduce queries on province_state
| Python | apache-2.0 | rstens/gwells,rstens/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells | ---
+++
@@ -6,7 +6,7 @@
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
- queryset = Organization.objects.all()
+ queryset = Organization.objects.all().select_related('province_state')
serializer_class = DrillerListSerializer
# Create your views here. |
67fb6076b98a25f22a343f0c6ec62193ed86125a | bmi_ilamb/bmi_ilamb.py | bmi_ilamb/bmi_ilamb.py | #! /usr/bin/env python
import sys
import subprocess
from basic_modeling_interface import Bmi
class BmiIlamb(Bmi):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._a... | """Basic Model Interface (BMI) for the ILAMB benchmarking system."""
import os
import subprocess
from basic_modeling_interface import Bmi
from .config import Configuration
class BmiIlamb(Bmi):
_component_name = 'ILAMB'
_command = 'ilamb-run'
_args = None
def __init__(self):
self._time = self... | Update ILAMB BMI to use Configuration | Update ILAMB BMI to use Configuration
I also set ILAMB_ROOT and MPLBACKEND at `initialize`. Not sure if
there's a better location.
| Python | mit | permamodel/bmi-ilamb | ---
+++
@@ -1,33 +1,40 @@
-#! /usr/bin/env python
-import sys
+"""Basic Model Interface (BMI) for the ILAMB benchmarking system."""
+
+import os
import subprocess
from basic_modeling_interface import Bmi
+from .config import Configuration
class BmiIlamb(Bmi):
+ _component_name = 'ILAMB'
_command = 'ila... |
b8df411dc6cbbad981c98d918627143ffd1c9ef3 | kmeldb/AlbumIndexEntry.py | kmeldb/AlbumIndexEntry.py | from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._title_numbers = []
self._discs_and_tracks = {}
for title in self._titles:
# S... | from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of th... | Return title numbers in disc and track order, increment disc number if duplicated track number | Return title numbers in disc and track order, increment disc number if duplicated track number
| Python | apache-2.0 | chrrrisw/kmel_db,chrrrisw/kmel_db | ---
+++
@@ -6,22 +6,26 @@
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
- self._title_numbers = []
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of the titles
... |
a657792c10f59ed94af3039807ef92318b5c23f9 | src/graphql/pyutils/is_iterable.py | src/graphql/pyutils/is_iterable.py | from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not isinstance(array, Co... | from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not issubclass(array, Co... | Correct a workaround for PyPy | Correct a workaround for PyPy
| Python | mit | graphql-python/graphql-core | ---
+++
@@ -7,7 +7,7 @@
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
-if not isinstance(array, Collection): # PyPy issue 3820
+if not issubclass(array, Collection): # PyPy <= 7.3.9
collection_types.append(array)
c... |
3749acbad597974ef2507b2e7e27240937658c0b | nilmtk/plots.py | nilmtk/plots.py | from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series w... | from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series w... | Fix bug where timezone was not used for xaxis. | Fix bug where timezone was not used for xaxis.
| Python | apache-2.0 | jaduimstra/nilmtk,josemao/nilmtk,pauldeng/nilmtk,AlexRobson/nilmtk,mmottahedi/nilmtk,nilmtk/nilmtk,nilmtk/nilmtk,HarllanAndrye/nilmtk | ---
+++
@@ -21,10 +21,12 @@
date_format : str, optional, default='%d/%m/%y %H:%M:%S'
"""
if ax is None:
- ax = plt.gca()
- ax.xaxis.axis_date(tz=series.index.tzinfo)
- ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format))
+ fig, ax = plt.subplots(1)
x = _to_ordinalf_n... |
6d2d9088797aace5698a0e44ac3ed725148dd60b | decorators.py | decorators.py | from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorat... | from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorat... | Fix typo in login_required decorator | Fix typo in login_required decorator
| Python | mit | RuddockHouse/RuddockWebsite,RuddockHouse/RuddockWebsite,RuddockHouse/RuddockWebsite | ---
+++
@@ -20,7 +20,7 @@
# Check permissions.
if permission != None:
if not auth.check_permission(permission):
- flash("You do have have permission to access this page.")
+ flash("You do not have permission to access this page.")
session['next'] = request.url
... |
21ce1aeb0359ef760a7936ed4123041e29b4f0b1 | scripts/maf_limit_to_species.py | scripts/maf_limit_to_species.py | #!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys... | #!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys... | Remove all-gap columns after removing rows of the alignment | Remove all-gap columns after removing rows of the alignment
| Python | mit | bxlab/bx-python,bxlab/bx-python,bxlab/bx-python | ---
+++
@@ -29,6 +29,7 @@
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
+ m.remove_all_gap_columns()
if len( m.components ) > 1:
maf_writer.write( m )
|
9d44c515dbb253e214ac0cd1145bddacc2586380 | example/urls.py | example/urls.py | from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
u... | from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.views.generic import RedirectView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comme... | Fix running the example project with Django 1.5 | Fix running the example project with Django 1.5
| Python | apache-2.0 | django-fluent/django-fluent-comments,akszydelko/django-fluent-comments,akszydelko/django-fluent-comments,Afnarel/django-fluent-comments,Afnarel/django-fluent-comments,edoburu/django-fluent-comments,Afnarel/django-fluent-comments,PetrDlouhy/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluen... | ---
+++
@@ -1,5 +1,6 @@
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
+from django.views.generic import RedirectView
admin.autodiscover()
urlpatterns = patterns('',
@@ -9,5 +10,5 @@
url(r'^comments/', include('fluent_comments.urls')),
url(r'^articles/', ... |
c92a56dc937dc414139e2bff958190cfb18de5d9 | tests/basics/try2.py | tests/basics/try2.py | # nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print... | # nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print... | Add testcase with exception handler spread across functions. | Add testcase with exception handler spread across functions.
| Python | mit | SHA2017-badge/micropython-esp32,skybird6672/micropython,vriera/micropython,SHA2017-badge/micropython-esp32,jimkmc/micropython,cnoviello/micropython,cloudformdesign/micropython,emfcamp/micropython,dhylands/micropython,xuxiaoxin/micropython,AriZuu/micropython,cloudformdesign/micropython,selste/micropython,ryannathans/mic... | ---
+++
@@ -21,3 +21,20 @@
bar()
except NameError:
print("except 1")
+
+# Check that exceptions across function boundaries work as expected
+def func1():
+ try:
+ print("try func1")
+ func2()
+ except NameError:
+ print("except func1")
+
+def func2():
+ try:
+ print("tr... |
33c7bd546236497aae9b0c96d6ae4c41f317a00e | saau/sections/transportation/data.py | saau/sections/transportation/data.py | from operator import itemgetter
from itertools import chain
from typing import List
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
... | from operator import itemgetter
from itertools import chain
from typing import List
import cgi
from urllib.parse import parse_qs
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
cgi.parse_qs = parse_qs
def get_layers(service):
layers = service.layer... | Patch missing method on cgi package | Patch missing method on cgi package
| Python | mit | Mause/statistical_atlas_of_au | ---
+++
@@ -1,12 +1,18 @@
from operator import itemgetter
from itertools import chain
from typing import List
+
+import cgi
+from urllib.parse import parse_qs
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
+
+
+cgi.parse_qs = parse_qs
def g... |
a818427216f71272ae8410f63927db4891dbe39e | netmiko/hp/hp_procurve_ssh.py | netmiko/hp/hp_procurve_ssh.py | from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been establishe... | from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been establishe... | Fix issue with HP ProCurve stacks and multiple hit enter to continue messages | Fix issue with HP ProCurve stacks and multiple hit enter to continue messages
| Python | mit | fooelisa/netmiko,ktbyers/netmiko,shamanu4/netmiko,ktbyers/netmiko,isidroamv/netmiko,fooelisa/netmiko,shamanu4/netmiko,isidroamv/netmiko | ---
+++
@@ -13,6 +13,8 @@
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
+ time.sleep(1 * delay_factor)
+ self.write_channel("\n")
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sle... |
b301d8b9860f93a2c1fecd552f8edda4c813c04a | controller.py | controller.py | import requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
r = requests.post('http://localhost:3000/login', json=payload)
print r.status_code
| import requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
session = requests.Session()
r = session.post('http://localhost:3000/login', json=payload)
print r.status_code
payload = {'plant':{'name':'Test Name','species':'Test species','days_per_watering':'9','start_date':'9/9/19... | Add persistance of session across requests | Add persistance of session across requests
| Python | mit | darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker | ---
+++
@@ -2,6 +2,12 @@
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
-r = requests.post('http://localhost:3000/login', json=payload)
+session = requests.Session()
+r = session.post('http://localhost:3000/login', json=payload)
print r.status_code
+
+payload = {'plant':{'nam... |
701a18199fd230f70793b2e2c23b84506b50014e | reports/urls.py | reports/urls.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^reports/changes/lifetimes/(?P<slug>[^/.]+)/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^repo... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^children/(?P<slug>[^/.]+)/reports/changes/lifetimes/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
ur... | Change reports URLs to extend from /children/<slug>. | Change reports URLs to extend from /children/<slug>.
| Python | bsd-2-clause | cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy | ---
+++
@@ -6,21 +6,21 @@
from . import views
urlpatterns = [
- url(r'^reports/changes/lifetimes/(?P<slug>[^/.]+)/$',
+ url(r'^children/(?P<slug>[^/.]+)/reports/changes/lifetimes/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
- url(r'^... |
96a313eef46c31af3308805f10ffa63e330cc817 | 02/test_move.py | 02/test_move.py | from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
... | from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
... | Remove test of two-argument normalize function. | Remove test of two-argument normalize function.
| Python | mit | machinelearningdeveloper/aoc_2016 | ---
+++
@@ -17,9 +17,6 @@
assert normalize_index(1) == 1
assert normalize_index(0) == 0
assert normalize_index(-1) == 0
- assert normalize_index(2, 1) == 0
- assert normalize_index(5, 2) == 1
- assert normalize_index(-1, 4) == 0
def test_move(self):
asse... |
496d7fd6e9b2b581bc470b57984473b29d084e74 | contentpages/tests.py | contentpages/tests.py | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route =... | Add coverage for content pages functionality | Add coverage for content pages functionality
| Python | mit | bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject | ---
+++
@@ -1,3 +1,15 @@
from django.test import TestCase
+from django.urls import reverse
-# Create your tests here.
+from contentpages.views import ContentPage
+
+
+class TestContentPage(TestCase):
+
+ def test_get_template(self):
+
+ # test that the template view uses the template requested
+ #... |
641d548b536c1574454d0d140263c56b7a0abae9 | pyfr/mpiutil.py | pyfr/mpiutil.py | # -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is n... | # -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is n... | Improve how we abort MPI runs. | Improve how we abort MPI runs.
| Python | bsd-3-clause | tjcorona/PyFR,Aerojspark/PyFR,tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,iyer-arvind/PyFR | ---
+++
@@ -20,7 +20,7 @@
if MPI.COMM_WORLD.size > 1 and exc is not None and\
not isinstance(exc, KeyboardInterrupt) and\
(not isinstance(exc, SystemExit) or exc.code != 0):
- MPI.COMM_WORLD.Abort()
+ MPI.COMM_WORLD.Abort(1)
else:
MPI.Finalize()
|
09fed8f6bfb32f0f4c3aba45d16a153eaefe79e4 | fetch.py | fetch.py | import fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = ... | import fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = ... | Kill dad code for old compiler | Kill dad code for old compiler
| Python | mit | buffis/fetch | ---
+++
@@ -24,9 +24,6 @@
fetchinterpreter.handle_line(line)
print "Output", fetchinterpreter.get_output()
-def execute_compiled():
- execfile("fetchout.py")
-
if __name__ == "__main__":
print "\n--Lexed--"
print_lexed() |
a5fdffe2f37e2e1c34044c259ef56c0e5feca0cb | allegedb/allegedb/tests/test_branch_plan.py | allegedb/allegedb/tests/test_branch_plan.py | import pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2... | import pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2... | Add an extra check in that test | Add an extra check in that test
| Python | agpl-3.0 | LogicalDash/LiSE,LogicalDash/LiSE | ---
+++
@@ -31,3 +31,7 @@
orm.turn = 2
assert 1 not in g
assert 2 not in g
+ orm.turn = 0
+ orm.branch = 'trunk'
+ orm.turn = 2
+ assert 2 in g |
46ebeba28f8fbb9d43457aa3fa539b29048a581b | netbox/users/api/views.py | netbox/users/api/views.py | from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(Model... | from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(Model... | Set default ordering for user and group API endpoints | Set default ordering for user and group API endpoints
| Python | apache-2.0 | digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox | ---
+++
@@ -13,13 +13,13 @@
#
class UserViewSet(ModelViewSet):
- queryset = RestrictedQuerySet(model=User).prefetch_related('groups')
+ queryset = RestrictedQuerySet(model=User).prefetch_related('groups').order_by('username')
serializer_class = serializers.UserSerializer
filterset_class = filters.... |
b9fbc9ba6ab2c379e26d6e599fcaaf6ab9b84473 | server/slack.py | server/slack.py | #!/usr/bin/python2.7
import json
import kartlogic.rank
import logging
import prettytable
import util.web
import util.slack
def handler(event, context):
logging.warning(event['body'])
logging.warning(json.dumps(util.slack.parse_input(event['body'])))
return util.web.respond_success("Successful")
def rank... | #!/usr/bin/python2.7
import kartlogic.rank
import prettytable
import util.web as webutil
import util.slack as slackutil
def handler(event, context):
input_data = slackutil.slack.parse_input(event['body'])
if slackutil.validate_slack_token(input_data) is False:
return webutil.respond_unauthorized("Inv... | Add Slack token validation to handler | Add Slack token validation to handler
| Python | mit | groppe/mario | ---
+++
@@ -1,16 +1,17 @@
#!/usr/bin/python2.7
-import json
import kartlogic.rank
-import logging
import prettytable
-import util.web
-import util.slack
+import util.web as webutil
+import util.slack as slackutil
def handler(event, context):
- logging.warning(event['body'])
- logging.warning(json.dumps(... |
d7e9244dcbfcb068305ab37ba2e08f0c19ffdd7d | nodeconductor/core/log.py | nodeconductor/core/log.py | from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra'] = {'eve... | from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter, object):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra']... | Fix EventLoggerAdapter to work on py2.6 | Fix EventLoggerAdapter to work on py2.6
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | ---
+++
@@ -3,7 +3,7 @@
import logging
-class EventLoggerAdapter(logging.LoggerAdapter):
+class EventLoggerAdapter(logging.LoggerAdapter, object):
"""
LoggerAdapter
""" |
506b193781462b0771e01df383d1197f64d576d4 | tests/basics/ModuleAttributes.py | tests/basics/ModuleAttributes.py | # Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... | # Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... | Cover the "__debug__" attribute as well. | Cover the "__debug__" attribute as well.
| Python | apache-2.0 | wfxiang08/Nuitka,tempbottle/Nuitka,tempbottle/Nuitka,wfxiang08/Nuitka,tempbottle/Nuitka,kayhayen/Nuitka,wfxiang08/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka,tempbottle/Nuitka,wfxiang08/Nuitka | ---
+++
@@ -24,3 +24,4 @@
print "doc:", __doc__
print "filename:", __file__
print "builtins:", __builtins__
+print "debug", __debug__ |
f347341d138bb4f610dcca9c9791001d54e734be | diceclient.py | diceclient.py | #!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["hos... | #!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["hos... | Add a command line option for number of sides. | Add a command line option for number of sides.
| Python | mit | dripton/ampchat | ---
+++
@@ -14,16 +14,17 @@
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", default_port, "server port"],
+ ["sides", "s", 6, "number of sides"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
-def roll_... |
b71a96f818c66b5578fb7c4475b67ecdcb16937a | recipes/recipe_modules/gclient/tests/sync_failure.py | recipes/recipe_modules/gclient/tests/sync_failure.py | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclien... | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclien... | Replace customzied test failure assertion with ResultReasonRE from engine | Replace customzied test failure assertion with ResultReasonRE from engine
This change is to facilitate the annotation protocol -> luciexe protocol
migration in the future. The failure response structure will be changed
after the migration. Therefore, we only need to change the
implementation detail of ResultReasonRE a... | Python | bsd-3-clause | CoherentLabs/depot_tools,CoherentLabs/depot_tools | ---
+++
@@ -14,9 +14,7 @@
yield api.test(
'no-json',
api.override_step_data('gclient sync', retcode=1),
- api.post_check(
- lambda check, steps:
- check(not steps['$result']['failure']['humanReason']
- .startswith('Uncaught Exception'))),
+ # Should not fail... |
caab908d8f8948c3035c94018d7a1e31332edbad | udata/tests/frontend/__init__.py | udata/tests/frontend/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).crea... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).crea... | Add traces if there is no JSON-LD while it was expected | Add traces if there is no JSON-LD while it was expected
| Python | agpl-3.0 | opendatateam/udata,opendatateam/udata,etalab/udata,jphnoel/udata,jphnoel/udata,etalab/udata,davidbgk/udata,davidbgk/udata,jphnoel/udata,etalab/udata,davidbgk/udata,opendatateam/udata | ---
+++
@@ -21,5 +21,7 @@
# The first ? is used to name the extracted string
# The second ? is used to express the non-greediness of the extraction
pattern = '<script id="json_ld" type="application/ld\+json">(?P<json_ld>[\s\S]*?)</script>'
- json_ld = re.search(pattern, response.data... |
62cc65003a426c7144da5e24f4806eb89cfd8118 | polling_stations/apps/data_collection/management/commands/import_south_cambridge.py | polling_stations/apps/data_collection/management/commands/import_south_cambridge.py | from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
... | from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
... | Comment out South Cambridgeshire election id | Comment out South Cambridgeshire election id
Update provided but queries to chase :(
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations | ---
+++
@@ -7,5 +7,5 @@
elections = [
'local.cambridgeshire.2017-05-04',
'mayor.cambridgeshire-and-peterborough.2017-05-04',
- 'parl.2017-06-08'
+ #'parl.2017-06-08'
] |
cf297fc336d069b9210cfebec9f2cd724faa62fa | src/acme/demo_bundle/command.py | src/acme/demo_bundle/command.py | # -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.co... | # -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.co... | Update with last version of pymfony | Update with last version of pymfony
| Python | mit | pymfony/pymfony-standard | ---
+++
@@ -16,7 +16,7 @@
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
-class DemoController(ContainerAware):
+class DemoCommand(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
|
d7fdebdc4ce52e59c126a27ea06171994a6c846b | src/config/common/ssl_adapter.py | src/config/common/ssl_adapter.py | """ HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both... | """ HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both... | Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module. This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__. | Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module.
This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__.
Courtesy: https://github.com/sigmavirus24/requests-toolbelt/commit/decadbd3512444889feb30cf1ff2f1448a3ecfca
Closes-Bug:#1... | Python | apache-2.0 | codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller | ---
+++
@@ -16,6 +16,7 @@
class SSLAdapter(HTTPAdapter):
'''An HTTPS Transport Adapter that can be configured with SSL/TLS
version.'''
+ HTTPAdapter.__attrs__.extend(['ssl_version'])
def __init__(self, ssl_version=None, **kwargs):
self.ssl_version = ssl_version |
01c17356bd9eed56979c55ccb55659508d08b218 | src/waldur_openstack/openstack_tenant/migrations/0004_fill_tenant_id.py | src/waldur_openstack/openstack_tenant/migrations/0004_fill_tenant_id.py | from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
tenant = service_settings.scope
if (
tenant
and ten... | from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
Tenant = apps.get_model('openstack', 'Tenant')
for service_settings in ServiceSettings.objects.filter(type='OpenS... | Fix migration: don't use virtual field scope. | Fix migration: don't use virtual field scope.
| Python | mit | opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind | ---
+++
@@ -1,17 +1,21 @@
+from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
+ Tenant = apps.get_model('openstack', 'Tenant')
for service_settings in Servic... |
8bbdadc61611512dbd1bfbff2495ff0dee101054 | adhocracy4/categories/forms.py | adhocracy4/categories/forms.py | from django import forms
from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
queryset = category_models.Categor... | from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
field = self.fields[self.category_field_name]
field... | Modify generated category form field instead of reinitialize it | Modify generated category form field instead of reinitialize it
The category fields had not been translated as the field had been
reinitialized instead of modified. With this PR the auto generated field
(with its localized verbose_name) will be kept and adapted to the
filtered queryset.
Furthermore the required param... | Python | agpl-3.0 | liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4 | ---
+++
@@ -1,5 +1,3 @@
-from django import forms
-
from adhocracy4.categories import models as category_models
@@ -9,13 +7,16 @@
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
- queryset = category_models.Category.objects.filter... |
957f3e82f13dc8a9bd09d40a25c1f65847e144b8 | aiohttp_json_api/decorators.py | aiohttp_json_api/decorators.py | from functools import wraps
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
context = kwargs.get('context')
... | from functools import wraps
from aiohttp import web
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI, JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
... | Fix bug with arguments handling in JSON API content decorator | Fix bug with arguments handling in JSON API content decorator
| Python | mit | vovanbo/aiohttp_json_api | ---
+++
@@ -1,19 +1,21 @@
from functools import wraps
+from aiohttp import web
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
-from .const import JSONAPI_CONTENT_TYPE
+from .const import JSONAPI, JSONAPI_CONTENT_TYPE
def jsonapi_conten... |
fb59f2e0bd01d75c90ea3cc0089c24fc5db86e8e | config/jupyter/jupyter_notebook_config.py | config/jupyter/jupyter_notebook_config.py | import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_extension_failures = True
c... | import json
import os
import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_exten... | Set $NBGALLERY_URL to override gallery location | Set $NBGALLERY_URL to override gallery location
| Python | mit | jupyter-gallery/jupyter-docker,jupyter-gallery/jupyter-docker,jupyter-gallery/jupyter-docker | ---
+++
@@ -1,3 +1,5 @@
+import json
+import os
import sys
sys.path.append('/root/.jupyter/extensions/')
@@ -14,3 +16,13 @@
# needed to receive notebooks from the gallery
c.JupyterApp.disable_check_xsrf = True
+
+# Override gallery location
+nbgallery_url = os.getenv('NBGALLERY_URL')
+if nbgallery_url:
+ pri... |
08c54be9e2e34b5655b2ea6f7778a83b606acade | src/lexus/lexical_simplifier.py | src/lexus/lexical_simplifier.py | __author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplif... | __author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplif... | Reduce the runtime of webapp api | Reduce the runtime of webapp api
| Python | mit | Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify | ---
+++
@@ -22,6 +22,8 @@
results = []
+ replacer = Replacer(lwlm_n)
+
for i in range(length):
sanitized_word = Sanitizer.sanitize_word(words[i])
@@ -29,7 +31,6 @@
if sanitized_word == '':
continue
- replacer = Replacer(lwlm_n)
... |
6d1612698c2e42ab60d521915f31ff08832e3745 | waterbutler/providers/dropbox/settings.py | waterbutler/providers/dropbox/settings.py | try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropbox.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://api-content.dropbox.com/1/')
| try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropboxapi.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://content.dropboxapi.com/1/')
| Update drobox api urls h/t @felliott | Update drobox api urls h/t @felliott
| Python | apache-2.0 | RCOSDP/waterbutler,rdhyee/waterbutler,TomBaxter/waterbutler,felliott/waterbutler,CenterForOpenScience/waterbutler,Johnetordoff/waterbutler | ---
+++
@@ -6,5 +6,5 @@
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
-BASE_URL = config.get('BASE_URL', 'https://api.dropbox.com/1/')
-BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://api-content.dropbox.com/1/')
+BASE_URL = config.get('BASE_URL', 'https://api.dropboxapi.com/1/')
+BASE_CONTENT_... |
9d78a7be6ea922844bc9c6a0795af8d7b7a247a3 | bl/text.py | bl/text.py |
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn ... |
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn ... | Revert "allow to write Text with raw data" | Revert "allow to write Text with raw data"
This reverts commit d05df9ea67bc626adc7a4940c9bad4881d672a38.
| Python | mpl-2.0 | BlackEarth/bl,BlackEarth/bl | ---
+++
@@ -14,11 +14,10 @@
else:
self.text = String("")
- def write(self, fn=None, text=None, encoding='UTF-8', data=None, **args):
- if data is None:
- try:
- data = (text or self.text or '').encode(encoding)
- except:
- data = (t... |
c42092f643bf34c997f2b964e3d132ed95012755 | scipy/testing/nulltester.py | scipy/testing/nulltester.py | ''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, ... | ''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, ... | Fix bench error on scipy import when nose is not installed | Fix bench error on scipy import when nose is not installed
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3851 d6536bca-fef9-0310-8506-e4c0a848fbcf
| Python | bsd-3-clause | lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt | ---
+++
@@ -13,4 +13,6 @@
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
+ def bench(self, labels=None, *args, **kwargs):
+ raise ImportError, 'Need nose for benchmarks - see %s' % nose_url
|
50e972491e7fbe62045a6bda4351428769103c81 | annotateit/model/annotation.py | annotateit/model/annotation.py | from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_fil... | from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_fil... | Update for compatibility with pyes==0.19.1 | Update for compatibility with pyes==0.19.1
| Python | agpl-3.0 | openannotation/annotateit,openannotation/annotateit | ---
+++
@@ -16,7 +16,7 @@
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
- uris_res = cls.es.conn.search({
+ uris_res = cls.es.conn.search_raw({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0 |
d7a227ae5f0f53b5c620864df08c7b883402e968 | netmiko/brocade/brocade_nos_ssh.py | netmiko/brocade/brocade_nos_ssh.py | """Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
... | """Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
... | Add save_config for brocade VDX | Add save_config for brocade VDX
| Python | mit | ktbyers/netmiko,ktbyers/netmiko | ---
+++
@@ -19,3 +19,8 @@
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor)
+
+ def save_config(self):
+ """Save Config for Brocade VDX."""
+ self.send_command('copy running-config startup-config', '[Y/N]')
+ ... |
74888d07942c0ee9ab8accbe87732380a700f9d0 | rule.py | rule.py | class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
| Add PriceRule class and init method. | Add PriceRule class and init method.
| Python | mit | bsmukasa/stock_alerter | ---
+++
@@ -1 +1,9 @@
+class PriceRule:
+ """PriceRule is a rule that triggers when a stock price satisfies a condition.
+ The condition is usually greater, equal or lesser than a given value.
+ """
+
+ def __init__(self, symbol, condition):
+ self.symbol = symbol
+ self.condition = condit... | |
457a40d3487d59147bcea71dd06f49317167c8d1 | hash_table.py | hash_table.py | #!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
cla... | #!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
cla... | Build out set function of hash table class; still need to deal with outcome of setting multiple values to same key | Build out set function of hash table class; still need to deal with outcome of setting multiple values to same key
| Python | mit | jwarren116/data-structures-deux | ---
+++
@@ -33,5 +33,6 @@
else:
raise KeyError('Value not found')
- def set(self):
- pass
+ def set(self, key, val):
+ hashed_key = self.hash(key)
+ self.table[hashed_key].append((key, val)) |
84783cdcdd52108df359cbe2add8c41b92b97e0b | openfisca_web_api/scripts/serve.py | openfisca_web_api/scripts/serve.py | # -*- coding: utf-8 -*-
import os
import sys
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
hostname = 'localhost'
port = 2000
def main():
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-fr... | # -*- coding: utf-8 -*-
import os
import sys
import argparse
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
def main():
parser = argparse.ArgumentParser(description = __doc__)
parser.add_argument('-p', '--port', action = 'store', default ... | Allow port to be changed | Allow port to be changed
| Python | agpl-3.0 | openfisca/openfisca-web-api,openfisca/openfisca-web-api | ---
+++
@@ -1,19 +1,21 @@
# -*- coding: utf-8 -*-
-
import os
import sys
+import argparse
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
-hostname = 'localhost'
-port = 2000
+def main():
+ parser = argparse.ArgumentParser(descripti... |
8dae2049c96932855cc0162437d799e258f94a53 | test/absolute_import/local_module.py | test/absolute_import/local_module.py | """
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
i... | """
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
i... | Fix inaccuracy in test comment, since jedi now does the right thing | Fix inaccuracy in test comment, since jedi now does the right thing
| Python | mit | dwillmer/jedi,flurischt/jedi,mfussenegger/jedi,tjwei/jedi,flurischt/jedi,jonashaag/jedi,jonashaag/jedi,mfussenegger/jedi,tjwei/jedi,WoLpH/jedi,WoLpH/jedi,dwillmer/jedi | ---
+++
@@ -7,7 +7,7 @@
"""
from __future__ import absolute_import
-import unittest # this is stdlib unittest, but jedi gets the local one
+import unittest
class Assertions(unittest.TestCase): |
e697e9887fa681918c9b10367ee2319969f591d0 | test/auth/test_client_credentials.py | test/auth/test_client_credentials.py | from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_sessio... | from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_sessio... | Check for right kind of error in invalid creds test | Check for right kind of error in invalid creds test
| Python | apache-2.0 | Mendeley/mendeley-python-sdk | ---
+++
@@ -19,6 +19,8 @@
mendeley = configure_mendeley()
mendeley.client_secret += '-invalid'
auth = mendeley.start_client_credentials_flow()
-
- with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(InvalidClientError):
+
+ # We should never get an acce... |
634e389ed260b404327e303afb4f5a1dc931ee36 | storm/db.py | storm/db.py | from random import randrange
import time
from storm import error
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = p... | import time
from storm import error
from tornado import gen
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = passwo... | Make connection pool less smart | Make connection pool less smart
You have to extend it and implement your own get_db function to use a
connection pool now
| Python | mit | liujiantong/storm,ccampbell/storm | ---
+++
@@ -1,6 +1,6 @@
-from random import randrange
import time
from storm import error
+from tornado import gen
class Connection(object):
@@ -17,26 +17,10 @@
self.connection = connection
self.count = count
self.lifetime = lifetime
- self.db_connections = [];
- def crea... |
2f65eba48e5bdeac85b12cac014cb648d068da46 | tests/test_utils.py | tests/test_utils.py | import unittest
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def t... | import unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all... | Add unit test for is_safe_url utility function | Add unit test for is_safe_url utility function
| Python | mit | Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary | ---
+++
@@ -1,7 +1,7 @@
import unittest
from app import create_app, db
-from app.utils import get_or_create
+from app.utils import get_or_create, is_safe_url
from app.models import User
@@ -25,3 +25,9 @@
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, ... |
b33654567ad3588ba51874ef109a9ee8efc0b0f0 | tests/functional/firefox/test_hello.py | tests/functional/firefox/test_hello.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_... | Fix failing Firefox Hello test | Fix failing Firefox Hello test
| Python | mpl-2.0 | sgarrity/bedrock,TheJJ100100/bedrock,alexgibson/bedrock,schalkneethling/bedrock,TheJJ100100/bedrock,gerv/bedrock,mozilla/bedrock,flodolo/bedrock,kyoshino/bedrock,TheoChevalier/bedrock,mozilla/bedrock,sgarrity/bedrock,craigcook/bedrock,pascalchevrel/bedrock,alexgibson/bedrock,sylvestre/bedrock,Sancus/bedrock,ericawright... | ---
+++
@@ -22,7 +22,6 @@
def test_try_hello_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_try_hello_button_displayed
- assert not page.is_download_button_displayed
@pytest.mark.skip_if_firefox |
df790275ba9f06296f800ecd913eca8393c300c6 | psyparse/handler/base_handler.py | psyparse/handler/base_handler.py | class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
... | class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
... | Fix bug in exception throwing (it caused an exception!). | Fix bug in exception throwing (it caused an exception!).
| Python | mit | tnez/PsyParse | ---
+++
@@ -7,9 +7,9 @@
"""
def new(self, entry):
"""Create a new entry"""
- raise ("""'new' method not defined in handler subclass""")
+ raise Exception("""'new' method not defined in handler subclass""")
def update(self, entry, attribute, new_value):
"""Updat... |
567d7c57def91c95620e8e5b1acda640b9c48a9d | src/startGUI.py | src/startGUI.py | # -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWind... | # -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
from PySide import QtCore
import signal
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Con... | Allow quitting the application with SIGINT (Ctrl-C) | Allow quitting the application with SIGINT (Ctrl-C)
| Python | mit | sciapp/pyMolDyn,sciapp/pyMolDyn,sciapp/pyMolDyn,sciapp/pyMolDyn,sciapp/pyMolDyn | ---
+++
@@ -4,6 +4,8 @@
from gui import main_window
from core import volumes, control
from PySide import QtGui
+from PySide import QtCore
+import signal
import sys
import os
import core.calculation
@@ -30,4 +32,11 @@
control.update()
window.updatestatus()
+ # Let the Python interpreter run every ... |
370c49eba30253f259454884441e9921b51719ab | dudebot/ai.py | dudebot/ai.py | class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
pass
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
| class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
return False, ''
class message_must_begin_with_prefix(object):
"""A simple decorator so that a bot AI ... | Add some decorators to make life easier. | Add some decorators to make life easier.
| Python | bsd-2-clause | sujaymansingh/dudebot | ---
+++
@@ -7,7 +7,38 @@
pass
def respond(self, sender_nickname, message):
- pass
+ return False, ''
+
+
+class message_must_begin_with_prefix(object):
+ """A simple decorator so that a bot AI can ignore all messages that don't
+ begin with the given prefix.
+ That way you can h... |
96a08a9c7b11ce96de1c2034efcc19622c4eb419 | drillion/ship_keys.py | drillion/ship_keys.py | from pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.LEFT], right=[key.D, key.RIGHT],
thrust=[key.W, key.UP], fire=[key.S, key.DOWN])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[... | from pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.J], right=[key.D, key.L],
thrust=[key.W, key.I], fire=[key.S, key.K])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[key.J], rig... | Change second ship controls to IJKL | Change second ship controls to IJKL
| Python | mit | elemel/drillion | ---
+++
@@ -1,8 +1,8 @@
from pyglet.window import key
-PLAYER_SHIP_KEYS = dict(left=[key.A, key.LEFT], right=[key.D, key.RIGHT],
- thrust=[key.W, key.UP], fire=[key.S, key.DOWN])
+PLAYER_SHIP_KEYS = dict(left=[key.A, key.J], right=[key.D, key.L],
+ thrust=[key.W, key.I... |
074e711dd58e432c39906c1fe6f7e9944407b1e5 | changes/api/snapshot_details.py | changes/api/snapshot_details.py | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqpar... | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.api.serializer.models.snapshot import SnapshotWithImagesSerializer
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snaps... | Add images to snapshot details | Add images to snapshot details
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes | ---
+++
@@ -3,6 +3,7 @@
from flask.ext.restful import reqparse
from changes.api.base import APIView
+from changes.api.serializer.models.snapshot import SnapshotWithImagesSerializer
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, Sn... |
2b9efb699d557cbd47d54b10bb6ff8be24596ab4 | src/nodeconductor_assembly_waldur/packages/tests/unittests/test_models.py | src/nodeconductor_assembly_waldur/packages/tests/unittests/test_models.py | from decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory(components=[])
total = Decimal... | from decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory()
total = Decimal('0.00')
... | Update test according to factory usage | Update test according to factory usage
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind | ---
+++
@@ -10,7 +10,7 @@
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
- package_template = factories.PackageTemplateFactory(components=[])
+ package_template = factories.PackageTemplateFactory()
total = Decimal('0.00')
for t in mode... |
8c773a53902860409f83ff445402eb56d6376a88 | app/utils/settings.py | app/utils/settings.py | from app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
def __setitem__(self, key, value):
... | from app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
try:
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
except KeyError... | Add error handling for posts_per_page type conversion | Add error handling for posts_per_page type conversion
| Python | mit | Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger | ---
+++
@@ -5,7 +5,11 @@
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
- self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
+
+ try:
+ self.__setitem__('posts_per_page', int(... |
7dd467f474675c2c2535b6c3b925340b72959089 | tests/settings.py | tests/settings.py | import os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', Tr... | import os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', Tr... | Use connection pool by default during testing | Use connection pool by default during testing
| Python | mit | m32/pytds,m32/pytds,denisenkom/pytds,tpow/pytds,denisenkom/pytds,tpow/pytds | ---
+++
@@ -21,6 +21,7 @@
'password': PASSWORD,
'use_mars': USE_MARS,
'bytes_to_unicode': True,
+ 'pooling': True,
}
if 'tds_version' in os.environ: |
69e081afd1d2b24d40a4992c6af4538aba86ca1c | brew_journal/brew_journal/urls.py | brew_journal/brew_journal/urls.py | from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
... | from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
... | Reset the base url matching regex to correctly reroute to the home page when provided an unknown url | Reset the base url matching regex to correctly reroute to the home page when provided an unknown url
| Python | apache-2.0 | moonboy13/brew-journal,moonboy13/brew-journal,moonboy13/brew-journal | ---
+++
@@ -18,5 +18,5 @@
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
# Default index view. Must be last to avoid accidentially catching other URLs
- url(r'^$', IndexView.as_view(), name='index'),
+ url(r'^.*$', IndexView.as_view(), name='index'),
) |
6d84cdb641d2d873118cb6cb26c5a7521ae40bd8 | dcclient/dcclient.py | dcclient/dcclient.py | """ Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from oslo.config import cfg
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
... | """ Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from neutron.openstack.common import log as logger
from oslo.config import cfg
LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
... | Add error treatment for existing network | Add error treatment for existing network
| Python | apache-2.0 | NeutronUfscarDatacom/DriverDatacom | ---
+++
@@ -6,8 +6,11 @@
from xml_manager.manager import ManagedXml
+from neutron.openstack.common import log as logger
from oslo.config import cfg
+
+LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
@@ -24,5 +27,8 @@
def create_network(self, vlan):
""" Creates a new n... |
e98f9fcc8537835b5a00bd0b6a755d7980a197de | template_tests/tests.py | template_tests/tests.py | import re
import os
from django.test import TestCase
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplates(TestCase):
def assertValidURLs(self, filename):
with open(filename) as f:
urls = [m.group('url') for m in re... | import re
import os
from django.test import TestCase
from django.utils.text import slugify
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplatesMeta(type):
def __new__(cls, name, bases, attrs):
def generate(template):
... | Use a metaclass instead of dirty dict()-mangling. | Use a metaclass instead of dirty dict()-mangling.
| Python | bsd-3-clause | lamby/django-template-tests | ---
+++
@@ -2,26 +2,36 @@
import os
from django.test import TestCase
+from django.utils.text import slugify
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
+class TestTemplatesMeta(type):
+ def __new__(cls, name, bases, attrs):
+ def... |
57560385ef05ba6a2234e43795a037a487f26cfd | djaml/utils.py | djaml/utils.py | import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(l... | import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(l... | Fix submodule attribute check for Django 1.4 compatibility | Fix submodule attribute check for Django 1.4 compatibility
| Python | mit | chartjes/djaml | ---
+++
@@ -9,7 +9,7 @@
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
- if hasattr(loader, 'load_template_source')]
+ if hasattr(loader, 'Loader')]
def get_submodules(package)... |
db08b3462fc217cfbf3644051f299ef5bbef3d14 | ckanext/stadtzhtheme/tests/test_validation.py | ckanext/stadtzhtheme/tests/test_validation.py | import nose
from ckanapi import TestAppCKAN, ValidationError
from ckan.tests import helpers, factories
eq_ = nose.tools.eq_
assert_true = nose.tools.assert_true
class TestValidation(helpers.FunctionalTestBase):
def test_invalid_url(self):
"""Test that an invalid resource url is caught by our validator.
... | import pytest
from ckanapi import ValidationError
from ckan.tests import helpers, factories
from ckantoolkit import config
@pytest.mark.ckan_config("ckan.plugins", "stadtzhtheme")
@pytest.mark.usefixtures("clean_db", "with_plugins")
class TestValidation(object):
def test_invalid_url(self):
"""Test that a... | Update tests to use pytest instead of nose | tests: Update tests to use pytest instead of nose
| Python | agpl-3.0 | opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme | ---
+++
@@ -1,32 +1,28 @@
-import nose
-from ckanapi import TestAppCKAN, ValidationError
+import pytest
+from ckanapi import ValidationError
from ckan.tests import helpers, factories
-
-eq_ = nose.tools.eq_
-assert_true = nose.tools.assert_true
+from ckantoolkit import config
-class TestValidation(helpers.Functi... |
22992aeeb123b061a9c11d812ac7fad6427453eb | timpani/themes.py | timpani/themes.py | import os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tab... | import os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tab... | Add template support to getCurrentTheme | Add template support to getCurrentTheme
| Python | mit | ollien/Timpani,ollien/Timpani,ollien/Timpani | ---
+++
@@ -18,10 +18,16 @@
except StopIteration:
return None
- themeFile = open(os.path.join(THEME_PATH, folderName, "theme.css"), "r")
+ themeFile = open(
+ os.path.join(THEME_PATH, folderName, "theme.css"), "r")
theme = themeFile.read()
themeFile.close()
- return theme
+ templateFile = open(
+... |
fa6402472e30f59e67acf45d9faba632a3efc5e8 | raiden/constants.py | raiden/constants.py | # -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
ROPSTEN_REGISTRY_ADDRESS = 'bbc60aa23059b039407ac008bd0b7e902890d382'
ROPSTEN_DISCOVERY_ADDRESS = '524b7dcacac3055bd42fc03b006e9fdcb607e2be'
MINUTE_SEC = 60
MINUTE_MS = 60 * 100... | # -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
# Deployed to Ropsten revival on 2017-06-19 from commit 2677298a69c1b1f35b9ab26beafe457acfdcc0ee
ROPSTEN_REGISTRY_ADDRESS = 'aff1f958c69a6820b08a02549ff9041629ae8257'
ROPSTEN_DIS... | Update pre-deployed Ropsten contract addresses | Update pre-deployed Ropsten contract addresses | Python | mit | hackaugusto/raiden,tomashaber/raiden,tomashaber/raiden,tomashaber/raiden,tomashaber/raiden,tomashaber/raiden,hackaugusto/raiden | ---
+++
@@ -8,8 +8,9 @@
UINT256_MAX = 2 ** 256 - 1
-ROPSTEN_REGISTRY_ADDRESS = 'bbc60aa23059b039407ac008bd0b7e902890d382'
-ROPSTEN_DISCOVERY_ADDRESS = '524b7dcacac3055bd42fc03b006e9fdcb607e2be'
+# Deployed to Ropsten revival on 2017-06-19 from commit 2677298a69c1b1f35b9ab26beafe457acfdcc0ee
+ROPSTEN_REGISTRY_ADD... |
335a33465e197c9a2e52ed9de90546e2ca6173ee | tests/test_websocket_subscriber.py | tests/test_websocket_subscriber.py | """Tests for the WebSocketSubscriber handlers."""
import json
import pytest
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornadose.handlers import WebSocketSubscriber
import utilities
@pytest.fixture
def store():
return utilities.TestStore()
@pytest.fixture
def app... | """Tests for the WebSocketSubscriber handlers."""
import json
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornado.testing import AsyncHTTPTestCase, gen_test
from tornadose.handlers import WebSocketSubscriber
import utilities
class WebSo... | Fix test case for WebSocketSubscriber | Fix test case for WebSocketSubscriber
Switched to unittest-style testing (pytest is a bit too magical
especially with the pytest-tornado extension). I may change all
tests later to use unittest.
| Python | mit | mivade/tornadose | ---
+++
@@ -1,33 +1,33 @@
"""Tests for the WebSocketSubscriber handlers."""
import json
-import pytest
+from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import websocket_connect
+from tornado.testing import AsyncHTTPTestCase, gen_test
from tornadose.handlers impo... |
3d2d07294f7b891b7e716911475333c5e34d5c98 | tests/unit/test_raw_generichash.py | tests/unit/test_raw_generichash.py | # Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 =... | # Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 =... | Add tests for keyed hashes | Add tests for keyed hashes
| Python | apache-2.0 | mindw/libnacl,RaetProtocol/libnacl,cachedout/libnacl,johnttan/libnacl,coinkite/libnacl,saltstack/libnacl | ---
+++
@@ -17,3 +17,23 @@
self.assertNotEqual(msg1, chash1)
self.assertNotEqual(msg2, chash2)
self.assertNotEqual(chash2, chash1)
+
+ def test_key_generichash(self):
+ msg1 = b'Are you suggesting coconuts migrate?'
+ msg2 = b'Not at all, they could be carried.'
+ ke... |
44609e0432855506cd977cd39f1a780dfbd9e366 | tests/consoles_tests.py | tests/consoles_tests.py | import io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
def _create_local_con... | import io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_stdout_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
@istest
def co... | Add test for stderr output from console | Add test for stderr output from console
| Python | bsd-2-clause | mwilliamson/toodlepip | ---
+++
@@ -7,9 +7,16 @@
@istest
-def console_writes_output_to_console():
+def console_writes_stdout_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
+ assert b"Go go go!" in output.getvalue()
+
+
+@istest
+def console_writes_stderr_output_t... |
2f9e058b4ef79f6eecb0292642c85a9e3e2376b0 | examples/pipes-repl.py | examples/pipes-repl.py | '''
Sample REPL code to integrate with Diesel
Using InteractiveInterpreter broke block handling (if/def/etc.), but exceptions
were handled well and the return value of code was printed.
Using exec runs the input in the current context, but exception handling and other
features of InteractiveInterpreter are lost.
'''
... | import sys
import code
import traceback
from diesel import Application, Pipe, until
QUIT_STR = "quit()\n"
DEFAULT_PROMPT = '>>> '
def diesel_repl():
'''Simple REPL for use inside a diesel app'''
# Import current_app into locals for use in REPL
from diesel.app import current_app
print 'Diesel Console'... | Fix REPL and add quit() command | Fix REPL and add quit() command
| Python | bsd-3-clause | dieseldev/diesel | ---
+++
@@ -1,42 +1,46 @@
-'''
-Sample REPL code to integrate with Diesel
-
-Using InteractiveInterpreter broke block handling (if/def/etc.), but exceptions
-were handled well and the return value of code was printed.
-
-Using exec runs the input in the current context, but exception handling and other
-features of I... |
a6e1d44039d95f9f3f6ab6c53ffa28c50f3f9af6 | bp/bp.py | bp/bp.py | # Python 3.6.1
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
| # Python 3.8.3
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
| Update Python version in template | Update Python version in template
I completely forgot about those templates too. I don't even remember
what "bp" was supposed to stand for.
| Python | mit | foxscotch/advent-of-code,foxscotch/advent-of-code | ---
+++
@@ -1,4 +1,4 @@
-# Python 3.6.1
+# Python 3.8.3
def get_input():
with open('input.txt', 'r') as f: |
85123f01f1e63b4fc7688e13104ee59c6efb263a | proscli/main.py | proscli/main.py | import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
import prosconductor.providers... | import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
@click.command('pros',
... | Remove deprecated and broken pros help option | Remove deprecated and broken pros help option
| Python | mpl-2.0 | purduesigbots/pros-cli,purduesigbots/purdueros-cli | ---
+++
@@ -12,21 +12,12 @@
click.echo('Aborted!')
pass
-import prosconductor.providers.utils
-
-@proscli.flasher_cli.command('help', short_help='Show this message and exit.')
-@click.argument('ignore', nargs=-1, expose_value=False)
-@default_options
-@click.pass_context
-def help_cmd(ctx):
- c... |
ecd3f6df837f38bf78940308088d0760272a0c18 | server/world.py | server/world.py | import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game.state)
def generate_tiles(self, state):
""" Generate a tileset from the game st... | import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game)
def generate_tiles(self, state):
""" Generate a tileset from the game state. "... | Use game.queue.is_turn(name) to build player or enemies | Use game.queue.is_turn(name) to build player or enemies
| Python | mit | supermitch/mech-ai,supermitch/mech-ai,supermitch/mech-ai | ---
+++
@@ -9,7 +9,7 @@
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
- self.generate_mechs(game.state)
+ self.generate_mechs(game)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
@@ -23,14 +23,13 @@
... |
7bc4afdde415ec4176c589fb867ccdee2db5c041 | fmn/filters/generic.py | fmn/filters/generic.py | # Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedms... | # Generic filters for FMN
import fedmsg
import fmn.lib.pkgdb
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
r... | Add first filter relying on pkgdb integration | Add first filter relying on pkgdb integration | Python | lgpl-2.1 | jeremycline/fmn,jeremycline/fmn,jeremycline/fmn | ---
+++
@@ -1,5 +1,7 @@
# Generic filters for FMN
import fedmsg
+
+import fmn.lib.pkgdb
def user_filter(config, message, fasnick=None, *args, **kw):
@@ -12,3 +14,16 @@
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
+
+
+def user_package_... |
8d235a76120aadcd555da3d641f509541f525eb8 | csunplugged/utils/retrieve_query_parameter.py | csunplugged/utils/retrieve_query_parameter.py | """Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
... | """Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
... | Add function to get list of parameters | Add function to get list of parameters
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | ---
+++
@@ -23,3 +23,27 @@
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
+
+
+def retrieve_query_parameter_list(request, parameter, valid_options=None):
+ """Retrieve the query parameter list.
+
+ If the parameter cann... |
ce1f62dd809b3bec0abb345464edede6a5701b20 | clock.py | clock.py | from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', min... | from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', min... | Change notifier interval: 20 -> 10 | Change notifier interval: 20 -> 10
| Python | mit | oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije | ---
+++
@@ -19,7 +19,7 @@
shell=True)
-@scheduler.scheduled_job('interval', minutes=20)
+@scheduler.scheduled_job('interval', minutes=10)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call( |
d4adacc41858e224a8508a6da7ea77a30d1f8d9a | utils/data_paths.py | utils/data_paths.py | import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submi... | import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submi... | Remove base/hidden/probe data file paths (data_io isn't writing split data to files) | Remove base/hidden/probe data file paths (data_io isn't writing split data to files)
| Python | mit | jvanbrug/netflix,jvanbrug/netflix | ---
+++
@@ -10,6 +10,3 @@
ALL_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.dta')
ALL_INDEX_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.idx')
-BASE_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'base.dta')
-HIDDEN_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'hidden... |
091c125f42463b372f0c2c99124578eb8fe13150 | 2019/aoc2019/day08.py | 2019/aoc2019/day08.py | from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.... | from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.... | Fix day 8 to paint front-to-back | Fix day 8 to paint front-to-back
| Python | mit | bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adv... | ---
+++
@@ -24,10 +24,11 @@
def part2(data: TextIO) -> str:
- layers = list(parse_layers(25, 6, data))
background = numpy.zeros(25 * 6, numpy.int8)
+ background.fill(2)
- for layer in reversed(layers):
- background[layer != 2] = layer[layer != 2]
+ for layer in parse_layers(25, 6, data)... |
28ecf02c3d08eae725512e1563cf74f1831bd02d | gears/engines/base.py | gears/engines/base.py | import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwarg... | import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwarg... | Fix unicode support in ExecEngine | Fix unicode support in ExecEngine
| Python | isc | gears/gears,gears/gears,gears/gears | ---
+++
@@ -40,10 +40,10 @@
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
- output, errors = p.communicate(input=asset.processed_source)
+ output, errors = p.communicate(input=asset.processed_source.encode('utf-8'))
if p.returncode... |
52610add5ae887dcbc06f1435fdff34f182d78c9 | go/campaigns/forms.py | go/campaigns/forms.py | from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('C', 'Conversation'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign ... | from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('D', 'Dialogue'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign woul... | Use dialogue terminology in menu | Use dialogue terminology in menu
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -6,7 +6,7 @@
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
- ('C', 'Conversation'),
+ ('D', 'Dialogue'),
)
name = forms.CharField(label="Campaign name", max_length=100) |
ee2e1727ece6b591b39752a1d3cd6a87d972226d | github3/search/code.py | github3/search/code.py | # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
... | # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
... | Add a __repr__ for CodeSearchResult | Add a __repr__ for CodeSearchResult
| Python | bsd-3-clause | h4ck3rm1k3/github3.py,ueg1990/github3.py,degustaf/github3.py,krxsky/github3.py,sigmavirus24/github3.py,itsmemattchung/github3.py,agamdua/github3.py,wbrefvem/github3.py,jim-minter/github3.py,icio/github3.py,christophelec/github3.py,balloob/github3.py | ---
+++
@@ -23,3 +23,6 @@
self.score = data.get('score')
#: Text matches
self.text_matches = data.get('text_matches', [])
+
+ def __repr__(self):
+ return '<CodeSearchResult [{0}]>'.format(self.path) |
48ab19d9f81fc9973249e600f938586182fe6c7b | shop/rest/auth.py | shop/rest/auth.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.Pa... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.Pa... | Fix a failing test for PasswordResetSerializer | Fix a failing test for PasswordResetSerializer
It seems that Django's template API changed. This should adjust to that.
| Python | bsd-3-clause | awesto/django-shop,nimbis/django-shop,nimbis/django-shop,khchine5/django-shop,jrief/django-shop,rfleschenberg/django-shop,awesto/django-shop,khchine5/django-shop,divio/django-shop,divio/django-shop,nimbis/django-shop,jrief/django-shop,nimbis/django-shop,rfleschenberg/django-shop,jrief/django-shop,rfleschenberg/django-s... | ---
+++
@@ -21,8 +21,8 @@
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
- 'subject_template_name': subject_template.name,
- 'email_template_name': body_template.n... |
54bf7dd89cd4288d869b94123ce45f3c639ea894 | website/addons/dropbox/__init__.py | website/addons/dropbox/__init__.py | from . import model
from . import routes
from . import views
MODELS = [model.AddonDropboxUserSettings] # TODO Other models needed? , model.AddonDropboxNodeSettings, model.DropboxGuidFile]
USER_SETTINGS_MODEL = model.AddonDropboxNodeSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.setti... | from . import model
from . import routes
from . import views
MODELS = [model.DropboxUserSettings]
USER_SETTINGS_MODEL = model.DropboxUserSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbo... | Fix settings; tests now passing | Fix settings; tests now passing
| Python | apache-2.0 | rdhyee/osf.io,abought/osf.io,aaxelb/osf.io,billyhunt/osf.io,laurenrevere/osf.io,jnayak1/osf.io,rdhyee/osf.io,monikagrabowska/osf.io,jnayak1/osf.io,felliott/osf.io,lyndsysimon/osf.io,caseyrygt/osf.io,caneruguz/osf.io,jinluyuan/osf.io,baylee-d/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,mattclark/osf.io,brandonPurvis/o... | ---
+++
@@ -2,8 +2,8 @@
from . import routes
from . import views
-MODELS = [model.AddonDropboxUserSettings] # TODO Other models needed? , model.AddonDropboxNodeSettings, model.DropboxGuidFile]
-USER_SETTINGS_MODEL = model.AddonDropboxNodeSettings
+MODELS = [model.DropboxUserSettings]
+USER_SETTINGS_MODEL = model... |
a854c1564f581bda5c355d97069d775485a65047 | installer/steps/a_setup_virtualenv.py | installer/steps/a_setup_virtualenv.py | import os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that no... | import os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that no... | Fix python path for windows | Fix python path for windows
| Python | mit | appi147/Jarvis,sukeesh/Jarvis,appi147/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis | ---
+++
@@ -29,4 +29,7 @@
# Create virtualenv if necessary
if not virtualenv_exists:
+ if unix_windows.IS_WIN:
+ shell("virtualenv env").should_not_fail()
+ else:
shell("virtualenv env --python=python3").should_not_fail() |
652bca441489dd49552cbd5945605d51921394f0 | snowfloat/settings.py | snowfloat/settings.py | """Client global settings."""
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
try:
# pylint: disable=F0401
from settings_prod import *
except ImportError:
try:
# pylint: disable=F0401
from settings_dev import *
... | """Client global settings."""
import os
import ConfigParser
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
CONFIG = ConfigParser.RawConfigParser()
for loc in (os.curdir, os.path.expanduser("~"), "/etc/snowfloat"):
try:
with open... | Read config file in different locations and set global config variables based on that. | Read config file in different locations and set global config variables based on that.
| Python | bsd-3-clause | snowfloat/snowfloat-python,snowfloat/snowfloat-python | ---
+++
@@ -1,4 +1,6 @@
"""Client global settings."""
+import os
+import ConfigParser
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
@@ -8,12 +10,13 @@
API_KEY = ''
API_PRIVATE_KEY = ''
-try:
- # pylint: disable=F0401
- from settings_prod import *
-except ImportError:
+CONFIG = ConfigParser.RawConfig... |
2fe37e7c46671a2ba9039f20c63930de2aaa0576 | src/cutecoin/tools/decorators.py | src/cutecoin/tools/decorators.py | import asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):... | import asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):... | Fix bug with exception never handled in once_at_a_time coroutines | Fix bug with exception never handled in once_at_a_time coroutines
| Python | mit | ucoin-io/cutecoin,ucoin-io/cutecoin,ucoin-io/cutecoin | ---
+++
@@ -13,15 +13,24 @@
def once_at_a_time(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
+ def task_done(task):
+ try:
+ args[0].__tasks.pop(fn.__name__)
+ except KeyError:
+ logging.debug("Task already removed")
+
if getattr... |
dbf147b4842edd96842fa384b594265daf0c555e | byceps/util/system.py | byceps/util/system.py | """
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Ra... | """
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
from ..config import ConfigurationError
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filen... | Raise `ConfigurationError` instead of `Exception` if environment variable `BYCEPS_CONFIG` is not set | Raise `ConfigurationError` instead of `Exception` if environment variable `BYCEPS_CONFIG` is not set
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps | ---
+++
@@ -8,6 +8,8 @@
import os
import sys
+
+from ..config import ConfigurationError
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
@@ -21,7 +23,7 @@
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
- raise Exception(
+ raise ConfigurationError(
"No configuration file was specif... |
0f8c4cd71bff68860d0a18f8680eda9a690f0959 | sqlstr/exception.py | sqlstr/exception.py | '''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
:message str:
'''
Exception.__init__(self, message)
| '''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
message -- string. Message describing the exception.
'''
Exception.__init__(self, message)
| Update docstring with parameter listing | Update docstring with parameter listing
| Python | mit | GochoMugo/sql-string-templating | ---
+++
@@ -8,6 +8,7 @@
def __init__(self, message):
'''
Instanitates a custom sqlstrException
- :message str:
+
+ message -- string. Message describing the exception.
'''
Exception.__init__(self, message) |
8e5e732ad02f9aa6df7a8963c73c2b0aa753ad0a | src/utils.py | src/utils.py | if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asct... | if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asct... | Reduce function, to stop nested lists | Reduce function, to stop nested lists
| Python | mit | Mause/tyrian,Mause/tyrian,Mause/tyrian,Mause/tyrian | ---
+++
@@ -21,3 +21,18 @@
logger.addHandler(hdlr)
+def reduce(obj, can_return_single=False):
+ """
+ Flattens nested lists, like so;
+
+ >>> reduce([[[[[[[None]]]]]]])
+ None
+
+ """
+
+ if type(obj) == list and len(obj) == 1 and type(obj[0]) == list:
+ return reduce(obj[0])
+ ... |
a0a0d120552eeb304ac4b49648a43be5cf83cdcb | piper/core.py | piper/core.py | class Piper(object):
"""
The main runner.
This class loads the configurations, sets up all other components, and
finally executes them in whatever order they are supposed to happen in.
"""
def __init__(self):
pass
| import logbook
class Piper(object):
"""
The main pipeline runner.
This class loads the configurations, sets up all other components,
executes them in whatever order they are supposed to happen in, collects
data about the state of the pipeline and persists it, and finally tears
down the compon... | Add more skeletonisms and documentation for Piper() | Add more skeletonisms and documentation for Piper()
| Python | mit | thiderman/piper | ---
+++
@@ -1,11 +1,82 @@
+import logbook
+
+
class Piper(object):
"""
- The main runner.
+ The main pipeline runner.
- This class loads the configurations, sets up all other components, and
- finally executes them in whatever order they are supposed to happen in.
+ This class loads the configu... |
0261a0f9a1dde9f9f6167e3630561219e3dca124 | statsmodels/datasets/__init__.py | statsmodels/datasets/__init__.py | """
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \
macrodata, nile, randhie, scotland, spector, stackloss, star98, \
strikes, sunspots, fair, heart, statecrime
| """
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino,
grunfeld, longley, macrodata, nile, randhie, scotland, spector,
stackloss, star98, strikes, sunspots, fair, heart, statecrime)
| Switch to relative imports and fix pep-8 | STY: Switch to relative imports and fix pep-8
| Python | bsd-3-clause | bsipocz/statsmodels,bsipocz/statsmodels,bsipocz/statsmodels,hlin117/statsmodels,bashtage/statsmodels,nguyentu1602/statsmodels,hlin117/statsmodels,musically-ut/statsmodels,yl565/statsmodels,jstoxrocky/statsmodels,wwf5067/statsmodels,bert9bert/statsmodels,nvoron23/statsmodels,bert9bert/statsmodels,astocko/statsmodels,jse... | ---
+++
@@ -2,7 +2,6 @@
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
-import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \
- macrodata, nile, randhie, scotland, spector, stackloss, star98, \
- strikes, sunspots, fair, heart, statecrime
... |
d7945f0394038e9c194a2e41e6da151b679128a3 | cs251tk/toolkit/process_student.py | cs251tk/toolkit/process_student.py | from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
st... | from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
st... | Remove extra newlines added during editing | Remove extra newlines added during editing
| Python | mit | StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit | ---
+++
@@ -24,16 +24,16 @@
):
if clean:
remove(student)
+
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
+ pull(student, no_update=no_update)
- pull(student, no_update=no_update)
checkout_date(student, date=date... |
105b5c3d8db38be9a12974e7be807c429e8ad9ad | contentcuration/contentcuration/utils/asynccommand.py | contentcuration/contentcuration/utils/asynccommand.py | from abc import abstractmethod
from collections import namedtuple
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
Progress = namedtuple(
'Progress',
[
'progress',
'total',
'fraction',
]
)
class TaskCommand(BaseCommand):
... | import logging as logmodule
from abc import abstractmethod
from django.core.management.base import BaseCommand
logmodule.basicConfig()
logging = logmodule.getLogger(__name__)
class Progress():
"""
A Progress contains the progress of the tasks, the total number of expected
tasks/data, and the fraction wh... | Define Progress as a Class and add more comments | Define Progress as a Class and add more comments
| Python | mit | fle-internal/content-curation,DXCanas/content-curation,fle-internal/content-curation,DXCanas/content-curation,DXCanas/content-curation,fle-internal/content-curation,fle-internal/content-curation,DXCanas/content-curation | ---
+++
@@ -1,36 +1,63 @@
+import logging as logmodule
from abc import abstractmethod
-from collections import namedtuple
from django.core.management.base import BaseCommand
-from django.core.management.base import CommandError
-Progress = namedtuple(
- 'Progress',
- [
- 'progress',
- 'total... |
117d7bd313c62ae8ccf5c0565ab1d0538db5423c | astrobin/settings/components/haystack.py | astrobin/settings/components/haystack.py | HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
... | HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
... | Enable real-time celery-based search index | Enable real-time celery-based search index
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin | ---
+++
@@ -11,6 +11,7 @@
],
},
}
-#if not TESTING:
- #HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
+if not TESTING:
+ HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
+ |
e26573b37f6cb12817b35d3ac0d19fa301fd1a99 | pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py | pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py | # -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
| # -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
@pytest.fixture
def bar(request):
return request.config.op... | Implement a custom fixture for the plugin | Implement a custom fixture for the plugin
| Python | mit | pytest-dev/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin,luzfcb/cookiecutter-pytest-plugin | ---
+++
@@ -11,3 +11,8 @@
dest='foo',
help='alias for --foo'
)
+
+
+@pytest.fixture
+def bar(request):
+ return request.config.option.foo |
aeebd8a4f2255bff03fbb55f3d7d29d822fbb31b | logaugment/__init__.py | logaugment/__init__.py | import logging
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__init__(name)
self._args = args
def filter(self, record):
if self._args is not None:
data = {}
try:
if callable(self._args):... | import logging
__title__ = 'logaugment'
__version__ = '0.0.1'
__author__ = 'Simeon Visser'
__email__ = 'simeonvisser@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 Simeon Visser'
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__ini... | Add project details to codebase | Add project details to codebase
| Python | mit | svisser/logaugment | ---
+++
@@ -1,4 +1,11 @@
import logging
+
+__title__ = 'logaugment'
+__version__ = '0.0.1'
+__author__ = 'Simeon Visser'
+__email__ = 'simeonvisser@gmail.com'
+__license__ = 'MIT'
+__copyright__ = 'Copyright 2014 Simeon Visser'
class AugmentFilter(logging.Filter): |
a9accd5460157e323e8514178d3e7bc9d2fa8667 | dn1/kolona_vozil_test.py | dn1/kolona_vozil_test.py | __author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
if __name__ == '__mai... | __author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil, Vozilo
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
def test_v... | Update unittests for Task 4 | Update unittests for Task 4
| Python | mit | nbasic/racunalnistvo-1 | ---
+++
@@ -1,7 +1,7 @@
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
-from jadrolinija import KolonaVozil
+from jadrolinija import KolonaVozil, Vozilo
class KolonaVozilTest(unittest.TestCase):
@@ -11,6 +11,42 @@
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual... |
05e651b0e606f216a78c61ccfb441ce7ed41d852 | reg/compat.py | reg/compat.py | import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
d... | import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
d... | Exclude from coverage the code pathways that are specific to Python 2. | Exclude from coverage the code pathways that are specific to Python 2.
| Python | bsd-3-clause | morepath/reg,taschini/reg | ---
+++
@@ -17,7 +17,7 @@
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
-else:
+else: # pragma: no cover
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.