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 |
|---|---|---|---|---|---|---|---|---|---|---|
444e28a332e31186971cebfd905e1aeadff1abfe | pydash/__meta__.py | pydash/__meta__.py | """Define project metadata
"""
__all__ = [
'__title__',
'__summary__',
'__url__',
'__version__',
'__author__',
'__email__',
'__license__',
]
__title__ = 'pydash'
__summary__ = 'Python port of Lo-Dash'
__url__ = 'https://github.com/dgilland/pydash'
__version__ = '1.1.0'
__author__ = 'Derrick Gilland'
__email__ = 'dgilland@gmail.com'
__license__ = 'MIT License'
| """Define project metadata
"""
__all__ = [
'__title__',
'__summary__',
'__url__',
'__version__',
'__author__',
'__email__',
'__license__',
]
__title__ = 'pydash'
__summary__ = 'Python port of Lo-Dash'
__url__ = 'https://github.com/dgilland/pydash'
__version__ = '2.0.0-dev'
__author__ = 'Derrick Gilland'
__email__ = 'dgilland@gmail.com'
__license__ = 'MIT License'
| Add v2 dev version designation. | Add v2 dev version designation.
| Python | mit | jacobbridges/pydash,bharadwajyarlagadda/pydash,dgilland/pydash | ---
+++
@@ -15,7 +15,7 @@
__summary__ = 'Python port of Lo-Dash'
__url__ = 'https://github.com/dgilland/pydash'
-__version__ = '1.1.0'
+__version__ = '2.0.0-dev'
__author__ = 'Derrick Gilland'
__email__ = 'dgilland@gmail.com' |
bdbd8e56dab87e0c7bd160ef91d5634064729626 | src/python/foglamp/core/server.py | src/python/foglamp/core/server.py | # -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
import signal
import asyncio
from aiohttp import web
from foglamp.core import routes
from foglamp.core import middleware
from foglamp.core import scheduler
__author__ = "Praveen Garg"
__copyright__ = "Copyright (c) 2017 OSIsoft, LLC"
__license__ = "Apache 2.0"
__version__ = "${VERSION}"
def _make_app():
"""create the server"""
# https://aiohttp.readthedocs.io/en/stable/_modules/aiohttp/web.html#run_app
app = web.Application(middlewares=[middleware.error_middleware])
routes.setup(app)
return app
def _shutdown(loop):
scheduler.shutdown()
for task in asyncio.Task.all_tasks():
task.cancel()
loop.stop()
def start():
"""starts the server"""
loop = asyncio.get_event_loop()
scheduler.start(loop)
for signal_name in (signal.SIGINT, signal.SIGTERM, signal.SIGQUIT):
loop.add_signal_handler(signal_name, _shutdown, loop)
web.run_app(_make_app(), host='0.0.0.0', port=8082)
| # -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
import signal
import asyncio
from aiohttp import web
from foglamp.core import routes
from foglamp.core import middleware
from foglamp.core import scheduler
__author__ = "Praveen Garg"
__copyright__ = "Copyright (c) 2017 OSIsoft, LLC"
__license__ = "Apache 2.0"
__version__ = "${VERSION}"
def _make_app():
"""create the server"""
# https://aiohttp.readthedocs.io/en/stable/_modules/aiohttp/web.html#run_app
app = web.Application(middlewares=[middleware.error_middleware])
routes.setup(app)
return app
def _shutdown(loop):
scheduler.shutdown()
for task in asyncio.Task.all_tasks():
task.cancel()
loop.stop()
def start():
"""starts the server"""
loop = asyncio.get_event_loop()
scheduler.start()
for signal_name in (signal.SIGINT, signal.SIGTERM, signal.SIGQUIT):
loop.add_signal_handler(signal_name, _shutdown, loop)
web.run_app(_make_app(), host='0.0.0.0', port=8082)
| Remove loop parameter from scheduler.start() | Remove loop parameter from scheduler.start() | Python | apache-2.0 | foglamp/FogLAMP,foglamp/FogLAMP,foglamp/FogLAMP,foglamp/FogLAMP | ---
+++
@@ -36,7 +36,7 @@
def start():
"""starts the server"""
loop = asyncio.get_event_loop()
- scheduler.start(loop)
+ scheduler.start()
for signal_name in (signal.SIGINT, signal.SIGTERM, signal.SIGQUIT):
loop.add_signal_handler(signal_name, _shutdown, loop) |
641434ef0d1056fecdedbe7dacfe2d915b89408b | undecorated.py | undecorated.py | # -*- coding: utf-8 -*-
# Copyright 2016 Ionuț Arțăriși <ionut@artarisi.eu>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Return a function with any decorators removed """
__version__ = '0.1.1'
def undecorated(o):
"""Remove all decorators from a function, method or class"""
# class decorator
if type(o) is type:
return o
try:
# python2
closure = o.func_closure
except AttributeError:
pass
try:
# python3
closure = o.__closure__
except AttributeError:
return
if closure:
for cell in closure:
# avoid infinite recursion
if cell.cell_contents is o:
continue
undecd = undecorated(cell.cell_contents)
if undecd:
return undecd
else:
return o
| # -*- coding: utf-8 -*-
# Copyright 2016 Ionuț Arțăriși <ionut@artarisi.eu>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__version__ = '0.1.1'
def undecorated(o):
"""Remove all decorators from a function, method or class"""
# class decorator
if type(o) is type:
return o
try:
# python2
closure = o.func_closure
except AttributeError:
pass
try:
# python3
closure = o.__closure__
except AttributeError:
return
if closure:
for cell in closure:
# avoid infinite recursion
if cell.cell_contents is o:
continue
undecd = undecorated(cell.cell_contents)
if undecd:
return undecd
else:
return o
| Remove module docstring as we have it on the func | Remove module docstring as we have it on the func
| Python | apache-2.0 | mapleoin/undecorated | ---
+++
@@ -12,8 +12,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
-"""Return a function with any decorators removed """
__version__ = '0.1.1' |
f4bc898b84ef516555367dde6dfdbfb249aa95ac | app.py | app.py | from flask import Flask, render_template, request, jsonify
import os
import shutil
app = Flask(__name__)
app.config.from_object('config.Debug')
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'GET':
return render_template('upload.html')
elif request.method == 'POST':
file = request.files['file']
if file:
filename = os.urandom(30).encode('hex') + '.' + file.filename.split('.')[-1]
while os.path.isfile(os.path.join(app.config['TEMP_DIR'], filename)):
filename = os.urandom(30).encode('hex')
file.save(os.path.join(app.config['TEMP_DIR'], filename))
return jsonify(filename=filename)
@app.route('/confirm/<filename>/<id>', methods=['POST'])
def confirm(filename, id):
if os.path.isfile(os.path.join(app.config['TEMP_DIR'], filename)):
shutil.move(os.path.join(app.config['TEMP_DIR'], filename), os.path.join(app.config['LIB_DIR'], filename))
return ''
if __name__ == "__main__":
app.run()
| from flask import Flask, render_template, request, jsonify
import os
import shutil
import requests
app = Flask(__name__)
app.config.from_object('config.Debug')
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'GET':
return render_template('upload.html')
elif request.method == 'POST':
file = request.files['file']
if file:
filename = os.urandom(30).encode('hex') + '.' + file.filename.split('.')[-1]
while os.path.isfile(os.path.join(app.config['TEMP_DIR'], filename)):
filename = os.urandom(30).encode('hex')
file.save(os.path.join(app.config['TEMP_DIR'], filename))
return jsonify(filename=filename)
@app.route('/confirm/<filename>/<id>', methods=['POST'])
def confirm(filename, id):
r = requests.get('https://www.googleapis.com/books/v1/volumes/s1gVAAAAYAAJ').json()
print r['id']
if os.path.isfile(os.path.join(app.config['TEMP_DIR'], filename)):
shutil.move(os.path.join(app.config['TEMP_DIR'], filename), os.path.join(app.config['LIB_DIR'], r['id']+'.'+filename.split('.')[-1]))
return ''
if __name__ == "__main__":
app.run()
| Save confirmed files with Google Books ID | Save confirmed files with Google Books ID
| Python | mit | citruspi/Alexandria,citruspi/Alexandria | ---
+++
@@ -1,6 +1,7 @@
from flask import Flask, render_template, request, jsonify
import os
import shutil
+import requests
app = Flask(__name__)
app.config.from_object('config.Debug')
@@ -31,9 +32,13 @@
@app.route('/confirm/<filename>/<id>', methods=['POST'])
def confirm(filename, id):
+ r = requests.get('https://www.googleapis.com/books/v1/volumes/s1gVAAAAYAAJ').json()
+
+ print r['id']
+
if os.path.isfile(os.path.join(app.config['TEMP_DIR'], filename)):
- shutil.move(os.path.join(app.config['TEMP_DIR'], filename), os.path.join(app.config['LIB_DIR'], filename))
+ shutil.move(os.path.join(app.config['TEMP_DIR'], filename), os.path.join(app.config['LIB_DIR'], r['id']+'.'+filename.split('.')[-1]))
return ''
|
e8935189659e882f534f5605086dc76ce7ce881b | rdrf/rdrf/admin.py | rdrf/rdrf/admin.py | from django.contrib import admin
from models import *
from registry.groups.models import User
class SectionAdmin(admin.ModelAdmin):
list_display = ('code', 'display_name')
class RegistryFormAdmin(admin.ModelAdmin):
list_display = ('registry', 'name', 'sections')
class RegistryAdmin(admin.ModelAdmin):
def queryset(self, request):
if not request.user.is_superuser:
user = User.objects.get(user=request.user)
return Registry.objects.filter(registry__in=[reg.id for reg in user.registry.all()])
return Registry.objects.all()
admin.site.register(CDEPermittedValue)
admin.site.register(CDEPermittedValueGroup)
admin.site.register(CommonDataElement)
admin.site.register(Wizard)
admin.site.register(RegistryForm, RegistryFormAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(Registry, RegistryAdmin) | from django.contrib import admin
from models import *
from registry.groups.models import User
class SectionAdmin(admin.ModelAdmin):
list_display = ('code', 'display_name')
class RegistryFormAdmin(admin.ModelAdmin):
list_display = ('registry', 'name', 'sections')
class RegistryAdmin(admin.ModelAdmin):
def queryset(self, request):
if not request.user.is_superuser:
user = User.objects.get(user=request.user)
return Registry.objects.filter(registry__in=[reg.id for reg in user.registry.all()])
return Registry.objects.all()
def has_add_permission(self, request):
if request.user.is_superuser:
return True
return False
admin.site.register(CDEPermittedValue)
admin.site.register(CDEPermittedValueGroup)
admin.site.register(CommonDataElement)
admin.site.register(Wizard)
admin.site.register(RegistryForm, RegistryFormAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(Registry, RegistryAdmin) | Disable adding registries for non-superusers | Disable adding registries for non-superusers
| Python | agpl-3.0 | muccg/rdrf,muccg/rdrf,muccg/rdrf,muccg/rdrf,muccg/rdrf | ---
+++
@@ -16,6 +16,11 @@
return Registry.objects.filter(registry__in=[reg.id for reg in user.registry.all()])
return Registry.objects.all()
+ def has_add_permission(self, request):
+ if request.user.is_superuser:
+ return True
+ return False
+
admin.site.register(CDEPermittedValue)
admin.site.register(CDEPermittedValueGroup) |
b1475056f22810912e50c62258c479acd86645a5 | follower/pid.py | follower/pid.py |
import sys
from time import time
class PID(object):
def __init__(self):
"""initizes value for the PID"""
self.kd = 0
self.ki = 0
self.kp = 1
self.previous_error = 0
self.integral_error = 0
def set_k_values(self, kp, kd, ki):
self.kp = kp
self.ki = ki
self.kd = kd
def pid(self, target, process_var, timestep):
current_error = (target + process_var)
p_error = self.kp * current_error
d_error = self.kd * (current_error - self.previous_error) \
/ timestep
self.integral_error = (
current_error + self.previous_error) / 2 \
+ self.integral_error
i_error = self.ki * self.integral_error
total_error = p_error + d_error + i_error
self.previous_error = current_error
return total_error
|
import sys
from time import time
class PID(object):
def __init__(self):
"""initizes value for the PID"""
self.kd = 0
self.ki = 0
self.kp = 1
self.previous_error = 0
self.integral_error = 0
def set_k_values(self, kp, kd, ki):
self.kp = kp
self.ki = ki
self.kd = kd
def pid(self, target, process_var, timestep):
current_error = (target - process_var)
p_error = self.kp * current_error
d_error = self.kd * (current_error - self.previous_error) \
/ timestep
self.integral_error = (
current_error + self.previous_error) / 2 \
+ self.integral_error
i_error = self.ki * self.integral_error
total_error = p_error + d_error + i_error
self.previous_error = current_error
return total_error
| Update to follower, reduce speed to motors. | Update to follower, reduce speed to motors.
| Python | bsd-2-clause | IEEERobotics/bot,IEEERobotics/bot,IEEERobotics/bot,deepakiam/bot,deepakiam/bot,deepakiam/bot | ---
+++
@@ -20,7 +20,7 @@
self.kd = kd
def pid(self, target, process_var, timestep):
- current_error = (target + process_var)
+ current_error = (target - process_var)
p_error = self.kp * current_error
d_error = self.kd * (current_error - self.previous_error) \
/ timestep |
b393c41bf73a492bbd4a7bc50d16dd74c126c3db | grab.py | grab.py | #!/usr/bin/env python
# Grab runs from S3 and do analysis
#
# Daniel Klein, 2015-08-14
import sys
import subprocess
import glob
# Putting this in front of expensive imports
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('remote_dir', help = 'S3 directory with completed runs')
parser.add_argument('run_id', help = 'ID of run to analyze')
parser.add_argument('--leave', help = 'don\'t delete downloaded files',
action = 'store_true')
args = parser.parse_args()
match_run = '%s_*__completed.json' % args.run_id
subprocess.call(['aws', 's3', 'sync', args.remote_dir, 'runs/',
'--exclude', '*',
'--include', match_run])
runs = glob.glob('runs/' + match_run)
print runs
run_stems = [run.split('completed')[0] for run in runs]
subprocess.call(['python', 'test.py'] + \
[run_stem + 'load.json' for run_stem in run_stems])
subprocess.call(['mv', 'out.pdf', 'runs/%s_figs.pdf' % args.run_id])
if not args.leave:
for run in runs:
subprocess.call(['rm', run])
| #!/usr/bin/env python
# Grab runs from S3 and do analysis
#
# Daniel Klein, 2015-08-14
import sys
import subprocess
import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('remote_dir', help = 'S3 directory with completed runs')
parser.add_argument('run_ids', help = 'IDs of runs to analyze',
nargs = '+')
parser.add_argument('--leave', help = 'don\'t delete downloaded files',
action = 'store_true')
args = parser.parse_args()
for run_id in args.run_ids:
print run_id
match_run = '%s_*__completed.json' % run_id
subprocess.call(['aws', 's3', 'sync', args.remote_dir, 'runs/',
'--exclude', '*',
'--include', match_run])
runs = glob.glob('runs/' + match_run)
print runs
run_stems = [run.split('completed')[0] for run in runs]
subprocess.call(['python', 'test.py'] + \
[run_stem + 'load.json' for run_stem in run_stems])
subprocess.call(['mv', 'out.pdf', 'runs/%s_figs.pdf' % run_id])
if not args.leave:
for run in runs:
subprocess.call(['rm', run])
| Allow pulling batch of runs for analysis | Allow pulling batch of runs for analysis
| Python | mit | othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel | ---
+++
@@ -7,33 +7,36 @@
import sys
import subprocess
import glob
+import argparse
-# Putting this in front of expensive imports
-import argparse
parser = argparse.ArgumentParser()
parser.add_argument('remote_dir', help = 'S3 directory with completed runs')
-parser.add_argument('run_id', help = 'ID of run to analyze')
+parser.add_argument('run_ids', help = 'IDs of runs to analyze',
+ nargs = '+')
parser.add_argument('--leave', help = 'don\'t delete downloaded files',
action = 'store_true')
args = parser.parse_args()
-match_run = '%s_*__completed.json' % args.run_id
+for run_id in args.run_ids:
+ print run_id
+
+ match_run = '%s_*__completed.json' % run_id
-subprocess.call(['aws', 's3', 'sync', args.remote_dir, 'runs/',
- '--exclude', '*',
- '--include', match_run])
+ subprocess.call(['aws', 's3', 'sync', args.remote_dir, 'runs/',
+ '--exclude', '*',
+ '--include', match_run])
-runs = glob.glob('runs/' + match_run)
-print runs
+ runs = glob.glob('runs/' + match_run)
+ print runs
-run_stems = [run.split('completed')[0] for run in runs]
+ run_stems = [run.split('completed')[0] for run in runs]
-subprocess.call(['python', 'test.py'] + \
- [run_stem + 'load.json' for run_stem in run_stems])
-
-subprocess.call(['mv', 'out.pdf', 'runs/%s_figs.pdf' % args.run_id])
+ subprocess.call(['python', 'test.py'] + \
+ [run_stem + 'load.json' for run_stem in run_stems])
-if not args.leave:
- for run in runs:
- subprocess.call(['rm', run])
+ subprocess.call(['mv', 'out.pdf', 'runs/%s_figs.pdf' % run_id])
+
+ if not args.leave:
+ for run in runs:
+ subprocess.call(['rm', run]) |
cbf788d734f3a93b7f6b85269ba8f32e9be50a81 | p3p/urls.py | p3p/urls.py | from django.conf.urls.defaults import patterns, url
from p3p.views import XmlView, P3PView
urlpatterns = patterns('p3p.views',
url(r'^p3p.xml$', XmlView.as_view(), name='p3p'),
url(r'^policy.p3p$', P3PView.as_view(), name='policy'),
)
| from django.conf.urls import patterns, url
from p3p.views import XmlView, P3PView
urlpatterns = patterns('p3p.views',
url(r'^p3p.xml$', XmlView.as_view(), name='p3p'),
url(r'^policy.p3p$', P3PView.as_view(), name='policy'),
)
| Fix compatibility problems with django. | Fix compatibility problems with django.
| Python | apache-2.0 | jjanssen/django-p3p | ---
+++
@@ -1,4 +1,5 @@
-from django.conf.urls.defaults import patterns, url
+from django.conf.urls import patterns, url
+
from p3p.views import XmlView, P3PView
urlpatterns = patterns('p3p.views', |
370809a6715675aee98b05bdd3c4d0c26a5d156a | meals/models.py | meals/models.py | from django.db import models
class Wbw_list(models.Model):
list_id = models.IntegerField(unique=True)
name = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.name
class Participant(models.Model):
wbw_list = models.ManyToManyField(Wbw_list, through='Participation')
wbw_id = models.IntegerField(unique=True)
class Participation(models.Model):
name = models.CharField(max_length=200)
wbw_list = models.ForeignKey(Wbw_list)
participant = models.ForeignKey(Participant)
def __str__(self):
return self.name
class Bystander(models.Model):
name = models.CharField(max_length=200)
participant = models.ForeignKey(Participant)
class Meal(models.Model):
price = models.IntegerField(default=0)
date = models.DateTimeField(auto_now=True)
completed = models.BooleanField(default=False)
description = models.CharField(max_length=200, blank=True)
wbw_list = models.ForeignKey(Wbw_list, null=True)
participants = models.ManyToManyField(Participant, blank=True)
bystanders = models.ManyToManyField(Bystander, blank=True)
payer = models.ForeignKey(Participant, null=True, related_name='paymeal')
| from django.db import models
class Wbw_list(models.Model):
list_id = models.IntegerField(unique=True)
name = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.name
class Participant(models.Model):
wbw_list = models.ManyToManyField(Wbw_list, through='Participation')
wbw_id = models.IntegerField(unique=True)
class Participation(models.Model):
name = models.CharField(max_length=200)
wbw_list = models.ForeignKey(Wbw_list)
participant = models.ForeignKey(Participant)
def __str__(self):
return self.name
class Bystander(models.Model):
name = models.CharField(max_length=200)
participant = models.ForeignKey(Participant)
class Meal(models.Model):
price = models.IntegerField(default=0)
date = models.DateTimeField(auto_now=True)
completed = models.BooleanField(default=False)
description = models.CharField(max_length=200, blank=True)
wbw_list = models.ForeignKey(Wbw_list, null=True)
participants = models.ManyToManyField(Participant, blank=True)
bystanders = models.ManyToManyField(Bystander, blank=True)
payer = models.ForeignKey(Participant, null=True, blank=True, related_name='paymeal')
| Allow meals with unknown payer | Allow meals with unknown payer
| Python | cc0-1.0 | joostrijneveld/eetvoudig,joostrijneveld/eetvoudig,joostrijneveld/eetvoudig | ---
+++
@@ -37,4 +37,4 @@
wbw_list = models.ForeignKey(Wbw_list, null=True)
participants = models.ManyToManyField(Participant, blank=True)
bystanders = models.ManyToManyField(Bystander, blank=True)
- payer = models.ForeignKey(Participant, null=True, related_name='paymeal')
+ payer = models.ForeignKey(Participant, null=True, blank=True, related_name='paymeal') |
a8115391de5a4490929cacc606282852b59f54c9 | IPython/html/widgets/widget_image.py | IPython/html/widgets/widget_image.py | """ButtonWidget class.
Represents a button in the frontend using a widget. Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import base64
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Bytes
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ImageWidget(DOMWidget):
view_name = Unicode('ImageView', sync=True)
# Define the custom state properties to sync with the front-end
format = Unicode('png', sync=True)
width = Unicode(sync=True) # TODO: C unicode
height = Unicode(sync=True)
_b64value = Unicode(sync=True)
value = Bytes()
def _value_changed(self, name, old, new):
self._b64value = base64.b64encode(new) | """ButtonWidget class.
Represents a button in the frontend using a widget. Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import base64
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, CUnicode, Bytes
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ImageWidget(DOMWidget):
view_name = Unicode('ImageView', sync=True)
# Define the custom state properties to sync with the front-end
format = Unicode('png', sync=True)
width = CUnicode(sync=True)
height = CUnicode(sync=True)
_b64value = Unicode(sync=True)
value = Bytes()
def _value_changed(self, name, old, new):
self._b64value = base64.b64encode(new) | Use CUnicode for width and height in ImageWidget | Use CUnicode for width and height in ImageWidget
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -17,7 +17,7 @@
import base64
from .widget import DOMWidget
-from IPython.utils.traitlets import Unicode, Bytes
+from IPython.utils.traitlets import Unicode, CUnicode, Bytes
#-----------------------------------------------------------------------------
# Classes
@@ -27,8 +27,8 @@
# Define the custom state properties to sync with the front-end
format = Unicode('png', sync=True)
- width = Unicode(sync=True) # TODO: C unicode
- height = Unicode(sync=True)
+ width = CUnicode(sync=True)
+ height = CUnicode(sync=True)
_b64value = Unicode(sync=True)
value = Bytes() |
bfdf65558e2f9b5b4e8d385b2911db374ffbfe03 | qipipe/qiprofile/update.py | qipipe/qiprofile/update.py | from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
def update(project, collection, subject, session, filename):
"""
Updates the qiprofile database from the clinical spreadsheet and
XNAT database for the given session.
:param project: the XNAT project name
:param collection: the image collection name
:param subject: the subject number
:param session: the XNAT session number
:param filename: the XLS input file location
"""
# Get or create the subject database subject.
key = dict(project=project, collection=collection, number=subject)
sbj = database.get_or_create(Subject, key)
# Update the clinical information from the XLS input.
clinical.update(sbj, filename)
# Update the imaging information from XNAT.
imaging.update(sbj, session)
| from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
def update(project, collection, subject, session, spreadsheet):
"""
Updates the qiprofile database from the clinical spreadsheet and
XNAT database for the given session.
:param project: the XNAT project name
:param collection: the image collection name
:param subject: the subject number
:param session: the XNAT session number
:param spreadsheet: the spreadsheet input file location
:param modeling_technique: the modeling technique
"""
# Get or create the subject database subject.
key = dict(project=project, collection=collection, number=subject)
sbj = database.get_or_create(Subject, key)
# Update the clinical information from the XLS input.
clinical.update(sbj, spreadsheet)
# Update the imaging information from XNAT.
imaging.update(sbj, session)
| Rename the filename argument to spreadsheet. | Rename the filename argument to spreadsheet.
| Python | bsd-2-clause | ohsu-qin/qipipe | ---
+++
@@ -4,7 +4,7 @@
from . import (clinical, imaging)
-def update(project, collection, subject, session, filename):
+def update(project, collection, subject, session, spreadsheet):
"""
Updates the qiprofile database from the clinical spreadsheet and
XNAT database for the given session.
@@ -13,12 +13,13 @@
:param collection: the image collection name
:param subject: the subject number
:param session: the XNAT session number
- :param filename: the XLS input file location
+ :param spreadsheet: the spreadsheet input file location
+ :param modeling_technique: the modeling technique
"""
# Get or create the subject database subject.
key = dict(project=project, collection=collection, number=subject)
sbj = database.get_or_create(Subject, key)
# Update the clinical information from the XLS input.
- clinical.update(sbj, filename)
+ clinical.update(sbj, spreadsheet)
# Update the imaging information from XNAT.
imaging.update(sbj, session) |
99f7b0edf2b84658e0a03149eb3e999293aa5e95 | src/model/train_xgb_model.py | src/model/train_xgb_model.py | import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
import xgboost as xgb
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
train = joblib.load(utils.processed_data_path + 'train_is_booking_all_top_5_cw_0.05_year_all.pkl')
X_train = train.ix[:,2:]
y_train = pd.DataFrame(train['hotel_cluster'].astype(int))
print "train XGBClassifier..."
cxgb = xgb.XGBClassifier(max_depth=15, n_estimators=100, learning_rate=0.02, colsample_bytree=0.5, min_child_weight=5, verbose=1)
cxgb.fit(X_train, y_train.ravel())
joblib.dump(cxgb, utils.model_path + 'cxgb_all_without_time_top_5_cw_0.05_year_all.pkl')
| import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
import xgboost as xgb
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
train = joblib.load(utils.processed_data_path + 'train_is_booking_all_top_5_cw_0.05_year_all.pkl')
X_train = train.ix[:,2:]
y_train = pd.DataFrame(train['hotel_cluster'].astype(int))
print "train XGBClassifier..."
cxgb = xgb.XGBClassifier(max_depth=15, n_estimators=100, learning_rate=0.02, colsample_bytree=0.5, min_child_weight=5)
cxgb.fit(X_train, y_train.ravel(), verbose=True)
joblib.dump(cxgb, utils.model_path + 'cxgb_all_without_time_top_5_cw_0.05_year_all.pkl')
| Fix bugs in rf and xgb models | Fix bugs in rf and xgb models
| Python | bsd-3-clause | parkerzf/kaggle-expedia,parkerzf/kaggle-expedia,parkerzf/kaggle-expedia | ---
+++
@@ -16,9 +16,9 @@
print "train XGBClassifier..."
-cxgb = xgb.XGBClassifier(max_depth=15, n_estimators=100, learning_rate=0.02, colsample_bytree=0.5, min_child_weight=5, verbose=1)
+cxgb = xgb.XGBClassifier(max_depth=15, n_estimators=100, learning_rate=0.02, colsample_bytree=0.5, min_child_weight=5)
-cxgb.fit(X_train, y_train.ravel())
+cxgb.fit(X_train, y_train.ravel(), verbose=True)
joblib.dump(cxgb, utils.model_path + 'cxgb_all_without_time_top_5_cw_0.05_year_all.pkl')
|
6c4343837fb3b92e0cc5db83f124a31658359c47 | pymake/builtins.py | pymake/builtins.py | """
Implicit variables; perhaps in the future this will also include some implicit
rules, at least match-anything cancellation rules.
"""
variables = {
'RM': 'rm -f',
'.LIBPATTERNS': 'lib%.so lib%.a',
}
| """
Implicit variables; perhaps in the future this will also include some implicit
rules, at least match-anything cancellation rules.
"""
variables = {
'RM': 'rm -f',
'.LIBPATTERNS': 'lib%.so lib%.a',
'.PYMAKE': '1',
}
| Set .PYMAKE so we can distinguish pymake from gmake | Set .PYMAKE so we can distinguish pymake from gmake
| Python | mit | indygreg/pymake,mozilla/pymake,mozilla/pymake,mozilla/pymake | ---
+++
@@ -6,4 +6,5 @@
variables = {
'RM': 'rm -f',
'.LIBPATTERNS': 'lib%.so lib%.a',
+ '.PYMAKE': '1',
} |
fea5497e615b0b952d76c665284d4090d223fe96 | hoomd/md/pytest/test_table_pressure.py | hoomd/md/pytest/test_table_pressure.py | import hoomd
import io
import numpy
def test_table_pressure(simulation_factory, two_particle_snapshot_factory):
"""Test that write.table can log MD pressure values."""
thermo = hoomd.md.compute.ThermodynamicQuantities(hoomd.filter.All())
snap = two_particle_snapshot_factory()
if snap.communicator.rank == 0:
snap.particles.velocity[:] = [[-2, 0, 0], [2, 0, 0]]
sim = simulation_factory(snap)
sim.operations.add(thermo)
integrator = hoomd.md.Integrator(dt=0.0)
integrator.methods.append(
hoomd.md.methods.NVT(hoomd.filter.All(), tau=1, kT=1))
sim.operations.integrator = integrator
logger = hoomd.logging.Logger(categories=['scalar'])
logger.add(thermo, quantities=['pressure'])
output = io.StringIO("")
table_writer = hoomd.write.Table(1, logger, output)
sim.operations.writers.append(table_writer)
sim.run(1)
output_lines = output.getvalue().split('\n')
ideal_gas_pressure = (2 * thermo.translational_kinetic_energy / 3
/ sim.state.box.volume)
numpy.testing.assert_allclose(float(output_lines[1]),
ideal_gas_pressure,
rtol=0.2)
| import hoomd
import io
import numpy
def test_table_pressure(simulation_factory, two_particle_snapshot_factory):
"""Test that write.table can log MD pressure values."""
thermo = hoomd.md.compute.ThermodynamicQuantities(hoomd.filter.All())
snap = two_particle_snapshot_factory()
if snap.communicator.rank == 0:
snap.particles.velocity[:] = [[-2, 0, 0], [2, 0, 0]]
sim = simulation_factory(snap)
sim.operations.add(thermo)
integrator = hoomd.md.Integrator(dt=0.0)
integrator.methods.append(
hoomd.md.methods.NVT(hoomd.filter.All(), tau=1, kT=1))
sim.operations.integrator = integrator
logger = hoomd.logging.Logger(categories=['scalar'])
logger.add(thermo, quantities=['pressure'])
output = io.StringIO("")
table_writer = hoomd.write.Table(1, logger, output)
sim.operations.writers.append(table_writer)
sim.run(1)
ideal_gas_pressure = (2 * thermo.translational_kinetic_energy / 3
/ sim.state.box.volume)
if sim.device.communicator.rank == 0:
output_lines = output.getvalue().split('\n')
numpy.testing.assert_allclose(float(output_lines[1]),
ideal_gas_pressure,
rtol=0.2)
| Fix test failure in MPI | Fix test failure in MPI
| Python | bsd-3-clause | joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue | ---
+++
@@ -25,9 +25,10 @@
sim.run(1)
- output_lines = output.getvalue().split('\n')
ideal_gas_pressure = (2 * thermo.translational_kinetic_energy / 3
/ sim.state.box.volume)
- numpy.testing.assert_allclose(float(output_lines[1]),
- ideal_gas_pressure,
- rtol=0.2)
+ if sim.device.communicator.rank == 0:
+ output_lines = output.getvalue().split('\n')
+ numpy.testing.assert_allclose(float(output_lines[1]),
+ ideal_gas_pressure,
+ rtol=0.2) |
b316988f45fed26f0694836cf9b5860b7441bc3d | setup.py | setup.py | from distutils.core import setup
setup(
name='PyAuParser',
version='0.53',
author="Esun Kim",
author_email='veblush+git_at_gmail.com',
url='https://github.com/veblush/PyAuParser',
description="New python engine for GOLD Parser",
license='MIT',
packages=['pyauparser', 'pyauparser.test'],
package_dir={'pyauparser.test': 'pyauparser/test'},
package_data={'pyauparser.test': ['data/*']},
scripts=["scripts/auparser.py"],
)
| from distutils.core import setup
setup(
name='PyAuParser',
version='0.53.1',
author="Esun Kim",
author_email='veblush+git_at_gmail.com',
url='https://github.com/veblush/PyAuParser',
description="New python engine for GOLD Parser",
license='MIT',
packages=['pyauparser', 'pyauparser.test'],
package_dir={'pyauparser.test': 'pyauparser/test'},
package_data={'pyauparser.test': ['data/*']},
scripts=["scripts/auparser.py"],
)
| Remove CR from auparser for linux | Remove CR from auparser for linux
| Python | mit | veblush/PyAuParser | ---
+++
@@ -2,7 +2,7 @@
setup(
name='PyAuParser',
- version='0.53',
+ version='0.53.1',
author="Esun Kim",
author_email='veblush+git_at_gmail.com',
url='https://github.com/veblush/PyAuParser', |
bd263dbbfe8d9dd595d7c8ab3a4a91ee73aea3cd | setup.py | setup.py | #! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# Setup for the PyMeshToolkit package
#
# External dependencies
from setuptools import setup, find_packages
# Setup configuration
setup(
name = "PyMeshToolkit",
version = "0.1dev",
packages = find_packages(),
scripts = ['Scripts/pymeshtoolkit.py'],
author = "Michaël Roy",
author_email = "microygh@gmail.com",
description = "Python 3D Mesh Toolkit",
license = "MIT",
url = "https://github.com/microy/PyMeshToolkit",
)
| #! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# Setup for the PyMeshToolkit package
#
# External dependencies
from setuptools import setup, find_packages
# Setup configuration
setup(
name = "PyMeshToolkit",
version = "0.1dev",
packages = find_packages(),
scripts = ['pymeshtoolkit.py'],
author = "Michaël Roy",
author_email = "microygh@gmail.com",
description = "Python 3D Mesh Toolkit",
license = "MIT",
url = "https://github.com/microy/PyMeshToolkit",
)
| Move the script to the main directory. | Move the script to the main directory.
| Python | mit | microy/MeshToolkit,microy/MeshToolkit,microy/PyMeshToolkit,microy/PyMeshToolkit | ---
+++
@@ -14,7 +14,7 @@
name = "PyMeshToolkit",
version = "0.1dev",
packages = find_packages(),
- scripts = ['Scripts/pymeshtoolkit.py'],
+ scripts = ['pymeshtoolkit.py'],
author = "Michaël Roy",
author_email = "microygh@gmail.com",
description = "Python 3D Mesh Toolkit", |
af8e871eb2752f0fe75ccd7b2a12f81a5ef19d04 | tests/test_np.py | tests/test_np.py | from parser_tool import parse, get_parser
def test_np():
grammar = get_parser("grammars/test_np.fcfg", trace=0)
f = open("grammars/nounphrase.sample")
for line in f:
# remove newline
actual_line = line[:-1]
trees = parse(grammar, actual_line)
assert len(trees) > 0, "Failed: %s" % actual_line
f.close()
| from parser_tool import parse, get_parser
from utils import go_over_file
grammar = get_parser("grammars/test_np.fcfg", trace=0)
def test_np_positive():
def is_ok(sentence):
trees = parse(grammar, sentence)
assert len(trees) > 0, "Failed: %s" % sentence
go_over_file("grammars/nounphrase.sample", is_ok)
def test_np_negative():
""" tests to see if grammar refuses wrong samples """
def is_not_ok(sentence):
trees = parse(grammar, sentence)
assert len(trees) == 0, "Failed: %s" % sentence
go_over_file("grammars/nounphrase.sample.negative", is_not_ok)
| Test both correct and wrong samples of noun phrase | Test both correct and wrong samples of noun phrase
Extended noun phrase test to check for the grammar refusing wrong
samples of noun phrases. Also added a utility module called
utils.py
| Python | mit | caninemwenja/marker,kmwenja/marker | ---
+++
@@ -1,13 +1,21 @@
from parser_tool import parse, get_parser
+from utils import go_over_file
-def test_np():
- grammar = get_parser("grammars/test_np.fcfg", trace=0)
+grammar = get_parser("grammars/test_np.fcfg", trace=0)
- f = open("grammars/nounphrase.sample")
- for line in f:
- # remove newline
- actual_line = line[:-1]
+def test_np_positive():
+ def is_ok(sentence):
+ trees = parse(grammar, sentence)
+ assert len(trees) > 0, "Failed: %s" % sentence
+
+ go_over_file("grammars/nounphrase.sample", is_ok)
- trees = parse(grammar, actual_line)
- assert len(trees) > 0, "Failed: %s" % actual_line
- f.close()
+def test_np_negative():
+ """ tests to see if grammar refuses wrong samples """
+
+ def is_not_ok(sentence):
+ trees = parse(grammar, sentence)
+ assert len(trees) == 0, "Failed: %s" % sentence
+
+ go_over_file("grammars/nounphrase.sample.negative", is_not_ok)
+ |
2102a955dd5bdceca00a087e1613e2974b54cf8e | setup.py | setup.py | """
Flask-Selfdoc
-------------
Flask selfdoc automatically creates an online documentation for your flask app.
"""
from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(
name='Flask-Selfdoc',
version='1.0',
url='http://github.com/jwg4/flask-selfdoc',
license='MIT',
author='Arnaud Coomans',
maintainer='Jack Grahl',
maintainer_email='jack.grahl@gmail.com',
description='Documentation generator for flask',
long_description=readme(),
# py_modules=['flask_autodoc'],
# if you would be using a package instead use packages instead
# of py_modules:
packages=['flask_selfdoc'],
package_data={'flask_selfdoc': ['templates/autodoc_default.html']},
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'Flask'
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
test_suite='tests',
)
| """
Flask-Selfdoc
-------------
Flask selfdoc automatically creates an online documentation for your flask app.
"""
from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(
name='Flask-Selfdoc',
version='1.0rc1',
url='http://github.com/jwg4/flask-selfdoc',
license='MIT',
author='Arnaud Coomans',
maintainer='Jack Grahl',
maintainer_email='jack.grahl@gmail.com',
description='Documentation generator for flask',
long_description=readme(),
# py_modules=['flask_autodoc'],
# if you would be using a package instead use packages instead
# of py_modules:
packages=['flask_selfdoc'],
package_data={'flask_selfdoc': ['templates/autodoc_default.html']},
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'Flask'
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
test_suite='tests',
)
| Make this the first release candidate. | Make this the first release candidate.
| Python | mit | jwg4/flask-autodoc,jwg4/flask-autodoc | ---
+++
@@ -14,7 +14,7 @@
setup(
name='Flask-Selfdoc',
- version='1.0',
+ version='1.0rc1',
url='http://github.com/jwg4/flask-selfdoc',
license='MIT',
author='Arnaud Coomans', |
b364d648f2e4071c750d9d8fdf000f8dce936a0a | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(
name = "deco",
version = "0.5.1",
description = "A decorator for concurrency",
packages = ["deco"],
author='Alex Sherman',
author_email='asherman1024@gmail.com',
url='https://github.com/alex-sherman/deco')
| #!/usr/bin/env python
from distutils.core import setup
setup(
name = "deco",
version = "0.5.2",
description = "A decorator for concurrency",
packages = ["deco"],
author='Alex Sherman',
author_email='asherman1024@gmail.com',
url='https://github.com/alex-sherman/deco')
| Increment version number, includes bug fixes for synchronized decorator and KeyboardInterrupt handling | Increment version number, includes bug fixes for synchronized decorator and KeyboardInterrupt handling
| Python | mit | alex-sherman/deco | ---
+++
@@ -4,7 +4,7 @@
setup(
name = "deco",
- version = "0.5.1",
+ version = "0.5.2",
description = "A decorator for concurrency",
packages = ["deco"],
author='Alex Sherman', |
cebb2341fed3eaabc126f33ee7ad6352164ac993 | setup.py | setup.py | #!/usr/bin/python
import time
from datetime import date
from setuptools import setup
from pagekite.common import APPVER
import os
try:
# This borks sdist.
os.remove('.SELF')
except:
pass
setup(
name="pagekite",
version=APPVER.replace('github', 'dev%d' % (120*int(time.time()/120))),
license="AGPLv3+",
author="Bjarni R. Einarsson",
author_email="bre@pagekite.net",
url="http://pagekite.org/",
description="""PageKite makes localhost servers visible to the world.""",
long_description="""\
PageKite is a system for running publicly visible servers (generally
web servers) on machines without a direct connection to the Internet,
such as mobile devices or computers behind restrictive firewalls.
PageKite works around NAT, firewalls and IP-address limitations by
using a combination of tunnels and reverse proxies.
Natively supported protocols: HTTP, HTTPS
Any other TCP-based service, including SSH and VNC, may be exposed
as well to clients supporting HTTP Proxies.
""",
packages=['pagekite', 'pagekite.ui', 'pagekite.proto'],
scripts=['scripts/pagekite', 'scripts/lapcat', 'scripts/vipagekite'],
install_requires=['SocksipyChain >= 2.0.15']
)
| #!/usr/bin/python
import time
from datetime import date
from setuptools import setup
from pagekite.common import APPVER
import os
try:
# This borks sdist.
os.remove('.SELF')
except:
pass
setup(
name="pagekite",
version=os.getenv(
'PAGEKITE_VERSION',
APPVER.replace('github', 'dev%d' % (120*int(time.time()/120)))),
license="AGPLv3+",
author="Bjarni R. Einarsson",
author_email="bre@pagekite.net",
url="http://pagekite.org/",
description="""PageKite makes localhost servers visible to the world.""",
long_description="""\
PageKite is a system for running publicly visible servers (generally
web servers) on machines without a direct connection to the Internet,
such as mobile devices or computers behind restrictive firewalls.
PageKite works around NAT, firewalls and IP-address limitations by
using a combination of tunnels and reverse proxies.
Natively supported protocols: HTTP, HTTPS
Any other TCP-based service, including SSH and VNC, may be exposed
as well to clients supporting HTTP Proxies.
""",
packages=['pagekite', 'pagekite.ui', 'pagekite.proto'],
scripts=['scripts/pagekite', 'scripts/lapcat', 'scripts/vipagekite'],
install_requires=['SocksipyChain >= 2.0.15']
)
| Make it possible to manually override version numbers | Make it possible to manually override version numbers
| Python | agpl-3.0 | pagekite/PyPagekite,pagekite/PyPagekite,pagekite/PyPagekite | ---
+++
@@ -13,7 +13,9 @@
setup(
name="pagekite",
- version=APPVER.replace('github', 'dev%d' % (120*int(time.time()/120))),
+ version=os.getenv(
+ 'PAGEKITE_VERSION',
+ APPVER.replace('github', 'dev%d' % (120*int(time.time()/120)))),
license="AGPLv3+",
author="Bjarni R. Einarsson",
author_email="bre@pagekite.net", |
e4cb8bbffd6f60002cff8f37d42f576ba6f1891c | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = "jpb",
version = "0.0.1",
packages = find_packages(),
#package_dir = {'':"lib"},
zip_safe = False,
entry_points = {
'console_scripts': [
'jpb_generate_source_package = jpb.cli:generate_source_package',
'jpb_build_source_package = jpb.cli:build_source_package',
'jpb_provide_package = jpb.cli:provide_package'
],
},
author = "Bernhard Miklautz",
author_email = "bernhard.miklautz@shacknet.at",
license = "MIT",
#keywords=
#url=
)
# vim:foldmethod=marker ts=2 ft=python ai sw=2
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = "jpb",
version = "0.0.1",
packages = find_packages(),
#package_dir = {'':"lib"},
zip_safe = False,
entry_points = {
'console_scripts': [
'jpb_generate_source_package = jpb.cli:generate_source_package',
'jpb_generate_binary_package = jpb.cli:generate_binary_package',
'jpb_provide_package = jpb.cli:provide_package'
],
},
author = "Bernhard Miklautz",
author_email = "bernhard.miklautz@shacknet.at",
license = "MIT",
#keywords=
#url=
)
# vim:foldmethod=marker ts=2 ft=python ai sw=2
| Rename binary back to jpb_generate_binary_package | Rename binary back to jpb_generate_binary_package
Binary jpb_generate_binary_package was named as jpb_build_source_package
This seems to be an accidental change made in commit df61be3d
| Python | mit | bmiklautz/jenkins-package-builder | ---
+++
@@ -11,7 +11,7 @@
entry_points = {
'console_scripts': [
'jpb_generate_source_package = jpb.cli:generate_source_package',
- 'jpb_build_source_package = jpb.cli:build_source_package',
+ 'jpb_generate_binary_package = jpb.cli:generate_binary_package',
'jpb_provide_package = jpb.cli:provide_package'
],
}, |
e32d470ba47973f3827a5f85e701826bbb08b621 | setup.py | setup.py | from distutils.core import setup
setup(
name='lcinvestor',
version=open('lcinvestor/VERSION').read(),
author='Jeremy Gillick',
author_email='none@none.com',
packages=['lcinvestor', 'lcinvestor.tests', 'lcinvestor.settings'],
package_data={
'lcinvestor': ['VERSION'],
'lcinvestor.settings': ['settings.yaml']
},
scripts=['bin/lcinvestor'],
url='https://github.com/jgillick/LendingClubAutoInvestor',
license=open('LICENSE.txt').read(),
description='A simple tool that will watch your LendingClub account and automatically invest cash as it becomes available.',
long_description=open('README.rst').read(),
install_requires=[
"lendingclub >= 0.1.2",
# "python-daemon >= 1.6",
"argparse >= 1.2.1",
"pybars >= 0.0.4",
"pyyaml >= 3.09",
"pause >= 0.1.2"
],
platforms='osx, posix, linux, windows',
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Environment :: Console',
'Environment :: No Input/Output (Daemon)',
'Topic :: Office/Business :: Financial'
],
keywords='lendingclub investing daemon'
)
| from distutils.core import setup
setup(
name='lcinvestor',
version=open('lcinvestor/VERSION').read(),
author='Jeremy Gillick',
author_email='none@none.com',
packages=['lcinvestor', 'lcinvestor.tests', 'lcinvestor.settings'],
package_data={
'lcinvestor': ['VERSION'],
'lcinvestor.settings': ['settings.yaml']
},
scripts=['bin/lcinvestor', 'bin/lcinvestor.bat'],
url='https://github.com/jgillick/LendingClubAutoInvestor',
license=open('LICENSE.txt').read(),
description='A simple tool that will watch your LendingClub account and automatically invest cash as it becomes available.',
long_description=open('README.rst').read(),
install_requires=[
"lendingclub >= 0.1.3",
# "python-daemon >= 1.6",
"argparse >= 1.2.1",
"pyyaml >= 3.09",
"pause >= 0.1.2"
],
platforms='osx, posix, linux, windows',
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Environment :: Console',
'Environment :: No Input/Output (Daemon)',
'Topic :: Office/Business :: Financial'
],
keywords='lendingclub investing daemon'
)
| Update requirements. Add bat file | Update requirements. Add bat file
| Python | mit | jgillick/LendingClubAutoInvestor,ilyakatz/LendingClubAutoInvestor,ilyakatz/LendingClubAutoInvestor | ---
+++
@@ -10,16 +10,15 @@
'lcinvestor': ['VERSION'],
'lcinvestor.settings': ['settings.yaml']
},
- scripts=['bin/lcinvestor'],
+ scripts=['bin/lcinvestor', 'bin/lcinvestor.bat'],
url='https://github.com/jgillick/LendingClubAutoInvestor',
license=open('LICENSE.txt').read(),
description='A simple tool that will watch your LendingClub account and automatically invest cash as it becomes available.',
long_description=open('README.rst').read(),
install_requires=[
- "lendingclub >= 0.1.2",
+ "lendingclub >= 0.1.3",
# "python-daemon >= 1.6",
"argparse >= 1.2.1",
- "pybars >= 0.0.4",
"pyyaml >= 3.09",
"pause >= 0.1.2"
], |
aee5dd434b29c43b04ccc13824ebebb490db3606 | setup.py | setup.py | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Collect xUnit xml files and upload them to bob-bench.org',
'author': 'Holger Hans Peter Freyther',
'url': 'http://www.bob-bench.org',
'download_url': 'http://www.bob-bench.org',
'author_email': 'help@bob-bench.org',
'version': '4',
'install_requires': [
'requests',
],
'license': 'AGPLv3+',
'packages': ['benchupload'],
'scripts': [],
'entry_points': {'console_scripts': ['benchupload=benchupload.__main__:main']},
'name': 'benchupload'
}
setup(**config)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Collect xUnit xml files and upload them to bob-bench.org',
'author': 'Holger Hans Peter Freyther',
'url': 'http://www.bob-bench.org',
'download_url': 'http://www.bob-bench.org',
'author_email': 'help@bob-bench.org',
'version': '5',
'install_requires': [
'requests',
],
'license': 'AGPLv3+',
'packages': ['benchupload'],
'scripts': [],
'entry_points': {'console_scripts': ['benchupload=benchupload.__main__:main']},
'name': 'benchupload'
}
setup(**config)
| Make a new release with the job id and cli args | Make a new release with the job id and cli args
| Python | agpl-3.0 | bob-bench/benchupload,bob-bench/benchupload | ---
+++
@@ -9,7 +9,7 @@
'url': 'http://www.bob-bench.org',
'download_url': 'http://www.bob-bench.org',
'author_email': 'help@bob-bench.org',
- 'version': '4',
+ 'version': '5',
'install_requires': [
'requests',
], |
96a0175f897621b8e828293c6e3ba089eb50ba4e | setup.py | setup.py | from setuptools import setup
setup(
name='nnpy',
version='1.1',
url='https://github.com/nanomsg/nnpy',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
],
packages=['nnpy'],
setup_requires=["cffi>=1.0.0"],
cffi_modules=["generate.py:ffi"],
install_requires=['cffi'],
)
| from setuptools import setup
setup(
name='nnpy',
version='1.2',
url='https://github.com/nanomsg/nnpy',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
],
packages=['nnpy'],
setup_requires=["cffi>=1.0.0"],
cffi_modules=["generate.py:ffi"],
install_requires=['cffi'],
)
| Bump version number to 1.2 | Bump version number to 1.2
| Python | mit | nanomsg/nnpy | ---
+++
@@ -2,7 +2,7 @@
setup(
name='nnpy',
- version='1.1',
+ version='1.2',
url='https://github.com/nanomsg/nnpy',
license='MIT',
author='Dirkjan Ochtman', |
2e54c8050f994646e7cbf9f18c9ab557341ec3f5 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name="IIS",
version="0.0",
long_description=__doc__,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
"Flask>=0.11.1,<0.12.0",
"Flask-Bootstrap>=3.3.7.0,<4.0.0.0",
"Flask-Login>=0.3.2,<0.4.0",
"Flask-Mail>=0.9.1,<0.10.0",
"Flask-SQLAlchemy>=2.1,<3.0",
"Flask-User>=0.6.8,<0.7.0",
"Flask-WTF>=0.12,<0.13.0",
"Flask-Migrate>=2.0.0,<3.0.0",
"Flask-Testing>=0.6.1,<0.7.0"
],
extras_require={
'dev': [
'mypy-lang>=0.4.4,<0.5.0'
]
}
)
| from setuptools import setup, find_packages
setup(
name="IIS",
version="0.0",
long_description=__doc__,
packages=find_packages(exclude=["tests.*", "tests"]),
include_package_data=True,
zip_safe=False,
install_requires=[
"Flask>=0.11.1,<0.12.0",
"Flask-Bootstrap>=3.3.7.0,<4.0.0.0",
"Flask-Login>=0.3.2,<0.4.0",
"Flask-Mail>=0.9.1,<0.10.0",
"Flask-SQLAlchemy>=2.1,<3.0",
"Flask-User>=0.6.8,<0.7.0",
"Flask-WTF>=0.12,<0.13.0",
"Flask-Migrate>=2.0.0,<3.0.0",
"Flask-Testing>=0.6.1,<0.7.0"
],
extras_require={
'dev': [
'mypy-lang>=0.4.4,<0.5.0'
]
}
)
| Exclude tests from installed packages | Exclude tests from installed packages
| Python | agpl-3.0 | interactomix/iis,interactomix/iis | ---
+++
@@ -4,7 +4,7 @@
name="IIS",
version="0.0",
long_description=__doc__,
- packages=find_packages(),
+ packages=find_packages(exclude=["tests.*", "tests"]),
include_package_data=True,
zip_safe=False,
install_requires=[ |
aa09ffc91c7cb1e54512132320b78776227b6417 | setup.py | setup.py | from setuptools import find_packages, setup
setup_args = dict(
name='furious',
version='0.1',
license='Apache',
description='Furious is a lightweight library that wraps Google App Engine'
'taskqueues to make building dynamic workflows easy.',
author='Robert Kluin',
author_email='robert.kluin@webfilings.com',
url='http://github.com/WebFilings/furious',
packages=find_packages(),
classifiers=[
'Development Status :: 2 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: Apache',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
)
if __name__ == '__main__':
setup(**setup_args)
| from setuptools import find_packages, setup
setup_args = dict(
name='furious',
version='0.9',
license='Apache',
description='Furious is a lightweight library that wraps Google App Engine'
'taskqueues to make building dynamic workflows easy.',
author='Robert Kluin',
author_email='robert.kluin@webfilings.com',
url='http://github.com/WebFilings/furious',
packages=find_packages(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: Apache',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
)
if __name__ == '__main__':
setup(**setup_args)
| Increment the version to 0.9 and set to beta. | Increment the version to 0.9 and set to beta.
Getting close to stable and 1.0 release.
| Python | apache-2.0 | rosshendrickson-wf/furious,mattsanders-wf/furious,mattsanders-wf/furious,andreleblanc-wf/furious,Workiva/furious,beaulyddon-wf/furious,rosshendrickson-wf/furious,andreleblanc-wf/furious,Workiva/furious,beaulyddon-wf/furious | ---
+++
@@ -3,7 +3,7 @@
setup_args = dict(
name='furious',
- version='0.1',
+ version='0.9',
license='Apache',
description='Furious is a lightweight library that wraps Google App Engine'
'taskqueues to make building dynamic workflows easy.',
@@ -12,7 +12,7 @@
url='http://github.com/WebFilings/furious',
packages=find_packages(),
classifiers=[
- 'Development Status :: 2 - Alpha',
+ 'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: Apache', |
3cc90bb8ccce7b2feefe95173f095a71996d2633 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup, Command
class TestDiscovery(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
errno = subprocess.call([
sys.executable,
'-m', 'unittest',
'discover',
'-p', '*.py',
'tests',
])
raise SystemExit(errno)
setup(name='steel',
version='0.1',
description='A Python framework for describing binary file formats',
author='Marty Alchin',
author_email='marty@martyalchin.com',
url='https://github.com/gulopine/steel',
packages=['steel', 'steel.bits', 'steel.chunks', 'steel.common', 'steel.fields'],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: System :: Filesystems',
],
cmdclass={'test': TestDiscovery},
)
| #!/usr/bin/env python
from distutils.core import setup, Command
class TestDiscovery(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
errno = subprocess.call([
sys.executable,
'-m', 'unittest',
'discover',
'-p', '*.py',
'tests',
])
raise SystemExit(errno)
setup(name='steel',
version='0.2',
description='A Python framework for describing binary file formats',
author='Marty Alchin',
author_email='marty@martyalchin.com',
url='https://github.com/gulopine/steel',
packages=['steel', 'steel.bits', 'steel.chunks', 'steel.common', 'steel.fields'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: System :: Filesystems',
],
cmdclass={'test': TestDiscovery},
)
| Update to version 0.2 and some trove classifiers | Update to version 0.2 and some trove classifiers
| Python | bsd-3-clause | gulopine/steel | ---
+++
@@ -25,18 +25,19 @@
setup(name='steel',
- version='0.1',
+ version='0.2',
description='A Python framework for describing binary file formats',
author='Marty Alchin',
author_email='marty@martyalchin.com',
url='https://github.com/gulopine/steel',
packages=['steel', 'steel.bits', 'steel.chunks', 'steel.common', 'steel.fields'],
classifiers=[
- 'Development Status :: 2 - Pre-Alpha',
+ 'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
+ 'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: System :: Filesystems',
], |
0991a4207c7b737186c188719c4dd21c76f3528b | setup.py | setup.py | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
requires = [
'pyramid',
'pyramid_mako',
'WebHelpers',
'FormEncode',
]
setup(name='pyramid_simpleform',
version='0.7',
description='pyramid_simpleform',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Chris Lambacher',
author_email='chris@kateandchris.net',
url='https://github.com/Pylons/pyramid_simpleform',
keywords='web pyramid pylons',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
license="LICENSE.txt",
install_requires=requires,
tests_require=requires,
test_suite="pyramid_simpleform",
)
| import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
requires = [
'pyramid',
'WebHelpers',
'FormEncode',
]
tests_require = requires + [
'pyramid_mako',
]
setup(name='pyramid_simpleform',
version='0.7',
description='pyramid_simpleform',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Chris Lambacher',
author_email='chris@kateandchris.net',
url='https://github.com/Pylons/pyramid_simpleform',
keywords='web pyramid pylons',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
license="LICENSE.txt",
install_requires=requires,
tests_require=tests_require,
test_suite="pyramid_simpleform",
)
| Make Mako requirement only for tests | Make Mako requirement only for tests
| Python | bsd-3-clause | vsobolmaven/pyramid_simpleform | ---
+++
@@ -12,9 +12,11 @@
requires = [
'pyramid',
- 'pyramid_mako',
'WebHelpers',
'FormEncode',
+]
+tests_require = requires + [
+ 'pyramid_mako',
]
setup(name='pyramid_simpleform',
@@ -36,7 +38,6 @@
zip_safe=False,
license="LICENSE.txt",
install_requires=requires,
- tests_require=requires,
+ tests_require=tests_require,
test_suite="pyramid_simpleform",
)
- |
a670ec2aa1f136155d483cb8697f0613962e604a | setup.py | setup.py | from setuptools import setup, find_packages
from distutils.extension import Extension
from Cython.Build import cythonize
extension_defaults = {
'extra_compile_args': [
'-std=gnu++11',
'-O3',
'-Wall',
'-Wextra',
'-Wconversion',
'-fno-strict-aliasing'
],
'language': 'c++',
'libraries': [
'rocksdb',
'snappy',
'bz2',
'z'
]
}
mod1 = Extension(
'rocksdb._rocksdb',
['rocksdb/_rocksdb.pyx'],
**extension_defaults
)
setup(
name="pyrocksdb",
version='0.4',
description="Python bindings for RocksDB",
keywords='rocksdb',
author='Stephan Hofmockel',
author_email="Use the github issues",
url="https://github.com/stephan-hof/pyrocksdb",
license='BSD License',
install_requires=[
'setuptools',
'Cython>=0.20',
],
package_dir={'rocksdb': 'rocksdb'},
packages=find_packages('.'),
ext_modules=cythonize([mod1]),
test_suite='rocksdb.tests',
include_package_data=True
)
| from setuptools import setup, find_packages
from distutils.extension import Extension
from Cython.Build import cythonize
extension_defaults = {
'extra_compile_args': [
'-std=c++11',
'-O3',
'-Wall',
'-Wextra',
'-Wconversion',
'-fno-strict-aliasing'
],
'language': 'c++',
'libraries': [
'rocksdb',
'snappy',
'bz2',
'z'
]
}
mod1 = Extension(
'rocksdb._rocksdb',
['rocksdb/_rocksdb.pyx'],
**extension_defaults
)
setup(
name="pyrocksdb",
version='0.4',
description="Python bindings for RocksDB",
keywords='rocksdb',
author='Stephan Hofmockel',
author_email="Use the github issues",
url="https://github.com/stephan-hof/pyrocksdb",
license='BSD License',
install_requires=[
'setuptools',
'Cython>=0.20',
],
package_dir={'rocksdb': 'rocksdb'},
packages=find_packages('.'),
ext_modules=cythonize([mod1]),
test_suite='rocksdb.tests',
include_package_data=True
)
| Use another compiler flag wich works for clang and gcc. | Use another compiler flag wich works for clang and gcc.
| Python | bsd-3-clause | stephan-hof/pyrocksdb,stephan-hof/pyrocksdb | ---
+++
@@ -4,7 +4,7 @@
extension_defaults = {
'extra_compile_args': [
- '-std=gnu++11',
+ '-std=c++11',
'-O3',
'-Wall',
'-Wextra', |
48539fdd2a244218a1ee2a59d026d3759b9e3475 | setup.py | setup.py | from distutils.core import setup
import pkg_resources
import sys
requires = None
if sys.version_info < (2, 7):
requires = ['argparse']
version = pkg_resources.require("fitparse")[0].version
setup(
name='fitparse',
version=version,
description='Python library to parse ANT/Garmin .FIT files',
author='David Cooper, Kévin Gomez',
author_email='dave@kupesoft.com, contact@kevingomez.fr',
url='https://github.com/K-Phoen/python-fitparse',
license=open('LICENSE').read(),
packages=['fitparse'],
scripts=['scripts/fitdump'], # Don't include generate_profile.py
install_requires=requires,
)
| from distutils.core import setup
import pkg_resources
import sys
requires = ['six']
if sys.version_info < (2, 7):
requires.append('argparse')
version = pkg_resources.require("fitparse")[0].version
setup(
name='fitparse',
version=version,
description='Python library to parse ANT/Garmin .FIT files',
author='David Cooper, Kévin Gomez',
author_email='dave@kupesoft.com, contact@kevingomez.fr',
url='https://github.com/K-Phoen/python-fitparse',
license=open('LICENSE').read(),
packages=['fitparse'],
scripts=['scripts/fitdump'], # Don't include generate_profile.py
install_requires=requires,
)
| Add six as a dependency | Add six as a dependency
six is imported, but not listed as a dependency in setup.py. Add it.
| Python | isc | K-Phoen/python-fitparse | ---
+++
@@ -3,9 +3,9 @@
import sys
-requires = None
+requires = ['six']
if sys.version_info < (2, 7):
- requires = ['argparse']
+ requires.append('argparse')
version = pkg_resources.require("fitparse")[0].version
|
643a01b56ebdbb706e3079122f570d450464f440 | setup.py | setup.py | from __future__ import print_function
from setuptools import setup, find_packages
import sys
v = sys.version_info
if v[:2] < (3, 5):
error = "ERROR: jupyterhub-kubespawner requires Python version 3.5 or above."
print(error, file=sys.stderr)
sys.exit(1)
setup(
name='jupyterhub-kubespawner',
version='0.10.2.dev',
install_requires=[
'jupyterhub>=0.8',
'pyYAML',
'kubernetes>=7.0',
'escapism',
'jinja2',
'async_generator>=1.8',
],
python_requires='>=3.5',
extras_require={
'test': [
'pytest>=3.3',
'pytest-cov',
'pytest-asyncio',
]
},
description='JupyterHub Spawner for Kubernetes',
url='http://github.com/jupyterhub/kubespawner',
author='Jupyter Contributors',
author_email='jupyter@googlegroups.com',
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
license='BSD',
packages=find_packages(),
project_urls={
'Documentation': 'https://jupyterhub-kubespawner.readthedocs.io',
'Source': 'https://github.com/jupyterhub/kubespawner',
'Tracker': 'https://github.com/jupyterhub/kubespawner/issues',
},
)
| from __future__ import print_function
from setuptools import setup, find_packages
import sys
v = sys.version_info
if v[:2] < (3, 5):
error = "ERROR: jupyterhub-kubespawner requires Python version 3.5 or above."
print(error, file=sys.stderr)
sys.exit(1)
setup(
name='jupyterhub-kubespawner',
version='0.10.2.dev',
install_requires=[
'jupyterhub>=0.8',
'pyYAML',
'kubernetes>=7.0',
'escapism',
'jinja2',
'async_generator>=1.8',
],
python_requires='>=3.5',
extras_require={
'test': [
'flake8',
'pytest>=3.3',
'pytest-cov',
'pytest-asyncio',
]
},
description='JupyterHub Spawner for Kubernetes',
url='http://github.com/jupyterhub/kubespawner',
author='Jupyter Contributors',
author_email='jupyter@googlegroups.com',
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
license='BSD',
packages=find_packages(),
project_urls={
'Documentation': 'https://jupyterhub-kubespawner.readthedocs.io',
'Source': 'https://github.com/jupyterhub/kubespawner',
'Tracker': 'https://github.com/jupyterhub/kubespawner/issues',
},
)
| Add flake8 static code testing | Add flake8 static code testing
| Python | bsd-3-clause | jupyterhub/kubespawner,yuvipanda/jupyterhub-kubernetes-spawner | ---
+++
@@ -22,6 +22,7 @@
python_requires='>=3.5',
extras_require={
'test': [
+ 'flake8',
'pytest>=3.3',
'pytest-cov',
'pytest-asyncio', |
668f84625189853dbe6caab9a1e5e84a12d108ed | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup
setup(
name='mezzanine-openshift',
version='1.1',
description='Mezzanine configured for deployment on OpenShift.',
author='Isaac Bythewood',
author_email='isaac@bythewood.me',
url='http://isaacbythewood.com/',
install_requires=[
'Django==1.5.1',
'mezzanine==1.4.6',
'django_compressor==1.3'
],
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='mezzanine-openshift',
version='1.2',
description='Mezzanine configured for deployment on OpenShift.',
author='Isaac Bythewood',
author_email='isaac@bythewood.me',
url='http://isaacbythewood.com/',
install_requires=[
'Django==1.5.1',
'mezzanine==1.4.7',
'django_compressor==1.3'
],
)
| Update to the latest version of Mezzanine 1.4.7 and bump the version of mezzanine-openshift to 1.2 | Update to the latest version of Mezzanine 1.4.7 and bump the version of mezzanine-openshift to 1.2 | Python | mit | chiora93/WavelenBlog,chiora93/WavelenBlog,chiora93/WavelenBlog | ---
+++
@@ -4,14 +4,14 @@
setup(
name='mezzanine-openshift',
- version='1.1',
+ version='1.2',
description='Mezzanine configured for deployment on OpenShift.',
author='Isaac Bythewood',
author_email='isaac@bythewood.me',
url='http://isaacbythewood.com/',
install_requires=[
'Django==1.5.1',
- 'mezzanine==1.4.6',
+ 'mezzanine==1.4.7',
'django_compressor==1.3'
],
) |
26cbf83b8d7665a48a399e5af59f784fba4b9463 | setup.py | setup.py | from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='prettystring',
version='0.1.0',
description='Build ANSI color encoded strings with ease.',
long_description=readme(),
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: User Interfaces',
'Topic :: Terminals',
'Topic :: Text Processing :: General',
'Topic :: Utilities'
],
keywords='color colorful pretty string strings',
url='https://github.com/robolivable/prettystring',
author='Robert Oliveira',
author_email='oliveira.rlde@gmail.com',
license='MIT',
packages=['prettystring'],
install_requires=['enum34==1.1.6'])
| from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='prettystring',
version='0.1.1',
description='Build ANSI color encoded strings with ease.',
long_description=readme(),
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: User Interfaces',
'Topic :: Terminals',
'Topic :: Text Processing :: General',
'Topic :: Utilities'
],
keywords='color colorful pretty string strings',
url='https://github.com/robolivable/prettystring',
author='Robert Oliveira',
author_email='oliveira.rlde@gmail.com',
license='MIT',
packages=['prettystring'],
install_requires=['enum34==1.1.6'])
| Update build version to 0.1.1 | Update build version to 0.1.1
| Python | mit | robolivable/prettystring | ---
+++
@@ -5,7 +5,7 @@
return f.read()
setup(name='prettystring',
- version='0.1.0',
+ version='0.1.1',
description='Build ANSI color encoded strings with ease.',
long_description=readme(),
classifiers=[ |
84c0a5fc9bea997964e4e4da63151717a11aaf14 | setup.py | setup.py | import re
import os
from setuptools import setup, find_packages
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
with open('abakus/__init__.py', 'r') as fd:
version = re.search(
r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(),
re.MULTILINE
).group(1)
setup(
name="django-auth-abakus",
version='1.1.0',
url='http://github.com/webkom/django-auth-abakus',
author='Webkom, Abakus Linjeforening',
author_email='webkom@abakus.no',
description='A django auth module that can be used to to authenticate '
'users against the API of abakus.no.',
packages=find_packages(exclude='tests'),
install_requires=[
'requests==2.7.0',
],
tests_require=[
'django>=1.4',
'requests==2.7.0',
'responses'
],
license='MIT',
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
"Programming Language :: Python",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
"Topic :: Software Development :: Libraries :: Python Modules",
"Framework :: Django",
"Environment :: Web Environment",
"Operating System :: OS Independent",
"Natural Language :: English",
]
)
| import re
import os
from setuptools import setup, find_packages
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
with open('abakus/__init__.py', 'r') as fd:
version = re.search(
r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(),
re.MULTILINE
).group(1)
setup(
name="django-auth-abakus",
version='1.1.0',
url='http://github.com/webkom/django-auth-abakus',
author='Webkom, Abakus Linjeforening',
author_email='webkom@abakus.no',
description='A django auth module that can be used to to authenticate '
'users against the API of abakus.no.',
packages=find_packages(exclude='tests'),
install_requires=[
'requests==2.10.0',
],
tests_require=[
'django>=1.4',
'requests==2.7.0',
'responses'
],
license='MIT',
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
"Programming Language :: Python",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
"Topic :: Software Development :: Libraries :: Python Modules",
"Framework :: Django",
"Environment :: Web Environment",
"Operating System :: OS Independent",
"Natural Language :: English",
]
)
| Upgrade dependency requests to ==2.10.0 | Upgrade dependency requests to ==2.10.0
| Python | mit | webkom/django-auth-abakus | ---
+++
@@ -22,7 +22,7 @@
'users against the API of abakus.no.',
packages=find_packages(exclude='tests'),
install_requires=[
- 'requests==2.7.0',
+ 'requests==2.10.0',
],
tests_require=[
'django>=1.4', |
42f4423b8e7d39dca766afa99bd129e31500e7b0 | setup.py | setup.py | from setuptools import setup, find_packages
import cplcom
setup(
name='CPLCom',
version=cplcom.__version__,
packages=find_packages(),
package_data={'cplcom': ['../media/*', './*.kv']},
install_requires=['moa', 'kivy'],
author='Matthew Einhorn',
author_email='moiein2000@gmail.com',
license='MIT',
description=(
'Project for common widgets used with Moa.')
)
| from setuptools import setup, find_packages
import cplcom
setup(
name='CPLCom',
version=cplcom.__version__,
packages=find_packages(),
package_data={'cplcom': ['../media/*', 'graphics.kv']},
install_requires=['moa', 'kivy'],
author='Matthew Einhorn',
author_email='moiein2000@gmail.com',
license='MIT',
description=(
'Project for common widgets used with Moa.')
)
| Include kv files in package. | Include kv files in package.
| Python | mit | matham/cplcom | ---
+++
@@ -6,7 +6,7 @@
name='CPLCom',
version=cplcom.__version__,
packages=find_packages(),
- package_data={'cplcom': ['../media/*', './*.kv']},
+ package_data={'cplcom': ['../media/*', 'graphics.kv']},
install_requires=['moa', 'kivy'],
author='Matthew Einhorn',
author_email='moiein2000@gmail.com', |
e11c58495dfebf18763db308f55c75564a52c195 | sight.py | sight.py | #!/usr/bin/env python
import ephem
from sr_lib import altazimuth, almanac, ha, ho
datelist = ['2016/01/12 18:00:00', '2016/01/12 19:00:00',
'2016/01/12 20:00:00', '2016/01/12 21:00:00']
jackson = ephem.Observer()
jackson.lat = '42.2458'
jackson.lon = '-84.4014'
jackson.pressure = 0
jackson.elevation = 303.9 # meters = 997 feet. Doesn't affect sun much.
ap = jackson.copy()
ap.lat = '42'
ap.lon = '-84'
for p in [jackson, ap]:
p.date = datelist[1]
s = ephem.Sun(p)
al = almanac(p.date)
aa = altazimuth(al['gha'], al['dec'], p.lon, p.lat)
print "PyEphem Hc ", s.alt, " Z", s.az
print " almanac and altazimuth:", aa
hs_1 = ephem.degrees('26')
print "hs", hs_1
ha_1 = ha(hs_1, ephem.degrees('0:1.2'), 'on', 15)
print "ha", ha_1
ho_1 = ho(ha_1, ephem.Date(datelist[0]), 'LL')
print "ho", ho_1
| #!/usr/bin/env python
import ephem
from sr_lib import altazimuth, almanac, ha, ho
datelist = ['2016/01/12 18:00:00', '2016/01/12 19:00:00',
'2016/01/12 20:00:00', '2016/01/12 21:00:00']
jackson = ephem.Observer()
jackson.lat = '42.2458'
jackson.lon = '-84.4014'
jackson.pressure = 0
jackson.elevation = 303.9 # meters = 997 feet. Doesn't affect sun much.
ap = jackson.copy()
ap.lat = '42'
ap.lon = '-84'
for p in [jackson, ap]:
p.date = datelist[0]
s = ephem.Sun(p)
print "Hc", s.alt, "Z", s.az
hs_1 = ephem.degrees('26')
print "hs", hs_1
ha_1 = ha(hs_1, ephem.degrees('0:1.2'), 'on', 15)
print "ha", ha_1
ho_1 = ho(ha_1, ephem.Date(datelist[0]), 'LL')
print "ho", ho_1
| Stop use of almanac() and altazimuth() functions for now. | Stop use of almanac() and altazimuth() functions for now.
| Python | mit | zimolzak/Sight-reduction-problems | ---
+++
@@ -17,12 +17,9 @@
ap.lon = '-84'
for p in [jackson, ap]:
- p.date = datelist[1]
+ p.date = datelist[0]
s = ephem.Sun(p)
- al = almanac(p.date)
- aa = altazimuth(al['gha'], al['dec'], p.lon, p.lat)
- print "PyEphem Hc ", s.alt, " Z", s.az
- print " almanac and altazimuth:", aa
+ print "Hc", s.alt, "Z", s.az
hs_1 = ephem.degrees('26')
print "hs", hs_1 |
dd59a1bd6ac56fc6a8bfb8de25776000dfe39af7 | tracker/management/commands/approval_reminders.py | tracker/management/commands/approval_reminders.py | '''
Simple module to aid in command-line debugging of notification related issues.
'''
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.core.mail import EmailMessage
from timetracker.overtime.models import PendingApproval, Tbluser
def send_approval_digest(market):
approvals = PendingApproval.objects.filter(closed=False, approver__market=market)
if not len(approvals):
return
if len({entry.approver for entry in approvals}) > 1:
error_log.critical(
"Cannot send e-mails as a clear approval chain cannot be established."
)
return
message = "Hi,\n\n" \
"You have %d approvals pending in the timetracker." \
"\n\n" \
"Kind Regards,\n" \
"Timetracker team"
message = message % len(approvals)
email = EmailMessage(from_email='timetracker@unmonitored.com')
email.body = message
email.to = ["aaron.france@hp.com"] #approvals[0].user.get_manager_email()
email.subject = "Pending Approvals in the Timetracker."
email.send()
class Command(BaseCommand):
def handle(self, *args, **options):
for market in Tbluser.MARKET_CHOICES:
if settings.SENDING_APPROVAL_DIGESTS.get(market[0]):
send_approval_digest(market[0])
| '''
Simple module to aid in command-line debugging of notification related issues.
'''
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.core.mail import EmailMessage
from timetracker.overtime.models import PendingApproval, Tbluser
def send_approval_digest(market):
approvals = PendingApproval.objects.filter(closed=False, approver__market=market)
if not len(approvals):
return
if len({entry.approver for entry in approvals}) > 1:
error_log.critical(
"Cannot send e-mails as a clear approval chain cannot be established."
)
return
message = "Hi,\n\n" \
"You have %d approvals pending in the timetracker." \
"\n\n" \
"Kind Regards,\n" \
"Timetracker team"
message = message % len(approvals)
email = EmailMessage(from_email='timetracker@unmonitored.com')
email.body = message
email.to = approvals[0].entry.user.get_manager_email()
email.subject = "Pending Approvals in the Timetracker."
email.send()
class Command(BaseCommand):
def handle(self, *args, **options):
for market in Tbluser.MARKET_CHOICES:
if settings.SENDING_APPROVAL_DIGESTS.get(market[0]):
send_approval_digest(market[0])
| Remove me from the debug e-mail recipient. | Remove me from the debug e-mail recipient.
| Python | bsd-3-clause | AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker | ---
+++
@@ -28,7 +28,7 @@
email = EmailMessage(from_email='timetracker@unmonitored.com')
email.body = message
- email.to = ["aaron.france@hp.com"] #approvals[0].user.get_manager_email()
+ email.to = approvals[0].entry.user.get_manager_email()
email.subject = "Pending Approvals in the Timetracker."
email.send()
|
83718336f5260e94cea32611fd7080966329ee2b | prompt_toolkit/filters/utils.py | prompt_toolkit/filters/utils.py | from __future__ import unicode_literals
from .base import Always, Never
from .types import SimpleFilter, CLIFilter
__all__ = (
'to_cli_filter',
'to_simple_filter',
)
def to_simple_filter(bool_or_filter):
"""
Accept both booleans and CLIFilters as input and
turn it into a SimpleFilter.
"""
assert isinstance(bool_or_filter, (bool, SimpleFilter)), \
TypeError('Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter)
return {
True: Always(),
False: Never()
}.get(bool_or_filter, bool_or_filter)
def to_cli_filter(bool_or_filter):
"""
Accept both booleans and CLIFilters as input and
turn it into a CLIFilter.
"""
assert isinstance(bool_or_filter, (bool, CLIFilter)), \
TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter)
return {
True: Always(),
False: Never()
}.get(bool_or_filter, bool_or_filter)
| from __future__ import unicode_literals
from .base import Always, Never
from .types import SimpleFilter, CLIFilter
__all__ = (
'to_cli_filter',
'to_simple_filter',
)
_always = Always()
_never = Never()
def to_simple_filter(bool_or_filter):
"""
Accept both booleans and CLIFilters as input and
turn it into a SimpleFilter.
"""
assert isinstance(bool_or_filter, (bool, SimpleFilter)), \
TypeError('Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter)
return {
True: _always,
False: _never,
}.get(bool_or_filter, bool_or_filter)
def to_cli_filter(bool_or_filter):
"""
Accept both booleans and CLIFilters as input and
turn it into a CLIFilter.
"""
assert isinstance(bool_or_filter, (bool, CLIFilter)), \
TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter)
return {
True: _always,
False: _never,
}.get(bool_or_filter, bool_or_filter)
| Reduce amount of Always/Never instances. (The are stateless.) | Reduce amount of Always/Never instances. (The are stateless.)
| Python | bsd-3-clause | melund/python-prompt-toolkit,jonathanslenders/python-prompt-toolkit,niklasf/python-prompt-toolkit | ---
+++
@@ -6,6 +6,9 @@
'to_cli_filter',
'to_simple_filter',
)
+
+_always = Always()
+_never = Never()
def to_simple_filter(bool_or_filter):
@@ -17,8 +20,8 @@
TypeError('Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter)
return {
- True: Always(),
- False: Never()
+ True: _always,
+ False: _never,
}.get(bool_or_filter, bool_or_filter)
@@ -31,6 +34,6 @@
TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter)
return {
- True: Always(),
- False: Never()
+ True: _always,
+ False: _never,
}.get(bool_or_filter, bool_or_filter) |
fe296c62c1a75f89f206a0105591a274a7782b4e | factory/tools/cat_StartdLog.py | factory/tools/cat_StartdLog.py | #!/bin/env python
#
# cat_StartdLog.py
#
# Print out the StartdLog for a glidein output file
#
# Usage: cat_StartdLog.py logname
#
import sys
sys.path.append("lib")
import gWftLogParser
USAGE="Usage: cat_StartdLog.py <logname>"
def main():
try:
print gWftLogParser.get_CondorLog(sys.argv[1],"StartdLog")
except:
sys.stderr.write("%s\n"%USAGE)
sys.exit(1)
if __name__ == '__main__':
main()
| #!/bin/env python
#
# cat_StartdLog.py
#
# Print out the StartdLog for a glidein output file
#
# Usage: cat_StartdLog.py logname
#
import sys
STARTUP_DIR=sys.path[0]
sys.path.append(os.path.join(STARTUP_DIR,"lib"))
import gWftLogParser
USAGE="Usage: cat_StartdLog.py <logname>"
def main():
try:
print gWftLogParser.get_CondorLog(sys.argv[1],"StartdLog")
except:
sys.stderr.write("%s\n"%USAGE)
sys.exit(1)
if __name__ == '__main__':
main()
| Allow for startup in a differend dir | Allow for startup in a differend dir
| Python | bsd-3-clause | holzman/glideinwms-old,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS | ---
+++
@@ -8,7 +8,8 @@
#
import sys
-sys.path.append("lib")
+STARTUP_DIR=sys.path[0]
+sys.path.append(os.path.join(STARTUP_DIR,"lib"))
import gWftLogParser
USAGE="Usage: cat_StartdLog.py <logname>" |
25a916a176affb396a403ab72031208df44735ed | feder/questionaries/filters.py | feder/questionaries/filters.py | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
import django_filters
from .models import Questionary
from atom.filters import CrispyFilterMixin, AutocompleteChoiceFilter
class QuestionaryFilter(CrispyFilterMixin, django_filters.FilterSet):
title = django_filters.CharFilter(lookup_type='icontains', label=_("Name"))
monitoring = AutocompleteChoiceFilter('MonitoringAutocomplete', label=_("Monitoring"))
created = django_filters.DateRangeFilter(label=_("Creation date"))
form_class = None
def __init__(self, user, *args, **kwargs):
self.user = user
super(QuestionaryFilter, self).__init__(*args, **kwargs)
if not self.user.is_superuser:
del self.fields['lock']
class Meta:
model = Questionary
fields = ['title', 'monitoring', 'created', 'lock']
order_by = ['created', ]
| # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
import django_filters
from .models import Questionary
from atom.filters import CrispyFilterMixin, AutocompleteChoiceFilter
class QuestionaryFilter(CrispyFilterMixin, django_filters.FilterSet):
title = django_filters.CharFilter(lookup_type='icontains', label=_("Name"))
monitoring = AutocompleteChoiceFilter('MonitoringAutocomplete', label=_("Monitoring"))
created = django_filters.DateRangeFilter(label=_("Creation date"))
form_class = None
def __init__(self, user, *args, **kwargs):
self.user = user
super(QuestionaryFilter, self).__init__(*args, **kwargs)
if not self.user.is_superuser:
del self.filters['lock']
class Meta:
model = Questionary
fields = ['title', 'monitoring', 'created', 'lock']
order_by = ['created', ]
| Fix lock filter in questionaries | Fix lock filter in questionaries
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder | ---
+++
@@ -15,7 +15,7 @@
self.user = user
super(QuestionaryFilter, self).__init__(*args, **kwargs)
if not self.user.is_superuser:
- del self.fields['lock']
+ del self.filters['lock']
class Meta:
model = Questionary |
22c9fb018ad1a0dca26f6e9c9bc0cc871c8dec25 | cfscrape.py | cfscrape.py | import re
import requests
import lxml.html
def grab_cloudflare(url, *args, **kwargs):
sess = requests.Session()
sess.headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0"}
safe_eval = lambda s: eval(s, {"__builtins__": {}}) if "#" not in s and "__" not in s else ""
page = sess.get(url, *args, **kwargs).content
if "a = document.getElementById('jschl-answer');" in page:
# Cloudflare anti-bots is on
html = lxml.html.fromstring(page)
challenge = html.find(".//input[@name='jschl_vc']").attrib["value"]
script = html.findall(".//script")[-1].text_content()
domain_parts = url.split("/")
domain = domain_parts[2]
math = re.search(r"a\.value = (\d.+?);", script).group(1)
answer = str(safe_eval(math) + len(domain))
data = {"jschl_vc": challenge, "jschl_answer": answer}
get_url = domain_parts[0] + '//' + domain + "/cdn-cgi/l/chk_jschl"
return sess.get(get_url, params=data, headers={"Referer": url}, *args, **kwargs).content
else:
return page
| import re
import requests
import lxml.html
def grab_cloudflare(url, *args, **kwargs):
sess = requests.session()
sess.headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0"}
safe_eval = lambda s: eval(s, {"__builtins__": {}}) if "#" not in s and "__" not in s else ""
page = sess.get(url, *args, **kwargs).content
if "a = document.getElementById('jschl-answer');" in page:
# Cloudflare anti-bots is on
html = lxml.html.fromstring(page)
challenge = html.find(".//input[@name='jschl_vc']").attrib["value"]
script = html.findall(".//script")[-1].text_content()
domain_parts = url.split("/")
domain = domain_parts[2]
math = re.search(r"a\.value = (\d.+?);", script).group(1)
answer = str(safe_eval(math) + len(domain))
data = {"jschl_vc": challenge, "jschl_answer": answer}
get_url = domain_parts[0] + '//' + domain + "/cdn-cgi/l/chk_jschl"
return sess.get(get_url, params=data, headers={"Referer": url}, *args, **kwargs).content
else:
return page
| Use requests.session instead of requests.Session | Use requests.session instead of requests.Session | Python | mit | AtVirus/cloudflare-scrape,Thor77/cloudflare-scrape,Muhammad-Farghaly/cloudflare-scrape,Anorov/cloudflare-scrape,nico202/cloudflare-scrape | ---
+++
@@ -4,7 +4,7 @@
def grab_cloudflare(url, *args, **kwargs):
- sess = requests.Session()
+ sess = requests.session()
sess.headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0"}
safe_eval = lambda s: eval(s, {"__builtins__": {}}) if "#" not in s and "__" not in s else ""
page = sess.get(url, *args, **kwargs).content |
3ac41e8b32aff3cf28590c8ab1a7abeae2b563f5 | shipper/helpers.py | shipper/helpers.py | # -*- coding: utf-8 -*-
import getpass
import random
class RandomSeed(object):
"""Creates a context with a temporarily used seed for the random
library. The state for the random functions is not modified
outside this context. Example usage::
with RandomSeed('reproducible seed'):
values = random.sample(range(1000), 10)
It is unclear whether the state is modified outside the current
thread as well. Use with caution when multithreading.
:param seed: the seed to use in the context
"""
def __init__(self, seed):
self.__seed = seed
def __enter__(self):
self.__original_state = random.getstate()
random.seed(self.__seed)
# don't store the seed longer than we need to
del self.__seed
def __exit__(self, type, value, traceback):
random.setstate(self.__original_state)
def prompt_password(confirm=False):
while True:
password = getpass.getpass('Password: ')
if not confirm or getpass.getpass('Confirmation: ') == password:
return password
print('Confirmation did not match the password')
| # -*- coding: utf-8 -*-
import getpass
import random
import click
class RandomSeed(object):
"""Creates a context with a temporarily used seed for the random
library. The state for the random functions is not modified
outside this context. Example usage::
with RandomSeed('reproducible seed'):
values = random.sample(range(1000), 10)
It is unclear whether the state is modified outside the current
thread as well. Use with caution when multithreading.
:param seed: the seed to use in the context
"""
def __init__(self, seed):
self.__seed = seed
def __enter__(self):
self.__original_state = random.getstate()
random.seed(self.__seed)
# don't store the seed longer than we need to
del self.__seed
def __exit__(self, type, value, traceback):
random.setstate(self.__original_state)
def prompt_password(confirm=False):
while True:
password = getpass.getpass('Password: ')
if not confirm or getpass.getpass('Confirmation: ') == password:
return password
click.secho('Confirmation did not match password. Try again.',
err=True, fg='red')
| Fix bug where print would be sent to stdout | Fix bug where print would be sent to stdout
| Python | mit | redodo/shipper | ---
+++
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
import getpass
import random
+
+import click
class RandomSeed(object):
@@ -34,4 +36,5 @@
password = getpass.getpass('Password: ')
if not confirm or getpass.getpass('Confirmation: ') == password:
return password
- print('Confirmation did not match the password')
+ click.secho('Confirmation did not match password. Try again.',
+ err=True, fg='red') |
73d09dfe48a4dd72080fe86e027663df6caf513a | tests/__init__.py | tests/__init__.py | #!/usr/bin/env python2
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import unittest
import os.path
if __name__ == '__main__':
print "Running"
suite = unittest.TestLoader().discover(
start_dir = os.path.dirname(os.path.abspath(__file__)),
pattern = "test_*.py",
top_level_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
unittest.TextTestRunner().run(suite)
| #!/usr/bin/env python2
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import unittest
import os.path
if __name__ == '__main__':
print("Running")
suite = unittest.TestLoader().discover(
start_dir = os.path.dirname(os.path.abspath(__file__)),
pattern = "test_*.py",
top_level_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
unittest.TextTestRunner().run(suite)
| Correct syntax for Python3 compatibility | Correct syntax for Python3 compatibility | Python | apache-2.0 | ocadotechnology/wry | ---
+++
@@ -16,7 +16,7 @@
import os.path
if __name__ == '__main__':
- print "Running"
+ print("Running")
suite = unittest.TestLoader().discover(
start_dir = os.path.dirname(os.path.abspath(__file__)),
pattern = "test_*.py", |
7d5207a493877910c4d6282cb8bb05b7a7ef6a13 | sdnip/hop_db.py | sdnip/hop_db.py |
class HopDB(object):
def __init__(self):
super(HopDB, self).__init__()
self.hops = {} # prefix -> hop
self.installed_prefix = []
def add_hop(self, prefix, next_hop):
self.hops.setdefault(prefix, next_hop)
def get_nexthop(self, prefix):
self.hops.get(prefix)
def is_prefix_installed(self, prefix):
return (prefix in self.installed_prefix)
def get_uninstalled_prefix_list(self):
result = [prefix for prefix in
self.hops.keys() if (prefix not in self.installed_prefix)]
return result
def install_prefix(self, prefix):
self.installed_prefix.append(prefix)
def get_all_prefixes(self):
return hops.keys()
|
class HopDB(object):
def __init__(self):
super(HopDB, self).__init__()
self.hops = {} # prefix -> hop
self.installed_prefix = []
def add_hop(self, prefix, next_hop):
self.hops.setdefault(prefix, next_hop)
def get_nexthop(self, prefix):
self.hops.get(prefix)
def is_prefix_installed(self, prefix):
return (prefix in self.installed_prefix)
def get_uninstalled_prefix_list(self):
result = [prefix for prefix in
self.hops.keys() if (prefix not in self.installed_prefix)]
return result
def install_prefix(self, prefix):
self.installed_prefix.append(prefix)
def get_all_prefixes(self):
return self.hops.keys()
| Fix missing ref from hop db | Fix missing ref from hop db
| Python | mit | sdnds-tw/Ryu-SDN-IP | ---
+++
@@ -24,4 +24,4 @@
self.installed_prefix.append(prefix)
def get_all_prefixes(self):
- return hops.keys()
+ return self.hops.keys() |
7b02aa6560fae3f36374f58c0b355381070047ec | tests/conftest.py | tests/conftest.py | # -*- coding: utf-8 -*-
from collections import namedtuple
from pytest import fixture
from flask import Flask, g
from flask_sqlalchemy import SQLAlchemy
from flask_perm import Perm
from flask_perm.core import db
@fixture
def app(request):
flask_app = Flask(__name__)
flask_app.config['TESTING'] = True
flask_app.config['DEBUG'] = True
flask_app.config['SERVER_NAME'] = 'localhost'
ctx = flask_app.app_context()
ctx.push()
request.addfinalizer(ctx.pop)
return flask_app
class User(namedtuple('User', 'id nickname')):
pass
@fixture
def perm(app, request):
def user_loader(id):
return User(id=id, nickname='User%d'%id)
def current_user_loader():
return user_loader(1)
def users_loader():
return [user_loader(id) for id in range(20)]
app.config['PERM_CURRENT_USER_ACCESS_VALIDATOR'] = lambda user: True
app.config['PERM_URL_PREFIX'] = '/perm'
perm = Perm()
perm.app = app
perm.init_app(app)
perm.user_loader(user_loader)
perm.current_user_loader(current_user_loader)
perm.users_loader(users_loader)
db.create_all()
return perm
| # -*- coding: utf-8 -*-
from collections import namedtuple
from pytest import fixture
from flask import Flask, g
from flask_sqlalchemy import SQLAlchemy
from flask_perm import Perm
from flask_perm.core import db
@fixture
def app(request):
flask_app = Flask(__name__)
flask_app.config['TESTING'] = True
flask_app.config['DEBUG'] = True
flask_app.config['SERVER_NAME'] = 'localhost'
ctx = flask_app.app_context()
ctx.push()
request.addfinalizer(ctx.pop)
return flask_app
class User(namedtuple('User', 'id nickname')):
pass
@fixture
def perm(app, request):
def user_loader(id):
return User(id=id, nickname='User%d'%id)
def current_user_loader():
return user_loader(1)
def users_loader(**kwargs):
return [user_loader(id) for id in range(20)]
app.config['PERM_URL_PREFIX'] = '/perm'
app.config['PERM_ADMIN_USERNAME'] = 'admin'
app.config['PERM_ADMIN_PASSWORD'] = 'test'
perm = Perm()
perm.app = app
perm.init_app(app)
perm.user_loader(user_loader)
perm.current_user_loader(current_user_loader)
perm.users_loader(users_loader)
db.create_all()
return perm
| Configure test admin username and password. | Configure test admin username and password.
| Python | mit | soasme/flask-perm,soasme/flask-perm,soasme/flask-perm | ---
+++
@@ -30,11 +30,12 @@
def current_user_loader():
return user_loader(1)
- def users_loader():
+ def users_loader(**kwargs):
return [user_loader(id) for id in range(20)]
- app.config['PERM_CURRENT_USER_ACCESS_VALIDATOR'] = lambda user: True
app.config['PERM_URL_PREFIX'] = '/perm'
+ app.config['PERM_ADMIN_USERNAME'] = 'admin'
+ app.config['PERM_ADMIN_PASSWORD'] = 'test'
perm = Perm()
perm.app = app |
b494a5b2ed94c1def6fb8bbbab5df5612ef30aa7 | tests/test_api.py | tests/test_api.py | from bmi_tester.api import check_bmi
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
fp.write("input.yaml")
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
| import os
from bmi_tester.api import check_bmi
def touch_file(fname):
with open(fname, "w"):
pass
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
fp.write(os.linesep.join(["input.yaml", "data.dat"]))
touch_file("input.yaml")
touch_file("data.dat")
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
| Test a manifest with multiple files. | Test a manifest with multiple files.
| Python | mit | csdms/bmi-tester | ---
+++
@@ -1,10 +1,16 @@
+import os
+
from bmi_tester.api import check_bmi
+
+
+def touch_file(fname):
+ with open(fname, "w"):
+ pass
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
- with open("input.yaml", "w"):
- pass
+ touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
@@ -15,8 +21,7 @@
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
- with open("input.yaml", "w"):
- pass
+ touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
@@ -31,9 +36,9 @@
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
- fp.write("input.yaml")
- with open("input.yaml", "w"):
- pass
+ fp.write(os.linesep.join(["input.yaml", "data.dat"]))
+ touch_file("input.yaml")
+ touch_file("data.dat")
assert (
check_bmi(
"bmi_tester.bmi:Bmi", |
524eb80f426a3a4530fe7ce5940eb0ef619b5396 | alerta/app/shell.py | alerta/app/shell.py |
import argparse
from alerta.app import app
from alerta.app import db
from alerta.version import __version__
LOG = app.logger
def main():
parser = argparse.ArgumentParser(
prog='alertad',
description='Alerta server (for development purposes only)',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
'-H',
'--host',
type=str,
default='0.0.0.0',
help='Bind host'
)
parser.add_argument(
'-P',
'--port',
type=int,
default=8080,
help='Listen port'
)
parser.add_argument(
'--debug',
action='store_true',
default=False,
help='Debug output'
)
args = parser.parse_args()
LOG.info('Starting alerta version %s ...', __version__)
app.run(host=args.host, port=args.port, debug=args.debug, threaded=True)
|
import argparse
from alerta.app import app
from alerta.app import db
from alerta.version import __version__
LOG = app.logger
def main():
parser = argparse.ArgumentParser(
prog='alertad',
description='Alerta server (for development purposes only)',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
'-H',
'--host',
type=str,
default='0.0.0.0',
help='Bind host'
)
parser.add_argument(
'-P',
'--port',
type=int,
default=8080,
help='Listen port'
)
parser.add_argument(
'--debug',
action='store_true',
default=False,
help='Debug output'
)
args = parser.parse_args()
LOG.info('Starting alerta version %s ...', __version__)
app.run(host=args.host, port=args.port, debug=args.debug, threaded=True, use_reloader=False)
| Disable auto-reloader in debug mode | Disable auto-reloader in debug mode
This was causing issues with plugin initialisation happening twice
and was getting rate limited by Telegram Bot API.
| Python | apache-2.0 | guardian/alerta,guardian/alerta,guardian/alerta,skob/alerta,skob/alerta,guardian/alerta,skob/alerta,skob/alerta | ---
+++
@@ -37,4 +37,4 @@
args = parser.parse_args()
LOG.info('Starting alerta version %s ...', __version__)
- app.run(host=args.host, port=args.port, debug=args.debug, threaded=True)
+ app.run(host=args.host, port=args.port, debug=args.debug, threaded=True, use_reloader=False) |
de84be15c4c519a680121e15c26d6eed6d091cd2 | toolbox/models.py | toolbox/models.py | from keras.layers import Conv2D
from keras.models import Sequential
from toolbox.metrics import psnr
def compile_srcnn(input_shape, c=1, f1=9, f2=1, f3=5, n1=64, n2=32):
"""Compile an SRCNN model.
See https://arxiv.org/abs/1501.00092.
"""
model = Sequential()
model.add(Conv2D(nb_filter=n1, nb_row=f1, nb_col=f1, init='he_normal',
activation='relu', input_shape=input_shape))
model.add(Conv2D(nb_filter=n2, nb_row=f2, nb_col=f2, init='he_normal',
activation='relu'))
model.add(Conv2D(nb_filter=c, nb_row=f3, nb_col=f3, init='he_normal'))
model.compile(optimizer='adam', loss='mse', metrics=[psnr])
return model
| from keras.layers import Conv2D
from keras.models import Sequential
from toolbox.metrics import psnr
def compile_srcnn(input_shape, c=1, f1=9, f2=1, f3=5, n1=64, n2=32):
"""Compile an SRCNN model.
See https://arxiv.org/abs/1501.00092.
"""
model = Sequential()
model.add(Conv2D(n1, f1, kernel_initializer='he_normal',
activation='relu', input_shape=input_shape))
model.add(Conv2D(n2, f2, kernel_initializer='he_normal',
activation='relu'))
model.add(Conv2D(c, f3, kernel_initializer='he_normal'))
model.compile(optimizer='adam', loss='mse', metrics=[psnr])
return model
| Upgrade to Keras 2 API | Upgrade to Keras 2 API
| Python | mit | qobilidop/srcnn,qobilidop/srcnn | ---
+++
@@ -10,10 +10,10 @@
See https://arxiv.org/abs/1501.00092.
"""
model = Sequential()
- model.add(Conv2D(nb_filter=n1, nb_row=f1, nb_col=f1, init='he_normal',
+ model.add(Conv2D(n1, f1, kernel_initializer='he_normal',
activation='relu', input_shape=input_shape))
- model.add(Conv2D(nb_filter=n2, nb_row=f2, nb_col=f2, init='he_normal',
+ model.add(Conv2D(n2, f2, kernel_initializer='he_normal',
activation='relu'))
- model.add(Conv2D(nb_filter=c, nb_row=f3, nb_col=f3, init='he_normal'))
+ model.add(Conv2D(c, f3, kernel_initializer='he_normal'))
model.compile(optimizer='adam', loss='mse', metrics=[psnr])
return model |
d2a0c23766cfd80f32b406503f47a5c5355bf6db | test_module_b/test_feat_3.py | test_module_b/test_feat_3.py | import unittest
import time
class TestE(unittest.TestCase):
def test_many_lines(self):
for i in xrange(100):
print 'Many lines', i
def test_feat_1_case_1(self):
time.sleep(0.5)
def test_feat_1_case_2(self):
time.sleep(0.5)
def test_feat_1_case_3(self):
time.sleep(0.5)
def test_feat_1_case_4(self):
for i in xrange(10):
time.sleep(0.1)
print 'Few lines %d' % i
| import unittest
import time
class TestE(unittest.TestCase):
def test_many_lines(self):
for i in xrange(100):
print 'Many lines', i
def test_feat_1_case_1(self):
time.sleep(0.5)
self.fail('Artificial fail one')
def test_feat_1_case_2(self):
time.sleep(0.5)
self.fail('Artificial fail two')
def test_feat_1_case_3(self):
time.sleep(0.5)
def test_feat_1_case_4(self):
for i in xrange(10):
time.sleep(0.1)
print 'Few lines %d' % i
| Make some slow tests fail | Make some slow tests fail
| Python | mit | martinsmid/pytest-ui | ---
+++
@@ -8,9 +8,11 @@
def test_feat_1_case_1(self):
time.sleep(0.5)
+ self.fail('Artificial fail one')
def test_feat_1_case_2(self):
time.sleep(0.5)
+ self.fail('Artificial fail two')
def test_feat_1_case_3(self):
time.sleep(0.5) |
5f41a6c748acee486cf157b7373c8d4c1efa2e4d | selenic/__init__.py | selenic/__init__.py | from distutils.version import StrictVersion
from selenium.webdriver.common.action_chains import ActionChains
import selenium
from .config import *
sel_ver = StrictVersion(selenium.__version__)
v2_37_2 = StrictVersion("2.37.2")
if sel_ver > v2_37_2:
raise Exception("please ascertain whether the ActionChains.send_keys "
"patch is required for Selenium version: " +
selenium.__version__)
if sel_ver >= StrictVersion("2.35.0") and sel_ver <= v2_37_2:
# Work around bug
def send_keys(self, *keys_to_send):
"""
Sends keys to current focused element.
:Args:
- keys_to_send: The keys to send.
"""
self.key_down(keys_to_send)
return self
ActionChains.send_keys = send_keys
| from distutils.version import StrictVersion
from selenium.webdriver.common.action_chains import ActionChains
import selenium
# To rexport here.
from .config import *
sel_ver = StrictVersion(selenium.__version__)
v2_35_0 = StrictVersion("2.35.0")
if sel_ver < v2_35_0:
raise Exception("please ascertain whether the ActionChains.send_keys "
"patch is required for Selenium version: " +
selenium.__version__)
if sel_ver >= v2_35_0 and sel_ver <= StrictVersion("2.37.2"):
# Work around bug
def send_keys(self, *keys_to_send):
"""
Sends keys to current focused element.
:Args:
- keys_to_send: The keys to send.
"""
self.key_down(keys_to_send)
return self
ActionChains.send_keys = send_keys
| Update for newer selenium version. | Update for newer selenium version.
| Python | mpl-2.0 | mangalam-research/selenic | ---
+++
@@ -3,17 +3,18 @@
from selenium.webdriver.common.action_chains import ActionChains
import selenium
+# To rexport here.
from .config import *
sel_ver = StrictVersion(selenium.__version__)
-v2_37_2 = StrictVersion("2.37.2")
+v2_35_0 = StrictVersion("2.35.0")
-if sel_ver > v2_37_2:
+if sel_ver < v2_35_0:
raise Exception("please ascertain whether the ActionChains.send_keys "
"patch is required for Selenium version: " +
selenium.__version__)
-if sel_ver >= StrictVersion("2.35.0") and sel_ver <= v2_37_2:
+if sel_ver >= v2_35_0 and sel_ver <= StrictVersion("2.37.2"):
# Work around bug
def send_keys(self, *keys_to_send):
""" |
ca756bc34a0f24c457f2adc6f4b0b78744f0be40 | urls.py | urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.conf import settings
from django.views.generic import TemplateView
urlpatterns = patterns('vortaro.views',
url(r'^informo$', 'about', name="about"),
url(r'^informo/api$', 'about_the_api', name="about_the_api"),
url(ur'^serĉo$', 'search_word', name="search_word"),
url(r'^vorto/(?P<word>.*)$', 'view_word', name="view_word"),
url(u'^$', 'index', name="index"),
)
urlpatterns += patterns('api.views',
url(u'^api/v1/vorto/(?P<word>.+)$', 'view_word', name="api_view_word"),
# We're deliberately using a non-UTF8 URL prefix to hopefully make it easier
# to use the API.
url(u'^api/v1/trovi/(?P<search_term>.+)$', 'search_word', name="api_search_word"),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^404$', TemplateView.as_view(template_name='404.html')),
)
| # -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from django.conf import settings
from django.views.generic import TemplateView
urlpatterns = patterns('vortaro.views',
url(r'^informo$', 'about', name="about"),
url(r'^informo/api$', 'about_the_api', name="about_the_api"),
url(ur'^serĉo$', 'search_word', name="search_word"),
url(r'^vorto/(?P<word>.*)$', 'view_word', name="view_word"),
url(u'^$', 'index', name="index"),
)
urlpatterns += patterns('api.views',
url(u'^api/v1/vorto/(?P<word>.+)$', 'view_word', name="api_view_word"),
# We're deliberately using a non-UTF8 URL prefix to hopefully make it easier
# to use the API.
url(u'^api/v1/trovi/(?P<search_term>.+)$', 'search_word', name="api_search_word"),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^404$', TemplateView.as_view(template_name='404.html')),
url(r'^500$', TemplateView.as_view(template_name='500.html')),
)
| Allow viewing the 500 page during dev. | Allow viewing the 500 page during dev.
| Python | agpl-3.0 | Wilfred/simpla-vortaro,Wilfred/simpla-vortaro | ---
+++
@@ -21,4 +21,5 @@
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^404$', TemplateView.as_view(template_name='404.html')),
+ url(r'^500$', TemplateView.as_view(template_name='500.html')),
) |
fcee154a123c7f9db81c92efce6d4a425dc0a3b1 | src/sentry/models/savedsearch.py | src/sentry/models/savedsearch.py | from __future__ import absolute_import, print_function
from django.db import models
from django.utils import timezone
from sentry.db.models import FlexibleForeignKey, Model, sane_repr
class SavedSearch(Model):
"""
A saved search query.
"""
__core__ = True
project = FlexibleForeignKey('sentry.Project')
name = models.CharField(max_length=128)
query = models.TextField()
date_added = models.DateTimeField(default=timezone.now)
is_default = models.BooleanField(default=False)
class Meta:
app_label = 'sentry'
db_table = 'sentry_savedsearch'
unique_together = (('project', 'name'),)
__repr__ = sane_repr('project_id', 'name')
class SavedSearchUserDefault(Model):
"""
Indicates the default saved search for a given user
"""
savedsearch = FlexibleForeignKey('sentry.SavedSearch')
project = FlexibleForeignKey('sentry.Project')
user = FlexibleForeignKey('sentry.User')
class Meta:
unique_together = (('project', 'user'),)
app_label = 'sentry'
db_table = 'sentry_savedsearch_userdefault'
| from __future__ import absolute_import, print_function
from django.db import models
from django.utils import timezone
from sentry.db.models import FlexibleForeignKey, Model, sane_repr
class SavedSearch(Model):
"""
A saved search query.
"""
__core__ = True
project = FlexibleForeignKey('sentry.Project')
name = models.CharField(max_length=128)
query = models.TextField()
date_added = models.DateTimeField(default=timezone.now)
is_default = models.BooleanField(default=False)
class Meta:
app_label = 'sentry'
db_table = 'sentry_savedsearch'
unique_together = (('project', 'name'),)
__repr__ = sane_repr('project_id', 'name')
class SavedSearchUserDefault(Model):
"""
Indicates the default saved search for a given user
"""
__core__ = True
savedsearch = FlexibleForeignKey('sentry.SavedSearch')
project = FlexibleForeignKey('sentry.Project')
user = FlexibleForeignKey('sentry.User')
class Meta:
unique_together = (('project', 'user'),)
app_label = 'sentry'
db_table = 'sentry_savedsearch_userdefault'
| Add SavedSarch to project defaults | Add SavedSarch to project defaults
| Python | bsd-3-clause | mvaled/sentry,jean/sentry,mvaled/sentry,nicholasserra/sentry,BuildingLink/sentry,gencer/sentry,JackDanger/sentry,beeftornado/sentry,mvaled/sentry,zenefits/sentry,nicholasserra/sentry,daevaorn/sentry,gencer/sentry,beeftornado/sentry,fotinakis/sentry,JamesMura/sentry,JackDanger/sentry,fotinakis/sentry,looker/sentry,JackDanger/sentry,mvaled/sentry,gencer/sentry,gencer/sentry,JamesMura/sentry,ifduyue/sentry,alexm92/sentry,looker/sentry,jean/sentry,mitsuhiko/sentry,alexm92/sentry,ifduyue/sentry,mvaled/sentry,looker/sentry,BuildingLink/sentry,daevaorn/sentry,zenefits/sentry,mvaled/sentry,jean/sentry,beeftornado/sentry,BuildingLink/sentry,JamesMura/sentry,ifduyue/sentry,daevaorn/sentry,jean/sentry,JamesMura/sentry,ifduyue/sentry,BuildingLink/sentry,daevaorn/sentry,fotinakis/sentry,nicholasserra/sentry,zenefits/sentry,JamesMura/sentry,BuildingLink/sentry,gencer/sentry,mitsuhiko/sentry,looker/sentry,ifduyue/sentry,zenefits/sentry,looker/sentry,jean/sentry,fotinakis/sentry,zenefits/sentry,alexm92/sentry | ---
+++
@@ -30,6 +30,8 @@
"""
Indicates the default saved search for a given user
"""
+ __core__ = True
+
savedsearch = FlexibleForeignKey('sentry.SavedSearch')
project = FlexibleForeignKey('sentry.Project')
user = FlexibleForeignKey('sentry.User') |
2eb8dfdfdc31c5315546ff7c89cd59f8d6cb4727 | tacker/__init__.py | tacker/__init__.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import gettext
gettext.install('tacker', unicode=1)
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import gettext
import six
if six.PY2:
gettext.install('tacker', unicode=1)
else:
gettext.install('tacker')
| Fix gettext wrong argument error in py34 | Fix gettext wrong argument error in py34
Closes-Bug: #1550202
Change-Id: I468bef7a8c0a9fa93576744e7869dfa5f2569fa0
| Python | apache-2.0 | priya-pp/Tacker,openstack/tacker,zeinsteinz/tacker,trozet/tacker,priya-pp/Tacker,stackforge/tacker,openstack/tacker,trozet/tacker,openstack/tacker,stackforge/tacker,zeinsteinz/tacker | ---
+++
@@ -17,5 +17,9 @@
import gettext
+import six
-gettext.install('tacker', unicode=1)
+if six.PY2:
+ gettext.install('tacker', unicode=1)
+else:
+ gettext.install('tacker') |
f79b8834ff88b9f4517d464407240f2bce6c7f5a | tests/test_parse.py | tests/test_parse.py | from hypothesis_auto import auto_pytest_magic
from isort import parse
from isort.settings import Config
TEST_CONTENTS = """
import xyz
import abc
def function():
pass
"""
def test_file_contents():
(
in_lines,
out_lines,
import_index,
place_imports,
import_placements,
as_map,
imports,
categorized_comments,
first_comment_index_start,
first_comment_index_end,
change_count,
original_line_count,
line_separator,
sections,
section_comments,
) = parse.file_contents(TEST_CONTENTS, config=Config())
assert "\n".join(in_lines) == TEST_CONTENTS
assert "import" not in "\n".join(out_lines)
assert import_index == 1
assert change_count == -2
assert original_line_count == len(in_lines)
auto_pytest_magic(parse.import_type)
auto_pytest_magic(parse.skip_line)
auto_pytest_magic(parse._strip_syntax)
auto_pytest_magic(parse._infer_line_separator)
| from hypothesis_auto import auto_pytest_magic
from isort import parse
from isort.settings import Config
TEST_CONTENTS = """
import xyz
import abc
def function():
pass
"""
def test_file_contents():
(
in_lines,
out_lines,
import_index,
place_imports,
import_placements,
as_map,
imports,
categorized_comments,
change_count,
original_line_count,
line_separator,
sections,
section_comments,
) = parse.file_contents(TEST_CONTENTS, config=Config())
assert "\n".join(in_lines) == TEST_CONTENTS
assert "import" not in "\n".join(out_lines)
assert import_index == 1
assert change_count == -2
assert original_line_count == len(in_lines)
auto_pytest_magic(parse.import_type)
auto_pytest_magic(parse.skip_line)
auto_pytest_magic(parse._strip_syntax)
auto_pytest_magic(parse._infer_line_separator)
| Fix signature of test case | Fix signature of test case
| Python | mit | PyCQA/isort,PyCQA/isort | ---
+++
@@ -23,8 +23,6 @@
as_map,
imports,
categorized_comments,
- first_comment_index_start,
- first_comment_index_end,
change_count,
original_line_count,
line_separator, |
88746539211d193e0d0f04510c71d64218cc6927 | test/test_users.py | test/test_users.py | import chatexchange
import live_testing
if live_testing.enabled:
def test_user_info():
client = chatexchange.Client('stackexchange.com')
user = client.get_user(-2)
assert user.id == -2
assert not user.is_moderator
assert user.name == "StackExchange"
assert user.room_count >= 18
assert user.message_count >= 129810
assert user.reputation == -1
user = client.get_user(31768)
assert user.id == 31768
assert user.is_moderator
assert user.name == "ManishEarth"
assert user.room_count >= 222
assert user.message_count >= 89093
assert user.reputation > 115000
| import chatexchange
import live_testing
if live_testing.enabled:
def test_user_info():
client = chatexchange.Client('stackexchange.com')
user = client.get_user(-2)
assert user.id == -2
assert not user.is_moderator
assert user.name == "Stack Exchange"
assert user.room_count >= 18
assert user.message_count >= 129810
assert user.reputation == -1
user = client.get_user(31768)
assert user.id == 31768
assert user.is_moderator
assert user.name == "ManishEarth"
assert user.room_count >= 222
assert user.message_count >= 89093
assert user.reputation > 115000
| Update name of user -2 | Update name of user -2
Changed from StackExchange to Stack Exchange
| Python | apache-2.0 | Charcoal-SE/ChatExchange,ByteCommander/ChatExchange6,ByteCommander/ChatExchange6,Charcoal-SE/ChatExchange | ---
+++
@@ -10,7 +10,7 @@
user = client.get_user(-2)
assert user.id == -2
assert not user.is_moderator
- assert user.name == "StackExchange"
+ assert user.name == "Stack Exchange"
assert user.room_count >= 18
assert user.message_count >= 129810
assert user.reputation == -1 |
cca387dc889b12457c1b1d8bb7b61ad3d2bbd57a | tests/test_room.py | tests/test_room.py | import unittest
from classes.room import Room
class RoomClassTest(unittest.TestCase):
pass
# def test_create_room_successfully(self):
# my_class_instance = Room()
# initial_room_count = len(my_class_instance.all_rooms)
# blue_office = my_class_instance.create_room("Blue", "office")
# self.assertTrue(blue_office)
# new_room_count = len(my_class_instance.all_rooms)
# self.assertEqual(new_room_count - initial_room_count, 1)
#
# def test_inputs_are_strings(self):
# # Test raises an error if either input is not a string
# with self.assertRaises(ValueError, msg='Only strings are allowed as input'):
# my_class_instance = Room()
# blue_office = my_class_instance.create_room(1234, "office")
| import unittest
from classes.room import Room
from classes.dojo import Dojo
class RoomClassTest(unittest.TestCase):
def test_add_occupant(self):
my_class_instance = Room("Blue", "office", 6)
my_dojo_instance = Dojo()
new_fellow = my_dojo_instance.add_person("fellow", "Peter", "Musonye", "Y")
initial_persons_count = len(my_class_instance.persons)
new_occupant = my_class_instance.add_occupant(new_fellow)
# self.assertTrue(new_occupant)
new_persons_count = len(my_class_instance.persons)
self.assertEqual(new_persons_count - initial_persons_count, 1)
def test_cannot_add_more_than_max_occupants(self):
my_class_instance = Room("Blue", "office", 4)
my_dojo_instance = Dojo()
fellow_1 = my_dojo_instance.add_person("fellow", "Peter", "Musonye", "Y")
fellow_2 = my_dojo_instance.add_person("staff", "Farhan", "Abdi")
fellow_3 = my_dojo_instance.add_person("fellow", "Rose", "Maina", "Y")
fellow_4 = my_dojo_instance.add_person("fellow", "Dennis", "Kola", "Y")
fellow_5 = my_dojo_instance.add_person("fellow", "Eddy", "Karanja", "Y")
occupant_1 = my_class_instance.add_occupant(fellow_1)
occupant_2 = my_class_instance.add_occupant(fellow_2)
occupant_3 = my_class_instance.add_occupant(fellow_3)
occupant_4 = my_class_instance.add_occupant(fellow_4)
occupant_5 = my_class_instance.add_occupant(fellow_5)
self.assertEqual(occupant_5, "Room is at full capacity")
| Add tests for class Room | Add tests for class Room
| Python | mit | peterpaints/room-allocator | ---
+++
@@ -1,19 +1,30 @@
import unittest
from classes.room import Room
+from classes.dojo import Dojo
class RoomClassTest(unittest.TestCase):
- pass
- # def test_create_room_successfully(self):
- # my_class_instance = Room()
- # initial_room_count = len(my_class_instance.all_rooms)
- # blue_office = my_class_instance.create_room("Blue", "office")
- # self.assertTrue(blue_office)
- # new_room_count = len(my_class_instance.all_rooms)
- # self.assertEqual(new_room_count - initial_room_count, 1)
- #
- # def test_inputs_are_strings(self):
- # # Test raises an error if either input is not a string
- # with self.assertRaises(ValueError, msg='Only strings are allowed as input'):
- # my_class_instance = Room()
- # blue_office = my_class_instance.create_room(1234, "office")
+ def test_add_occupant(self):
+ my_class_instance = Room("Blue", "office", 6)
+ my_dojo_instance = Dojo()
+ new_fellow = my_dojo_instance.add_person("fellow", "Peter", "Musonye", "Y")
+ initial_persons_count = len(my_class_instance.persons)
+ new_occupant = my_class_instance.add_occupant(new_fellow)
+ # self.assertTrue(new_occupant)
+ new_persons_count = len(my_class_instance.persons)
+ self.assertEqual(new_persons_count - initial_persons_count, 1)
+
+ def test_cannot_add_more_than_max_occupants(self):
+ my_class_instance = Room("Blue", "office", 4)
+ my_dojo_instance = Dojo()
+ fellow_1 = my_dojo_instance.add_person("fellow", "Peter", "Musonye", "Y")
+ fellow_2 = my_dojo_instance.add_person("staff", "Farhan", "Abdi")
+ fellow_3 = my_dojo_instance.add_person("fellow", "Rose", "Maina", "Y")
+ fellow_4 = my_dojo_instance.add_person("fellow", "Dennis", "Kola", "Y")
+ fellow_5 = my_dojo_instance.add_person("fellow", "Eddy", "Karanja", "Y")
+ occupant_1 = my_class_instance.add_occupant(fellow_1)
+ occupant_2 = my_class_instance.add_occupant(fellow_2)
+ occupant_3 = my_class_instance.add_occupant(fellow_3)
+ occupant_4 = my_class_instance.add_occupant(fellow_4)
+ occupant_5 = my_class_instance.add_occupant(fellow_5)
+ self.assertEqual(occupant_5, "Room is at full capacity") |
4c765b0765b8c5eb43b5850d9c3877d37d40ed5b | qr_code/urls.py | qr_code/urls.py | from django.urls import path
from qr_code import views
app_name = 'qr_code'
urlpatterns = [
path('images/serve-qr-code-image/', views.serve_qr_code_image, name='serve_qr_code_image')
]
| from django.conf import settings
from django.urls import path
from qr_code import views
app_name = 'qr_code'
urlpatterns = [
path(getattr(settings, 'SERVE_QR_CODE_IMAGE_PATH', 'images/serve-qr-code-image/'), views.serve_qr_code_image, name='serve_qr_code_image')
]
| Introduce setting `SERVE_QR_CODE_IMAGE_PATH` to configure the path under which QR Code images are served. | Introduce setting `SERVE_QR_CODE_IMAGE_PATH` to configure the path under which QR Code images are served.
| Python | bsd-3-clause | dprog-philippe-docourt/django-qr-code,dprog-philippe-docourt/django-qr-code,dprog-philippe-docourt/django-qr-code | ---
+++
@@ -1,3 +1,4 @@
+from django.conf import settings
from django.urls import path
from qr_code import views
@@ -5,5 +6,5 @@
app_name = 'qr_code'
urlpatterns = [
- path('images/serve-qr-code-image/', views.serve_qr_code_image, name='serve_qr_code_image')
+ path(getattr(settings, 'SERVE_QR_CODE_IMAGE_PATH', 'images/serve-qr-code-image/'), views.serve_qr_code_image, name='serve_qr_code_image')
] |
21b8c54d564fb48d9982e8377e0f2a8c0effb96e | rasa/nlu/run.py | rasa/nlu/run.py | import logging
import typing
from typing import Optional, Text
from rasa.shared.utils.cli import print_info, print_success
from rasa.shared.nlu.interpreter import RegexInterpreter
from rasa.shared.constants import INTENT_MESSAGE_PREFIX
from rasa.nlu.model import Interpreter
from rasa.shared.utils.io import json_to_string
import asyncio
if typing.TYPE_CHECKING:
from rasa.nlu.components import ComponentBuilder
logger = logging.getLogger(__name__)
def run_cmdline(
model_path: Text, component_builder: Optional["ComponentBuilder"] = None
) -> None:
interpreter = Interpreter.load(model_path, component_builder)
regex_interpreter = RegexInterpreter()
print_success("NLU model loaded. Type a message and press enter to parse it.")
while True:
print_success("Next message:")
try:
message = input().strip()
except (EOFError, KeyboardInterrupt):
print_info("Wrapping up command line chat...")
break
if message.startswith(INTENT_MESSAGE_PREFIX):
result = asyncio.run(regex_interpreter.parse(message))
else:
result = interpreter.parse(message)
print(json_to_string(result))
| import logging
import typing
from typing import Optional, Text
from rasa.shared.utils.cli import print_info, print_success
from rasa.shared.nlu.interpreter import RegexInterpreter
from rasa.shared.constants import INTENT_MESSAGE_PREFIX
from rasa.nlu.model import Interpreter
from rasa.shared.utils.io import json_to_string
import asyncio
if typing.TYPE_CHECKING:
from rasa.nlu.components import ComponentBuilder
logger = logging.getLogger(__name__)
def run_cmdline(
model_path: Text, component_builder: Optional["ComponentBuilder"] = None
) -> None:
interpreter = Interpreter.load(model_path, component_builder)
regex_interpreter = RegexInterpreter()
print_success("NLU model loaded. Type a message and press enter to parse it.")
while True:
print_success("Next message:")
try:
message = input().strip()
except (EOFError, KeyboardInterrupt):
print_info("Wrapping up command line chat...")
break
if message.startswith(INTENT_MESSAGE_PREFIX):
result = regex_interpreter.synchronous_parse(message)
else:
result = interpreter.parse(message)
print(json_to_string(result))
| Swap parse call for synchronous_parse | Swap parse call for synchronous_parse
| Python | apache-2.0 | RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu | ---
+++
@@ -31,7 +31,7 @@
break
if message.startswith(INTENT_MESSAGE_PREFIX):
- result = asyncio.run(regex_interpreter.parse(message))
+ result = regex_interpreter.synchronous_parse(message)
else:
result = interpreter.parse(message)
|
0785554db32573f3c693ef4d3a6de952a2f841cc | taggittokenfield/views.py | taggittokenfield/views.py | import json
from django.http import HttpResponse
from taggit.models import Tag
def filter_tags(request):
"Returns a JSON formatted list of tags starting with the value of GET variable 'q'."
limiter = request.GET['q']
results = Tag.objects.filter(name__startswith=limiter).values_list('name', flat=True)
data = []
for tag_name in results:
data.append({'id': '"%s"' % tag_name, 'name': tag_name})
return HttpResponse(json.dumps(data), mimetype="application/json") | import json
from django.http import HttpResponse
from taggit.models import Tag
def filter_tags(request):
"Returns a JSON formatted list of tags starting with the value of GET variable 'q'."
limiter = request.GET['q']
results = Tag.objects.filter(name__istartswith=limiter).values_list('name', flat=True)
data = []
for tag_name in results:
data.append({'id': '"%s"' % tag_name, 'name': tag_name})
return HttpResponse(json.dumps(data), mimetype="application/json") | Tag searches should be case-insensitive. | Tag searches should be case-insensitive.
| Python | bsd-3-clause | harrislapiroff/django-taggit-tokenfield,harrislapiroff/django-taggit-tokenfield | ---
+++
@@ -5,7 +5,7 @@
def filter_tags(request):
"Returns a JSON formatted list of tags starting with the value of GET variable 'q'."
limiter = request.GET['q']
- results = Tag.objects.filter(name__startswith=limiter).values_list('name', flat=True)
+ results = Tag.objects.filter(name__istartswith=limiter).values_list('name', flat=True)
data = []
for tag_name in results:
data.append({'id': '"%s"' % tag_name, 'name': tag_name}) |
ebc7aa75d871929220ee0197aaf92a24efc3f9da | PVGeo/__main__.py | PVGeo/__main__.py | import os
import sys
import platform
def GetInstallationPaths():
path = os.path.dirname(os.path.dirname(__file__))
PYTHONPATH = path
PV_PLUGIN_PATH = '%s/%s' % (path, 'PVPlugins')
script = 'curl -s https://cdn.rawgit.com/OpenGeoVis/PVGeo/master/installMac.sh | sh -s'
if 'darwin' in platform.system().lower():
# Install launch agents
print('Copy paste the following line(s) to execute in your bash terminal:\n')
print('%s %s' % (script, PYTHONPATH))
print('\n')
else:
print('Set these environmental variables to use PVGeo in ParaView:')
print('\n')
print('export PYTHONPATH="%s"' % PYTHONPATH)
print('export PV_PLUGIN_PATH="%s"' % PV_PLUGIN_PATH)
print('\n')
return
if __name__ == '__main__':
arg = sys.argv[1]
if arg.lower() == 'install':
GetInstallationPaths()
else:
raise RuntimeError('Unknown argument: %s' % arg)
| import os
import sys
import platform
def GetInstallationPaths():
path = os.path.dirname(os.path.dirname(__file__))
PYTHONPATH = path
PV_PLUGIN_PATH = '%s/%s' % (path, 'PVPlugins')
script = 'curl -s https://raw.githubusercontent.com/OpenGeoVis/PVGeo/master/installMac.sh | sh -s'
if 'darwin' in platform.system().lower():
# Install launch agents
print('Copy paste the following line(s) to execute in your bash terminal:\n')
print('%s %s' % (script, PYTHONPATH))
print('\n')
else:
print('Set these environmental variables to use PVGeo in ParaView:')
print('\n')
print('export PYTHONPATH="%s"' % PYTHONPATH)
print('export PV_PLUGIN_PATH="%s"' % PV_PLUGIN_PATH)
print('\n')
return
if __name__ == '__main__':
arg = sys.argv[1]
if arg.lower() == 'install':
GetInstallationPaths()
else:
raise RuntimeError('Unknown argument: %s' % arg)
| Use non-cached sever for mac install script | Use non-cached sever for mac install script
| Python | bsd-3-clause | banesullivan/ParaViewGeophysics,banesullivan/ParaViewGeophysics,banesullivan/ParaViewGeophysics | ---
+++
@@ -7,7 +7,7 @@
PYTHONPATH = path
PV_PLUGIN_PATH = '%s/%s' % (path, 'PVPlugins')
- script = 'curl -s https://cdn.rawgit.com/OpenGeoVis/PVGeo/master/installMac.sh | sh -s'
+ script = 'curl -s https://raw.githubusercontent.com/OpenGeoVis/PVGeo/master/installMac.sh | sh -s'
if 'darwin' in platform.system().lower():
# Install launch agents |
1fbea5f1a10613eba97ef3ff66d7ba197837b1e9 | tsv2md/__init__.py | tsv2md/__init__.py | import fileinput
import textwrap
import sys
class Table(object):
def __init__(self):
self.lines = []
self.width = 20
def feed(self,line):
self.lines.append(line.split("\t"))
def print_sep(self):
for _ in range(len(self.lines[0])):
print "-"*self.width,
print
def print_begin(self):
for _ in self.lines[0][0:-1]:
sys.stdout.write("-"*(self.width+1))
sys.stdout.write("-"*self.width)
print
def print_end(self):
self.print_begin()
def print_row(self,line,spacer=True):
cells = []
for celldata in line:
cells.append(textwrap.wrap(celldata,self.width))
max_d = max(map(len,cells))
for i in range(max_d):
for cell in cells:
try:
print "%-*s" % (self.width,cell[i]),
except IndexError:
print " "*self.width,
print
def print_blank_line(self):
print
def dump(self):
lines = self.lines
header = lines[0]
self.print_begin()
self.print_row(header)
self.print_sep()
for line in lines[1:]:
self.print_row(line)
self.print_blank_line()
self.print_end()
def main():
table = Table()
for line in fileinput.input():
table.feed(line.rstrip())
table.dump()
| import fileinput
import textwrap
import sys
class Table(object):
def __init__(self):
self.lines = []
self.width = 20
def feed(self,line):
self.lines.append(line.split("\t"))
def print_sep(self):
for _ in range(len(self.lines[0])):
print "-"*self.width,
print
def print_begin(self):
for _ in self.lines[0][0:-1]:
sys.stdout.write("-"*(self.width+1))
sys.stdout.write("-"*self.width)
print
def print_end(self):
self.print_begin()
def print_row(self,line):
cells = []
for celldata in line:
cells.append(textwrap.wrap(celldata,self.width))
max_d = max(map(len,cells))
for i in range(max_d):
for cell in cells:
try:
print "%-*s" % (self.width,cell[i]),
except IndexError:
print " "*self.width,
print
def print_blank_line(self):
print
def dump(self):
lines = self.lines
header = lines[0]
self.print_begin()
self.print_row(header)
self.print_sep()
for line in lines[1:]:
self.print_row(line)
self.print_blank_line()
self.print_end()
def main():
table = Table()
for line in fileinput.input():
table.feed(line.rstrip())
table.dump()
| Remove superfluous option from print_row. | Remove superfluous option from print_row.
| Python | mit | wouteroostervld/tsv2md | ---
+++
@@ -26,7 +26,7 @@
def print_end(self):
self.print_begin()
- def print_row(self,line,spacer=True):
+ def print_row(self,line):
cells = []
for celldata in line:
cells.append(textwrap.wrap(celldata,self.width)) |
8b34daa2a61422c79fef2afd9137bf2f1c2a5b12 | project3/webscale/synthesizer/admin.py | project3/webscale/synthesizer/admin.py | from django.contrib import admin
from .models import ApplicationTable,OldUser,Snippit,SnippitData,HolesTable,GoogleAuth,Comment
# Register your models here.
admin.site.register(ApplicationTable)
admin.site.register(OldUser)
admin.site.register(Snippit)
admin.site.register(SnippitData)
admin.site.register(HolesTable)
admin.site.register(GoogleAuth)
admin.site.register(Comment)
| from django.contrib import admin
from .models import ApplicationTable,Snippit,SnippitData,HolesTable,GoogleAuth,Comment
# Register your models here.
admin.site.register(ApplicationTable)
admin.site.register(Snippit)
admin.site.register(SnippitData)
admin.site.register(HolesTable)
admin.site.register(GoogleAuth)
admin.site.register(Comment)
| Delete calls to Old User model | Delete calls to Old User model
| Python | mit | 326-WEBSCALE/webscale-synthesizer,326-WEBSCALE/webscale-synthesizer,326-WEBSCALE/webscale-synthesizer,326-WEBSCALE/webscale-synthesizer,326-WEBSCALE/webscale-synthesizer | ---
+++
@@ -1,8 +1,7 @@
from django.contrib import admin
-from .models import ApplicationTable,OldUser,Snippit,SnippitData,HolesTable,GoogleAuth,Comment
+from .models import ApplicationTable,Snippit,SnippitData,HolesTable,GoogleAuth,Comment
# Register your models here.
admin.site.register(ApplicationTable)
-admin.site.register(OldUser)
admin.site.register(Snippit)
admin.site.register(SnippitData)
admin.site.register(HolesTable) |
491657b0b4e9344416ae3f84114eef403e020b43 | pywikibot/families/lyricwiki_family.py | pywikibot/families/lyricwiki_family.py | # -*- coding: utf-8 -*-
"""Family module for LyricWiki."""
__version__ = '$Id$'
from pywikibot import family
# The LyricWiki family
# user_config.py:
# usernames['lyricwiki']['en'] = 'user'
class Family(family.Family):
"""Family class for LyricWiki."""
def __init__(self):
"""Constructor."""
family.Family.__init__(self)
self.name = 'lyricwiki'
self.langs = {
'en': 'lyrics.wikia.com',
}
def version(self, code):
"""Return the version for this family."""
return "1.19.18"
def scriptpath(self, code):
"""Return the script path for this family."""
return ''
def apipath(self, code):
"""Return the path to api.php for this family."""
return '/api.php'
| # -*- coding: utf-8 -*-
"""Family module for LyricWiki."""
__version__ = '$Id$'
from pywikibot import family
# The LyricWiki family
# user_config.py:
# usernames['lyricwiki']['en'] = 'user'
class Family(family.Family):
"""Family class for LyricWiki."""
def __init__(self):
"""Constructor."""
family.Family.__init__(self)
self.name = 'lyricwiki'
self.langs = {
'en': 'lyrics.wikia.com',
}
def version(self, code):
"""Return the version for this family."""
return '1.19.18'
def scriptpath(self, code):
"""Return the script path for this family."""
return ''
def apipath(self, code):
"""Return the path to api.php for this family."""
return '/api.php'
| Synchronize version with compat using "'" instead of '"' | [sync] Synchronize version with compat using "'" instead of '"'
Change-Id: Ie0be0baa5eea030449b5c16d30a68ff3865aa3cf
| Python | mit | TridevGuha/pywikibot-core,magul/pywikibot-core,jayvdb/pywikibot-core,h4ck3rm1k3/pywikibot-core,magul/pywikibot-core,h4ck3rm1k3/pywikibot-core,happy5214/pywikibot-core,PersianWikipedia/pywikibot-core,jayvdb/pywikibot-core,wikimedia/pywikibot-core,icyflame/batman,happy5214/pywikibot-core,wikimedia/pywikibot-core,Darkdadaah/pywikibot-core,npdoty/pywikibot,VcamX/pywikibot-core,trishnaguha/pywikibot-core,xZise/pywikibot-core,Darkdadaah/pywikibot-core,hasteur/g13bot_tools_new,npdoty/pywikibot,smalyshev/pywikibot-core,hasteur/g13bot_tools_new,valhallasw/pywikibot-core,darthbhyrava/pywikibot-local,hasteur/g13bot_tools_new,emijrp/pywikibot-core | ---
+++
@@ -24,7 +24,7 @@
def version(self, code):
"""Return the version for this family."""
- return "1.19.18"
+ return '1.19.18'
def scriptpath(self, code):
"""Return the script path for this family.""" |
09eb73a9af576dd4026c69c2bc87c98be21c0e4e | segments/nvm.py | segments/nvm.py |
def add_nvm_segment():
import os
import subprocess
try:
output = subprocess.check_output(['bash', '-c', '. ~/.nvm/nvm.sh; nvm current'])
except (OSError, subprocess.CalledProcessError):
return
version = output.rstrip()
if version in ('system', 'none'):
return
shline.append(' node: %s ' % version, Color.NVM_FG, Color.NVM_BG)
add_nvm_segment()
|
def add_nvm_segment():
import os
import subprocess
try:
output = subprocess.check_output(['bash', '-c', '. ~/.nvm/nvm.sh; nvm current'])
except (OSError, subprocess.CalledProcessError):
return
version = output.rstrip()
if version in ('system', 'none'):
return
shline.append(u' \u2B22 %s ' % version, Color.NVM_FG, Color.NVM_BG)
add_nvm_segment()
| Use an hexagon to represent the Node version | Use an hexagon to represent the Node version
| Python | mit | saghul/shline | ---
+++
@@ -12,6 +12,6 @@
if version in ('system', 'none'):
return
- shline.append(' node: %s ' % version, Color.NVM_FG, Color.NVM_BG)
+ shline.append(u' \u2B22 %s ' % version, Color.NVM_FG, Color.NVM_BG)
add_nvm_segment() |
b5fbaafddf41f4efc1a4841a8a35f2fda094e60a | js2py/prototypes/jsfunction.py | js2py/prototypes/jsfunction.py | # python 3 support
import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
# todo fix apply and bind
class FunctionPrototype:
def toString():
if not this.is_callable():
raise TypeError('toString is not generic!')
args = ', '.join(this.code.__code__.co_varnames[:this.argcount])
return 'function %s(%s) ' % (this.func_name, args) + this.source
def call():
arguments_ = arguments
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.call(obj, args)
def apply():
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
appl = arguments[1]
args = tuple([appl[e] for e in xrange(len(appl))])
return this.call(obj, args)
def bind(thisArg):
target = this
if not target.is_callable():
raise this.MakeError(
'Object must be callable in order to be used with bind method')
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments[e] for e in xrange(1, len(arguments))])
return this.PyJsBoundFunction(target, thisArg, args)
| # python 3 support
import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
class FunctionPrototype:
def toString():
if not this.is_callable():
raise TypeError('toString is not generic!')
args = ', '.join(this.code.__code__.co_varnames[:this.argcount])
return 'function %s(%s) ' % (this.func_name, args) + this.source
def call():
arguments_ = arguments
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.call(obj, args)
def apply():
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
appl = arguments[1]
args = tuple([appl[e] for e in xrange(len(appl))])
return this.call(obj, args)
def bind(thisArg):
arguments_ = arguments
target = this
if not target.is_callable():
raise this.MakeError(
'Object must be callable in order to be used with bind method')
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.PyJsBoundFunction(target, thisArg, args)
| Fix injected local 'arguments' not working in list comprehension in bind. | Fix injected local 'arguments' not working in list comprehension in bind.
| Python | mit | PiotrDabkowski/Js2Py,PiotrDabkowski/Js2Py,PiotrDabkowski/Js2Py | ---
+++
@@ -5,8 +5,6 @@
long = int
xrange = range
unicode = str
-
-# todo fix apply and bind
class FunctionPrototype:
@@ -41,6 +39,7 @@
return this.call(obj, args)
def bind(thisArg):
+ arguments_ = arguments
target = this
if not target.is_callable():
raise this.MakeError(
@@ -48,5 +47,5 @@
if len(arguments) <= 1:
args = ()
else:
- args = tuple([arguments[e] for e in xrange(1, len(arguments))])
+ args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.PyJsBoundFunction(target, thisArg, args) |
b1a0ccda6aa4cb9408512af15bed47b2986509e1 | setup.py | setup.py | #!/usr/bin/env python
import sys
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import pkg_resources
NAME = 'pillowfight'
VERSION = '0.1'
SUMMARY = 'Eases the transition from PIL to Pillow for projects.'
fp = open('README.rst', 'r')
DESCRIPTION = fp.read().strip()
fp.close()
# If PIL is installed, use that. Otherwise prefer the newer Pillow library.
pil_req = pkg_resources.Requirement.parse('PIL')
try:
pkg_resources.get_provider(pil_req)
# We found PIL. So, guess we have to use that.
image_lib = 'PIL'
sys.stderr.write('The "PIL" library is deprecated and support will be '
'removed in a future release.\n'
'To switch to "Pillow", you must first uninstall '
'"PIL".\n\n')
except pkg_resources.DistributionNotFound:
image_lib = 'Pillow'
setup(name=NAME,
version=VERSION,
license='MIT',
description=SUMMARY,
long_description=DESCRIPTION,
install_requires=[image_lib],
zip_safe=True,
url='https://github.com/beanbaginc/pillowfight',
maintainer='Beanbag, Inc.',
maintainer_email='support@beanbaginc.com')
| #!/usr/bin/env python
import sys
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import pkg_resources
NAME = 'pillowfight'
VERSION = '0.1'
SUMMARY = 'Eases the transition from PIL to Pillow for projects.'
fp = open('README.rst', 'r')
DESCRIPTION = fp.read().strip()
fp.close()
PIL_WARNING = '''
***************************************************************************
The "PIL" library is deprecated in favor of "Pillow", and may not be
supported in a future release.
To switch to "Pillow", you must first uninstall "PIL".
***************************************************************************
'''
# If PIL is installed, use that. Otherwise prefer the newer Pillow library.
pil_req = pkg_resources.Requirement.parse('PIL')
try:
pkg_resources.get_provider(pil_req)
# We found PIL. So, guess we have to use that.
sys.stderr.write('\n%s\n' % PIL_WARNING.strip())
image_lib = 'PIL'
except pkg_resources.DistributionNotFound:
image_lib = 'Pillow'
setup(name=NAME,
version=VERSION,
license='MIT',
description=SUMMARY,
long_description=DESCRIPTION,
install_requires=[image_lib],
zip_safe=True,
url='https://github.com/beanbaginc/pillowfight',
maintainer='Beanbag, Inc.',
maintainer_email='support@beanbaginc.com')
| Make the PIL warning a little more noticeable. | Make the PIL warning a little more noticeable.
The warning has been fleshed out just a bit, and has a border above
and below it to make it more obvious.
| Python | mit | beanbaginc/pillowfight | ---
+++
@@ -19,6 +19,15 @@
DESCRIPTION = fp.read().strip()
fp.close()
+PIL_WARNING = '''
+***************************************************************************
+The "PIL" library is deprecated in favor of "Pillow", and may not be
+supported in a future release.
+
+To switch to "Pillow", you must first uninstall "PIL".
+***************************************************************************
+'''
+
# If PIL is installed, use that. Otherwise prefer the newer Pillow library.
pil_req = pkg_resources.Requirement.parse('PIL')
@@ -27,12 +36,8 @@
pkg_resources.get_provider(pil_req)
# We found PIL. So, guess we have to use that.
+ sys.stderr.write('\n%s\n' % PIL_WARNING.strip())
image_lib = 'PIL'
-
- sys.stderr.write('The "PIL" library is deprecated and support will be '
- 'removed in a future release.\n'
- 'To switch to "Pillow", you must first uninstall '
- '"PIL".\n\n')
except pkg_resources.DistributionNotFound:
image_lib = 'Pillow'
|
ca7f95e3a6b6ad8bb0ddca170a365211b9a05f3e | setup.py | setup.py | from setuptools import find_packages
from setuptools import setup
setup(
name='brew',
version='0.0.1',
author='Chris Gilmer',
author_email='chris.gilmer@gmail.com',
maintainer='Chris Gilmer',
maintainer_email='chris.gilmer@gmail.com',
description='Brew Day Tools',
url='https://github.com/chrisgilmerproj/brewday',
packages=find_packages(exclude=["*.tests",
"*.tests.*",
"tests.*",
"tests"]),
scripts=['bin/abv',
'bin/sugar',
'bin/temp',
'bin/yeast'],
include_package_data=True,
zip_safe=True,
tests_require=[
'nose==1.3.1',
'pluggy==0.3.1',
'py==1.4.31',
'tox==2.3.1',
],
classifiers=(
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"Intended Audience :: Other Audience",
"License :: OSI Approved :: GNU General Public License (GPL)",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
),
)
| from setuptools import find_packages
from setuptools import setup
setup(
name='brewday',
version='0.0.1',
author='Chris Gilmer',
author_email='chris.gilmer@gmail.com',
maintainer='Chris Gilmer',
maintainer_email='chris.gilmer@gmail.com',
description='Brew Day Tools',
url='https://github.com/chrisgilmerproj/brewday',
packages=find_packages(exclude=["*.tests",
"*.tests.*",
"tests.*",
"tests"]),
scripts=['bin/abv',
'bin/sugar',
'bin/temp',
'bin/yeast'],
include_package_data=True,
zip_safe=True,
tests_require=[
'nose==1.3.1',
'pluggy==0.3.1',
'py==1.4.31',
'tox==2.3.1',
],
classifiers=(
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"Intended Audience :: Other Audience",
"License :: OSI Approved :: GNU General Public License (GPL)",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
),
)
| Fix the name on the package from brew to brewday | Fix the name on the package from brew to brewday
| Python | mit | chrisgilmerproj/brewday,chrisgilmerproj/brewday | ---
+++
@@ -2,7 +2,7 @@
from setuptools import setup
setup(
- name='brew',
+ name='brewday',
version='0.0.1',
author='Chris Gilmer',
author_email='chris.gilmer@gmail.com', |
7281e01b49bf5f28ae5c6f8cb1891d39d5bd3b4f | lutrisweb/settings/production.py | lutrisweb/settings/production.py | import os
from base import * # noqa
DEBUG = False
MEDIA_URL = '//lutris.net/media/'
FILES_ROOT = '/srv/files'
ALLOWED_HOSTS = ['.lutris.net', '.lutris.net.', ]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': 'localhost',
#'CONN_MAX_AGE': 600,
}
}
EMAIL_HOST = os.environ['EMAIL_HOST']
EMAIL_HOST_USER = os.environ['EMAIL_HOST_USER']
EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD']
EMAIL_USE_TLS = True
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
# SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
STEAM_API_KEY = os.environ['STEAM_API_KEY']
| import os
from base import * # noqa
DEBUG = False
MEDIA_URL = '//lutris.net/media/'
FILES_ROOT = '/srv/files'
ALLOWED_HOSTS = ['.lutris.net', '.lutris.net.', ]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': os.environ['DATABASE_PASSWORD'],
'HOST': 'localhost',
#'CONN_MAX_AGE': 600,
}
}
EMAIL_HOST = os.environ['EMAIL_HOST']
EMAIL_HOST_USER = os.environ['EMAIL_HOST_USER']
EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD']
EMAIL_USE_TLS = True
#TEMPLATE_LOADERS = (
# 'django.template.loaders.filesystem.Loader',
# 'django.template.loaders.app_directories.Loader',
#)
# SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
STEAM_API_KEY = os.environ['STEAM_API_KEY']
| Disable some prod optimisations (more) | Disable some prod optimisations (more)
| Python | agpl-3.0 | lutris/website,lutris/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website,Turupawn/website,lutris/website | ---
+++
@@ -23,10 +23,10 @@
EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD']
EMAIL_USE_TLS = True
-TEMPLATE_LOADERS = (
- 'django.template.loaders.filesystem.Loader',
- 'django.template.loaders.app_directories.Loader',
-)
+#TEMPLATE_LOADERS = (
+# 'django.template.loaders.filesystem.Loader',
+# 'django.template.loaders.app_directories.Loader',
+#)
# SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
|
015eb13331f121452ce44be39cb52aef3465f5c6 | dthm4kaiako/tests/resources/factories.py | dthm4kaiako/tests/resources/factories.py | """Module for factories for tesing resources application."""
import random
from factory import DjangoModelFactory, Faker, post_generation
from factory.faker import faker
from resources.models import (
Resource,
ResourceComponent,
)
class ResourceFactory(DjangoModelFactory):
"""Factory for generating resources."""
name = Faker('sentence')
description = Faker('paragraph', nb_sentences=5)
class Meta:
"""Metadata for class."""
model = Resource
@post_generation
def create_components(self, create, extracted, **kwargs):
"""Create components for resource."""
FAKER = faker.Faker()
number_of_components = random.randint(0, 9)
for i in range(number_of_components):
component_name = FAKER.sentence()
component_type = random.choice(list(ResourceComponent.COMPONENT_TYPE_DATA))
if component_type == ResourceComponent.TYPE_WEBSITE:
ResourceComponent.objects.create(
name=component_name,
resource=self,
component_url=FAKER.url(),
)
# TODO: Implement all types of components
else:
ResourceComponent.objects.create(
name=component_name,
resource=self,
component_url=FAKER.url(),
)
| """Module for factories for tesing resources application."""
import random
from factory import DjangoModelFactory, Faker, post_generation
from factory.faker import faker
from resources.models import (
Resource,
ResourceComponent,
)
class ResourceFactory(DjangoModelFactory):
"""Factory for generating resources."""
name = Faker('sentence')
description = Faker('paragraph', nb_sentences=5)
class Meta:
"""Metadata for class."""
model = Resource
@post_generation
def create_components(self, create, extracted, **kwargs):
"""Create components for resource."""
FAKER = faker.Faker()
number_of_components = random.randint(1, 9)
for i in range(number_of_components):
component_name = FAKER.sentence()
component_type = random.choice(list(ResourceComponent.COMPONENT_TYPE_DATA))
resource_count = Resource.objects.count()
if component_type == ResourceComponent.TYPE_WEBSITE:
ResourceComponent.objects.create(
name=component_name,
resource=self,
component_url=FAKER.url(),
)
elif component_type == ResourceComponent.TYPE_RESOURCE and resource_count >= 2:
resources = list(Resource.objects.exclude(pk=self.pk))
resource_component = resources[random.randint(0, len(resources) - 1)]
ResourceComponent.objects.create(
name=resource_component.name,
resource=self,
component_resource=resource_component,
)
# TODO: Implement all types of components
else:
ResourceComponent.objects.create(
name=component_name,
resource=self,
component_url=FAKER.url(),
)
| Update sampledata generator to allow component resources | Update sampledata generator to allow component resources
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -24,16 +24,26 @@
def create_components(self, create, extracted, **kwargs):
"""Create components for resource."""
FAKER = faker.Faker()
- number_of_components = random.randint(0, 9)
+ number_of_components = random.randint(1, 9)
for i in range(number_of_components):
component_name = FAKER.sentence()
component_type = random.choice(list(ResourceComponent.COMPONENT_TYPE_DATA))
+ resource_count = Resource.objects.count()
+
if component_type == ResourceComponent.TYPE_WEBSITE:
ResourceComponent.objects.create(
name=component_name,
resource=self,
component_url=FAKER.url(),
+ )
+ elif component_type == ResourceComponent.TYPE_RESOURCE and resource_count >= 2:
+ resources = list(Resource.objects.exclude(pk=self.pk))
+ resource_component = resources[random.randint(0, len(resources) - 1)]
+ ResourceComponent.objects.create(
+ name=resource_component.name,
+ resource=self,
+ component_resource=resource_component,
)
# TODO: Implement all types of components
else: |
c876794a24e9adb83f41d9878220dc8c63228e2e | utils/database.py | utils/database.py | class Database(object):
def __init__(self, channels):
self.userdb = {}
for i in channels:
self.userdb[i] = {}
def removeEntry(self, event, nick):
try:
del self.userdb[event.target][nick]
except KeyError:
for i in self.userdb[event.target].values():
if i['host'] == event.source.host:
del self.userdb[event.target][i['hostmask'].split("!")[0]]
break
def addEntry(self, channel, nick, hostmask, host, account):
self.userdb[channel][nick] = {
'hostmask': hostmask,
'host': host,
'account': account
}
def __getitem__(self, key):
return self.userdb[key]
def __delitem__(self, key):
del self.userdb[key]
def __setitem__(self, key, value):
self.userdb[key] = value
def __str__(self):
return repr(self.userdb)
def get(self, key, default=None):
try:
return self.userdb[key]
except KeyError:
return default
def keys(self):
return self.userdb.keys()
def values(self):
return self.userdb.values()
| class Database(object):
def __init__(self, channels):
self.userdb = {}
for i in channels:
self.userdb[i] = {}
def removeEntry(self, event, nick):
try:
del self.userdb[event.target][nick]
except KeyError:
for i in self.userdb[event.target].values():
if i['host'] == event.source.host:
del self.userdb[event.target][i['hostmask'].split("!")[0]]
break
def addEntry(self, channel, nick, hostmask, host, account):
self.userdb[channel][nick] = {
'hostmask': hostmask,
'host': host,
'account': account
}
def __getitem__(self, key):
return self.userdb[key]
def __delitem__(self, key):
del self.userdb[key]
def __setitem__(self, key, value):
self.userdb[key] = value
def __str__(self):
return str(self.userdb)
def get(self, key, default=None):
try:
return self.userdb[key]
except KeyError:
return default
def keys(self):
return self.userdb.keys()
def values(self):
return self.userdb.values()
| Use str instead of repr | Use str instead of repr | Python | mit | wolfy1339/Python-IRC-Bot | ---
+++
@@ -30,7 +30,7 @@
self.userdb[key] = value
def __str__(self):
- return repr(self.userdb)
+ return str(self.userdb)
def get(self, key, default=None):
try: |
aa966c1a208f2c3f4b2a2a196c39b1df5a0b67c8 | basics/candidate.py | basics/candidate.py |
import numpy as np
class Bubble2D(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, props):
super(Bubble2D, self).__init__()
self._channel = props[0]
self._y = props[1]
self._x = props[2]
self._major = props[3]
self._minor = props[4]
self._pa = props[5]
@property
def params(self):
return [self._channel, self._y, self._x, self._major,
self._minor, self._pa]
@property
def area(self):
return np.pi * self.major * self.minor
@property
def pa(self):
return self._pa
@property
def major(self):
return self._major
@property
def minor(self):
return self._minor
def profiles_lines(self, array, **kwargs):
'''
Calculate radial profile lines of the 2D bubbles.
'''
from basics.profile import azimuthal_profiles
return azimuthal_profiles(array, self.params, **kwargs)
|
import numpy as np
class Bubble2D(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, props):
super(Bubble2D, self).__init__()
self._channel = props[0]
self._y = props[1]
self._x = props[2]
self._major = props[3]
self._minor = props[4]
self._pa = props[5]
@property
def params(self):
return [self._channel, self._y, self._x, self._major,
self._minor, self._pa]
@property
def area(self):
return np.pi * self.major * self.minor
@property
def pa(self):
return self._pa
@property
def major(self):
return self._major
@property
def minor(self):
return self._minor
def profiles_lines(self, array, **kwargs):
'''
Calculate radial profile lines of the 2D bubbles.
'''
from basics.profile import azimuthal_profiles
return azimuthal_profiles(array, self.params, **kwargs)
def as_mask(self):
'''
Return a boolean mask of the 2D region.
'''
raise NotImplementedError()
def find_shape(self):
'''
Expand/contract to match the contours in the data.
'''
raise NotImplementedError()
| Add methods that need to be implemented | Add methods that need to be implemented
| Python | mit | e-koch/BaSiCs | ---
+++
@@ -45,3 +45,15 @@
from basics.profile import azimuthal_profiles
return azimuthal_profiles(array, self.params, **kwargs)
+
+ def as_mask(self):
+ '''
+ Return a boolean mask of the 2D region.
+ '''
+ raise NotImplementedError()
+
+ def find_shape(self):
+ '''
+ Expand/contract to match the contours in the data.
+ '''
+ raise NotImplementedError() |
2fbbe27d4d0e64d21e5cdcad5d717d12e5f2d583 | cobe/control.py | cobe/control.py | import cmdparse
import commands
import logging
import optparse
import sys
parser = cmdparse.CommandParser()
parser.add_option("", "--debug", action="store_true",
help=optparse.SUPPRESS_HELP)
parser.add_option("", "--profile", action="store_true",
help=optparse.SUPPRESS_HELP)
parser.add_commands(commands)
def main():
(command, options, args) = parser.parse_args()
formatter = logging.Formatter("%(levelname)s: %(message)s")
console = logging.StreamHandler()
console.setFormatter(formatter)
logging.root.addHandler(console)
if options.debug:
logging.root.setLevel(logging.DEBUG)
else:
logging.root.setLevel(logging.INFO)
if options.profile:
import cProfile
if command is None:
parser.print_help()
sys.exit(1)
try:
if options.profile:
cProfile.run("command.run(options, args)", "cobe.pstats")
else:
command.run(options, args)
except KeyboardInterrupt:
print
sys.exit(1)
if __name__ == "__main__":
main()
| import cmdparse
import commands
import logging
import optparse
import sys
parser = cmdparse.CommandParser()
parser.add_option("", "--debug", action="store_true",
help=optparse.SUPPRESS_HELP)
parser.add_option("", "--profile", action="store_true",
help=optparse.SUPPRESS_HELP)
parser.add_command(commands.InitCommand(), "Control")
parser.add_command(commands.ConsoleCommand(), "Control")
parser.add_command(commands.LearnCommand(), "Learning")
parser.add_command(commands.LearnIrcLogCommand(), "Learning")
def main():
(command, options, args) = parser.parse_args()
formatter = logging.Formatter("%(levelname)s: %(message)s")
console = logging.StreamHandler()
console.setFormatter(formatter)
logging.root.addHandler(console)
if options.debug:
logging.root.setLevel(logging.DEBUG)
else:
logging.root.setLevel(logging.INFO)
if options.profile:
import cProfile
if command is None:
parser.print_help()
sys.exit(1)
try:
if options.profile:
cProfile.run("command.run(options, args)", "cobe.pstats")
else:
command.run(options, args)
except KeyboardInterrupt:
print
sys.exit(1)
if __name__ == "__main__":
main()
| Add command groups for better help output | Add command groups for better help output
| Python | mit | LeMagnesium/cobe,DarkMio/cobe,pteichman/cobe,pteichman/cobe,meska/cobe,DarkMio/cobe,wodim/cobe-ng,tiagochiavericosta/cobe,wodim/cobe-ng,meska/cobe,tiagochiavericosta/cobe,LeMagnesium/cobe | ---
+++
@@ -10,7 +10,10 @@
parser.add_option("", "--profile", action="store_true",
help=optparse.SUPPRESS_HELP)
-parser.add_commands(commands)
+parser.add_command(commands.InitCommand(), "Control")
+parser.add_command(commands.ConsoleCommand(), "Control")
+parser.add_command(commands.LearnCommand(), "Learning")
+parser.add_command(commands.LearnIrcLogCommand(), "Learning")
def main():
(command, options, args) = parser.parse_args() |
e0d66977ed4aca80eefc4d011bd8753987df3e8e | docker/settings.py | docker/settings.py | from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
| from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 25
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
| Increase connection pool size for canvas rest client. | Increase connection pool size for canvas rest client.
| Python | apache-2.0 | uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics | ---
+++
@@ -23,4 +23,5 @@
}
}
+RESTCLIENTS_CANVAS_POOL_SIZE = 25
ACADEMIC_CANVAS_ACCOUNT_ID = '84378' |
fbe05b7e2fe97724cb126f0a5b5dd656591d41d7 | apps/polls/tests.py | apps/polls/tests.py | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| import datetime
from django.utils import timezone
from django.test import TestCase
from apps.polls.models import Poll
class PollMethodTests(TestCase):
def test_was_published_recently_with_future_poll(self):
"""
was_published_recently_with_future_poll() should return False for for polls whose
pub_date is is the future
"""
future_poll = Poll(pub_date=timezone.now() + datetime.timedelta(days=30))
self.assertEqual(future_poll.was_published_recently(), False) | Create a test to expose the bug | Create a test to expose the bug
| Python | bsd-3-clause | datphan/teracy-tutorial,teracyhq/django-tutorial | ---
+++
@@ -1,16 +1,17 @@
-"""
-This file demonstrates writing tests using the unittest module. These will pass
-when you run "manage.py test".
+import datetime
-Replace this with more appropriate tests for your application.
-"""
-
+from django.utils import timezone
from django.test import TestCase
+from apps.polls.models import Poll
-class SimpleTest(TestCase):
- def test_basic_addition(self):
+
+class PollMethodTests(TestCase):
+
+ def test_was_published_recently_with_future_poll(self):
"""
- Tests that 1 + 1 always equals 2.
+ was_published_recently_with_future_poll() should return False for for polls whose
+ pub_date is is the future
"""
- self.assertEqual(1 + 1, 2)
+ future_poll = Poll(pub_date=timezone.now() + datetime.timedelta(days=30))
+ self.assertEqual(future_poll.was_published_recently(), False) |
b9a54ba81dbd7b0235ad774602a7098d590eb92c | tests/test_gui_widgets.py | tests/test_gui_widgets.py |
from polyglotdb.gui.widgets.basic import DirectoryWidget
def test_directory_widget(qtbot):
widget = DirectoryWidget()
qtbot.addWidget(widget)
widget.setPath('test')
assert(widget.value() == 'test')
|
#from polyglotdb.gui.widgets.basic import DirectoryWidget
#def test_directory_widget(qtbot):
# widget = DirectoryWidget()
# qtbot.addWidget(widget)
# widget.setPath('test')
# assert(widget.value() == 'test')
| Disable GUI testing for now | Disable GUI testing for now
| Python | mit | PhonologicalCorpusTools/PolyglotDB,PhonologicalCorpusTools/PolyglotDB,samihuc/PolyglotDB,MontrealCorpusTools/PolyglotDB,PhonologicalCorpusTools/PyAnnotationGraph,samihuc/PolyglotDB,PhonologicalCorpusTools/PyAnnotationGraph,MontrealCorpusTools/PolyglotDB | ---
+++
@@ -1,10 +1,10 @@
-from polyglotdb.gui.widgets.basic import DirectoryWidget
+#from polyglotdb.gui.widgets.basic import DirectoryWidget
-def test_directory_widget(qtbot):
- widget = DirectoryWidget()
- qtbot.addWidget(widget)
+#def test_directory_widget(qtbot):
+# widget = DirectoryWidget()
+# qtbot.addWidget(widget)
- widget.setPath('test')
+# widget.setPath('test')
- assert(widget.value() == 'test')
+# assert(widget.value() == 'test') |
5b735dff075cb4fb2e9fd89dc4d872281210964d | config/regenerate_launch_files.py | config/regenerate_launch_files.py | #!/usr/bin/env python3
# (C) 2015 Jean Nassar
# Released under BSD
import glob
import os
import subprocess as sp
import rospkg
import tqdm
def get_launch_dir(package: str) -> str:
return os.path.join(rospkg.RosPack().get_path(package), "launch")
def get_file_root(path: str) -> str:
"""
>>> get_file_root("/tmp/test.txt")
'test'
"""
return os.path.split(path[:path.rindex(".")])[1]
def compile_xacro(inpath: str, outpath: str) -> None:
sp.call("rosrun xacro xacro {inpath} --inorder -o {outpath}"
.format(inpath=inpath, outpath=outpath).split(),
stdout=sp.DEVNULL)
def main():
launch_dir = get_launch_dir("spirit")
os.chdir(launch_dir)
for path in tqdm.tqdm(glob.glob("xacro/*.xacro"),
desc="Regenerating launch files"):
root = get_file_root(path)
compile_xacro(path, os.path.join("launchers", root))
if __name__ == "__main__":
main()
| #!/usr/bin/env python2
# (C) 2015 Jean Nassar
# Released under BSD
import glob
import os
import subprocess as sp
import rospkg
import tqdm
def get_launch_dir(package):
return os.path.join(rospkg.RosPack().get_path(package), "launch")
def get_file_root(path):
"""
>>> get_file_root("/tmp/test.txt")
'test'
"""
return os.path.split(path[:path.rindex(".")])[1]
def compile_xacro(inpath, outpath, stdout):
sp.call("rosrun xacro xacro {inpath} --inorder -o {outpath}"
.format(inpath=inpath, outpath=outpath).split(),
stdout=stdout)
def main():
launch_dir = get_launch_dir("spirit")
os.chdir(launch_dir)
with open(os.devnull, "w") as DEVNULL:
for path in tqdm.tqdm(glob.glob("xacro/*.xacro"),
desc="Regenerating launch files"):
root = get_file_root(path)
compile_xacro(path, os.path.join("launchers", root), DEVNULL)
if __name__ == "__main__":
main()
| Make compatible with Python 2 and 3. | Make compatible with Python 2 and 3.
| Python | mit | masasin/spirit,masasin/spirit | ---
+++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python3
+#!/usr/bin/env python2
# (C) 2015 Jean Nassar
# Released under BSD
import glob
@@ -9,11 +9,11 @@
import tqdm
-def get_launch_dir(package: str) -> str:
+def get_launch_dir(package):
return os.path.join(rospkg.RosPack().get_path(package), "launch")
-def get_file_root(path: str) -> str:
+def get_file_root(path):
"""
>>> get_file_root("/tmp/test.txt")
'test'
@@ -22,19 +22,20 @@
return os.path.split(path[:path.rindex(".")])[1]
-def compile_xacro(inpath: str, outpath: str) -> None:
+def compile_xacro(inpath, outpath, stdout):
sp.call("rosrun xacro xacro {inpath} --inorder -o {outpath}"
.format(inpath=inpath, outpath=outpath).split(),
- stdout=sp.DEVNULL)
+ stdout=stdout)
def main():
launch_dir = get_launch_dir("spirit")
os.chdir(launch_dir)
- for path in tqdm.tqdm(glob.glob("xacro/*.xacro"),
- desc="Regenerating launch files"):
- root = get_file_root(path)
- compile_xacro(path, os.path.join("launchers", root))
+ with open(os.devnull, "w") as DEVNULL:
+ for path in tqdm.tqdm(glob.glob("xacro/*.xacro"),
+ desc="Regenerating launch files"):
+ root = get_file_root(path)
+ compile_xacro(path, os.path.join("launchers", root), DEVNULL)
if __name__ == "__main__": |
07b6484b33d687a7c32f91b5c2274d54c1e106ff | stormtracks/settings/default_stormtracks_settings.py | stormtracks/settings/default_stormtracks_settings.py | # *** DON'T MODIFY THIS FILE! ***
#
# Instead copy it to stormtracks_settings.py
#
# Default settings for project
# This will get copied to $HOME/.stormtracks/
# on install.
import os
SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
# expandvars expands e.g. $HOME
DATA_DIR = os.path.expandvars('$HOME/stormtracks/data')
OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks/output')
C20_FULL_DATA_DIR = os.path.join(DATA_DIR, 'c20_full')
C20_MEAN_DATA_DIR = os.path.join(DATA_DIR, 'c20_mean')
IBTRACS_DATA_DIR = os.path.join(DATA_DIR, 'ibtracs')
| # *** DON'T MODIFY THIS FILE! ***
#
# Instead copy it to stormtracks_settings.py
#
# Default settings for project
# This will get copied to $HOME/.stormtracks/
# on install.
import os
SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
# expandvars expands e.g. $HOME
DATA_DIR = os.path.expandvars('$HOME/stormtracks_data/data')
OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/output')
C20_FULL_DATA_DIR = os.path.join(DATA_DIR, 'c20_full')
C20_MEAN_DATA_DIR = os.path.join(DATA_DIR, 'c20_mean')
IBTRACS_DATA_DIR = os.path.join(DATA_DIR, 'ibtracs')
| Change the location of stormtracks data. | Change the location of stormtracks data.
| Python | mit | markmuetz/stormtracks,markmuetz/stormtracks | ---
+++
@@ -9,8 +9,8 @@
SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
# expandvars expands e.g. $HOME
-DATA_DIR = os.path.expandvars('$HOME/stormtracks/data')
-OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks/output')
+DATA_DIR = os.path.expandvars('$HOME/stormtracks_data/data')
+OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/output')
C20_FULL_DATA_DIR = os.path.join(DATA_DIR, 'c20_full')
C20_MEAN_DATA_DIR = os.path.join(DATA_DIR, 'c20_mean') |
faf861e53c1d4f554da82cd66b6b8de4fa7a2ab7 | src/main/python/infra_buddy/notifier/datadog.py | src/main/python/infra_buddy/notifier/datadog.py | from infra_buddy.context.deploy_ctx import DeployContext
import datadog as dd
class DataDogNotifier(object):
def __init__(self, key, deploy_context):
# type: (DeployContext) -> None
super(DataDogNotifier, self).__init__()
self.deploy_context = deploy_context
dd.initialize(api_key=key)
def notify_event(self, title, type, message):
dd.api.Event.create(title=title,
text=message,
alert_type=type,
tags=self._get_tags())
def _get_tags(self):
return ['application:{app},role:{role},environment:{env}'.format(
app=self.deploy_context.application,
role=self.deploy_context.role,
env=self.deploy_context.environment)]
| import datadog as dd
class DataDogNotifier(object):
def __init__(self, key, deploy_context):
# type: (DeployContext) -> None
super(DataDogNotifier, self).__init__()
self.deploy_context = deploy_context
dd.initialize(api_key=key)
def notify_event(self, title, type, message):
dd.api.Event.create(title=title,
text=message,
alert_type=type,
tags=self._get_tags())
def _get_tags(self):
return ['application:{app},role:{role},environment:{env}'.format(
app=self.deploy_context.application,
role=self.deploy_context.role,
env=self.deploy_context.environment)]
| Remove import for type annotation | Remove import for type annotation
| Python | apache-2.0 | AlienVault-Engineering/infra-buddy | ---
+++
@@ -1,4 +1,3 @@
-from infra_buddy.context.deploy_ctx import DeployContext
import datadog as dd
|
34e0934d2f62a98728601a18126fa21eb50cf5a5 | doubles/testing.py | doubles/testing.py | class User(object):
"""An importable dummy class used for testing purposes."""
class_attribute = 'foo'
@staticmethod
def static_method():
pass
@classmethod
def class_method(cls):
return 'class method'
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def instance_method(self):
pass
def method_with_varargs(self, *args):
pass
def method_with_default_args(self, foo, bar='baz'):
pass
def method_with_varkwargs(self, **kwargs):
pass
def method_with_positional_arguments(self, foo):
pass
| class User(object):
"""An importable dummy class used for testing purposes."""
class_attribute = 'foo'
@staticmethod
def static_method():
return 'static_method return value'
@classmethod
def class_method(cls):
return 'class_method return value'
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def instance_method(self):
return 'instance_method return value'
def method_with_varargs(self, *args):
return 'method_with_varargs return value'
def method_with_default_args(self, foo, bar='baz'):
return 'method_with_default_args return value'
def method_with_varkwargs(self, **kwargs):
return 'method_with_varkwargs return value'
def method_with_positional_arguments(self, foo):
return 'method_with_positional_arguments return value'
| Return easily identifiable values from User methods. | Return easily identifiable values from User methods.
| Python | mit | uber/doubles | ---
+++
@@ -5,11 +5,11 @@
@staticmethod
def static_method():
- pass
+ return 'static_method return value'
@classmethod
def class_method(cls):
- return 'class method'
+ return 'class_method return value'
def __init__(self, name, age):
self.name = name
@@ -19,16 +19,16 @@
return self.name
def instance_method(self):
- pass
+ return 'instance_method return value'
def method_with_varargs(self, *args):
- pass
+ return 'method_with_varargs return value'
def method_with_default_args(self, foo, bar='baz'):
- pass
+ return 'method_with_default_args return value'
def method_with_varkwargs(self, **kwargs):
- pass
+ return 'method_with_varkwargs return value'
def method_with_positional_arguments(self, foo):
- pass
+ return 'method_with_positional_arguments return value' |
a5b70775d106d07acfb54ce0b3998a03ed195de7 | test/uritemplate_test.py | test/uritemplate_test.py | import uritemplate
import simplejson
import sys
filename = sys.argv[1]
print "Running", filename
f = file(filename)
testdata = simplejson.load(f)
try:
desired_level = int(sys.argv[2])
except IndexError:
desired_level = 4
for name, testsuite in testdata.iteritems():
vars = testsuite['variables']
testcases = testsuite['testcases']
level = testsuite.get('level', 4)
if level > desired_level:
continue
print name
for testcase in testcases:
template = testcase[0]
expected = testcase[1]
actual = uritemplate.expand(template, vars)
sys.stdout.write(".")
if expected != actual:
print "Template %s expected to expand to %s, got %s instead" % (template, expected, actual)
assert 0
print
| import uritemplate
import simplejson
import sys
filename = sys.argv[1]
print "Running", filename
f = file(filename)
testdata = simplejson.load(f)
try:
desired_level = int(sys.argv[2])
except IndexError:
desired_level = 4
for name, testsuite in testdata.iteritems():
vars = testsuite['variables']
testcases = testsuite['testcases']
level = testsuite.get('level', 4)
if level > desired_level:
continue
print name
for testcase in testcases:
template = testcase[0]
expected = testcase[1]
actual = uritemplate.expand(template, vars)
sys.stdout.write(".")
if type(expected) == type([]):
if actual not in expected:
sys.stderr.write("%s didn't expand as expected, got %s instead\n" % (template, actual))
assert 0
else:
if actual != expected:
sys.stderr.write("%s expected to expand to %s, got %s instead\n" % (template, expected, actual))
assert 0
print
| Handle lists of possibilities in tests | Handle lists of possibilities in tests
| Python | apache-2.0 | uri-templates/uritemplate-py | ---
+++
@@ -26,7 +26,12 @@
expected = testcase[1]
actual = uritemplate.expand(template, vars)
sys.stdout.write(".")
- if expected != actual:
- print "Template %s expected to expand to %s, got %s instead" % (template, expected, actual)
- assert 0
+ if type(expected) == type([]):
+ if actual not in expected:
+ sys.stderr.write("%s didn't expand as expected, got %s instead\n" % (template, actual))
+ assert 0
+ else:
+ if actual != expected:
+ sys.stderr.write("%s expected to expand to %s, got %s instead\n" % (template, expected, actual))
+ assert 0
print |
48362fa70ab20f66f4f398c68ab252dfd36c6117 | crust/fields.py | crust/fields.py | class Field(object):
"""
Base class for all field types
"""
# This tracks each time a Field instance is created. Used to retain order.
creation_counter = 0
def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs):
super(Field, self).__init__(*args, **kwargs)
self.name = name
self.primary_key = primary_key
self.serialize = serialize
self.creation_counter = Field.creation_counter
Field.creation_counter += 1
def hydrate(self, value):
return value
| class Field(object):
"""
Base class for all field types
"""
# This tracks each time a Field instance is created. Used to retain order.
creation_counter = 0
def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs):
super(Field, self).__init__(*args, **kwargs)
self.name = name
self.primary_key = primary_key
self.serialize = serialize
self.creation_counter = Field.creation_counter
Field.creation_counter += 1
def hydrate(self, value):
return value
def dehydrate(self, value):
return value
| Make provisions for dehydrating a field | Make provisions for dehydrating a field
| Python | bsd-2-clause | dstufft/crust | ---
+++
@@ -18,3 +18,6 @@
def hydrate(self, value):
return value
+
+ def dehydrate(self, value):
+ return value |
24538a6e91983974c729a559ab24ee90ad529d7e | engines/string_template_engine.py | engines/string_template_engine.py | #!/usr/bin/env python3
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __init__(self, template, **kwargs):
"""Initialize string.Template."""
super(StringTemplate, self).__init__(**kwargs)
self.template = Template(template)
def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
return self.template.substitute(mapping)
| #!/usr/bin/env python3
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __init__(self, template, tolerant=False, **kwargs):
"""Initialize string.Template."""
super(StringTemplate, self).__init__(**kwargs)
self.template = Template(template)
self.tolerant = tolerant
def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
if self.tolerant:
return self.template.safe_substitute(mapping)
return self.template.substitute(mapping)
| Implement tolerant handling in string.Template engine. | Implement tolerant handling in string.Template engine.
| Python | mit | blubberdiblub/eztemplate | ---
+++
@@ -15,12 +15,16 @@
handle = 'string.Template'
- def __init__(self, template, **kwargs):
+ def __init__(self, template, tolerant=False, **kwargs):
"""Initialize string.Template."""
super(StringTemplate, self).__init__(**kwargs)
self.template = Template(template)
+ self.tolerant = tolerant
def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
+ if self.tolerant:
+ return self.template.safe_substitute(mapping)
+
return self.template.substitute(mapping) |
73d2c1e1675ed9e7fe2bc389ec0079c5c6ce73ee | numpy/_array_api/_constants.py | numpy/_array_api/_constants.py | from .. import e, inf, nan, pi
| from ._array_object import ndarray
from ._dtypes import float64
import numpy as np
e = ndarray._new(np.array(np.e, dtype=float64))
inf = ndarray._new(np.array(np.inf, dtype=float64))
nan = ndarray._new(np.array(np.nan, dtype=float64))
pi = ndarray._new(np.array(np.pi, dtype=float64))
| Make the array API constants into dimension 0 arrays | Make the array API constants into dimension 0 arrays
The spec does not actually specify whether these should be dimension 0 arrays
or Python floats (which they are in NumPy). However, making them dimension 0
arrays is cleaner, and ensures they also have all the methods and attributes
that are implemented on the ndarray object.
| Python | bsd-3-clause | jakirkham/numpy,simongibbons/numpy,seberg/numpy,mattip/numpy,mhvk/numpy,mattip/numpy,anntzer/numpy,endolith/numpy,jakirkham/numpy,charris/numpy,seberg/numpy,mattip/numpy,anntzer/numpy,simongibbons/numpy,numpy/numpy,simongibbons/numpy,mhvk/numpy,simongibbons/numpy,charris/numpy,rgommers/numpy,jakirkham/numpy,rgommers/numpy,jakirkham/numpy,endolith/numpy,rgommers/numpy,endolith/numpy,charris/numpy,anntzer/numpy,mhvk/numpy,mhvk/numpy,pdebuyl/numpy,pdebuyl/numpy,rgommers/numpy,pdebuyl/numpy,mattip/numpy,pdebuyl/numpy,simongibbons/numpy,numpy/numpy,charris/numpy,numpy/numpy,seberg/numpy,numpy/numpy,jakirkham/numpy,seberg/numpy,endolith/numpy,mhvk/numpy,anntzer/numpy | ---
+++
@@ -1 +1,9 @@
-from .. import e, inf, nan, pi
+from ._array_object import ndarray
+from ._dtypes import float64
+
+import numpy as np
+
+e = ndarray._new(np.array(np.e, dtype=float64))
+inf = ndarray._new(np.array(np.inf, dtype=float64))
+nan = ndarray._new(np.array(np.nan, dtype=float64))
+pi = ndarray._new(np.array(np.pi, dtype=float64)) |
b2e2ff0c6a31472e16706cb72765a0ca939e1414 | web.py | web.py | import csv
import sqlite3
from flask import Flask, request, render_template, g, jsonify
app = Flask(__name__)
db_filename = 'db.sqlite'
def connect_db():
conn = sqlite3.connect(db_filename)
curs = conn.execute('PRAGMA foreign_keys = ON')
return conn
@app.before_request
def before_request():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()
@app.route('/json')
def json():
cur = g.db.execute('''
SELECT
snapshot_time, count(*)
FROM
snapshot_content sc
JOIN snapshot s ON sc.snapshot_id = s.id
GROUP BY snapshot_id
ORDER BY s.snapshot_time''')
return jsonify({'chart_data': list(cur)})
@app.route('/')
def index():
return render_template('chart.html')
if __name__ == '__main__':
app.run(debug=True)
| import csv
import sqlite3
from flask import Flask, request, render_template, g, jsonify
app = Flask(__name__)
db_filename = 'db.sqlite'
def connect_db():
conn = sqlite3.connect(db_filename)
curs = conn.execute('PRAGMA foreign_keys = ON')
return conn
@app.before_request
def before_request():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()
@app.route('/json')
def json():
cur = g.db.execute('''
SELECT
strftime('%s', snapshot_time), count(*)
FROM
snapshot_content sc
JOIN snapshot s ON sc.snapshot_id = s.id
GROUP BY snapshot_id
ORDER BY s.snapshot_time''')
data = [(int(unix_timestamp)*1000, count) for unix_timestamp, count in cur]
return jsonify({'chart_data': data})
@app.route('/')
def index():
return render_template('chart.html')
if __name__ == '__main__':
app.run(debug=True)
| Package count chart: fixed labels of x axis | Package count chart: fixed labels of x axis
| Python | mit | Koblaid/distrostats,Koblaid/distrostats | ---
+++
@@ -30,13 +30,14 @@
def json():
cur = g.db.execute('''
SELECT
- snapshot_time, count(*)
+ strftime('%s', snapshot_time), count(*)
FROM
snapshot_content sc
JOIN snapshot s ON sc.snapshot_id = s.id
GROUP BY snapshot_id
ORDER BY s.snapshot_time''')
- return jsonify({'chart_data': list(cur)})
+ data = [(int(unix_timestamp)*1000, count) for unix_timestamp, count in cur]
+ return jsonify({'chart_data': data})
@app.route('/') |
0933e4c671ca1297378b2ad388933e11265321d0 | traptor/dd_monitoring.py | traptor/dd_monitoring.py | ###############################################################################
# This is a very strange handler setup, but this is how it's documented.
# See https://github.com/DataDog/datadogpy#quick-start-guide
###############################################################################
import os
from datadog import initialize
traptor_type = os.environ['TRAPTOR_TYPE']
traptor_id = os.environ['TRAPTOR_ID']
DEFAULT_TAGS = [
'traptor_type:{}'.format(traptor_type),
'traptor_id:{}'.format(traptor_id),
]
options = {
'statsd_host': os.environ['STATSD_HOST_IP'],
}
initialize(**options)
from datadog import statsd
DATADOG_METRICS = {
'tweet_process_success': 'traptor.src.tweet_process.success',
'tweet_process_failure': 'traptor.src.tweet_process.failure',
'tweet_to_kafka_success': 'traptor.src.tweet_to_kafka.success',
'tweet_to_kafka_failure': 'traptor.src.tweet_to_kafka.failure',
}
def increment(metric_name):
return statsd.increment(DATADOG_METRICS[metric_name], tags=DEFAULT_TAGS)
def gauge(metric_name, value):
return statsd.gauge(DATADOG_METRICS[metric_name], value, tags=DEFAULT_TAGS)
| ###############################################################################
# This is a very strange handler setup, but this is how it's documented.
# See https://github.com/DataDog/datadogpy#quick-start-guide
###############################################################################
import os
from datadog import initialize
traptor_type = os.getenv('TRAPTOR_TYPE', 'track')
traptor_id = os.getenv('TRAPTOR_ID', '0')
DEFAULT_TAGS = [
'traptor_type:{}'.format(traptor_type),
'traptor_id:{}'.format(traptor_id),
]
options = {
'statsd_host': os.getenv('STATSD_HOST_IP', '127.0.0.1')
}
initialize(**options)
from datadog import statsd
DATADOG_METRICS = {
'tweet_process_success': 'traptor.src.tweet_process.success',
'tweet_process_failure': 'traptor.src.tweet_process.failure',
'tweet_to_kafka_success': 'traptor.src.tweet_to_kafka.success',
'tweet_to_kafka_failure': 'traptor.src.tweet_to_kafka.failure',
}
def increment(metric_name):
return statsd.increment(DATADOG_METRICS[metric_name], tags=DEFAULT_TAGS)
def gauge(metric_name, value):
return statsd.gauge(DATADOG_METRICS[metric_name], value, tags=DEFAULT_TAGS)
| Use getenv instead of environment dict | Use getenv instead of environment dict
| Python | mit | istresearch/traptor,istresearch/traptor | ---
+++
@@ -5,8 +5,8 @@
import os
from datadog import initialize
-traptor_type = os.environ['TRAPTOR_TYPE']
-traptor_id = os.environ['TRAPTOR_ID']
+traptor_type = os.getenv('TRAPTOR_TYPE', 'track')
+traptor_id = os.getenv('TRAPTOR_ID', '0')
DEFAULT_TAGS = [
'traptor_type:{}'.format(traptor_type),
@@ -14,7 +14,7 @@
]
options = {
- 'statsd_host': os.environ['STATSD_HOST_IP'],
+ 'statsd_host': os.getenv('STATSD_HOST_IP', '127.0.0.1')
}
initialize(**options)
|
264075d9b313f5c2677e32fcf5d340bba73f0b0e | corehq/apps/app_manager/migrations/0019_exchangeapplication_required_privileges.py | corehq/apps/app_manager/migrations/0019_exchangeapplication_required_privileges.py | # Generated by Django 2.2.24 on 2021-09-13 21:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_manager', '0018_migrate_case_search_labels'),
]
operations = [
migrations.AddField(
model_name='exchangeapplication',
name='required_privileges',
field=models.TextField(null=True),
),
]
| # Generated by Django 2.2.24 on 2021-09-14 17:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_manager', '0018_migrate_case_search_labels'),
]
operations = [
migrations.AddField(
model_name='exchangeapplication',
name='required_privileges',
field=models.TextField(help_text='Space-separated list of privilege strings from corehq.privileges', null=True),
),
]
| Fix migration with help text | Fix migration with help text
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,4 +1,4 @@
-# Generated by Django 2.2.24 on 2021-09-13 21:04
+# Generated by Django 2.2.24 on 2021-09-14 17:54
from django.db import migrations, models
@@ -13,6 +13,6 @@
migrations.AddField(
model_name='exchangeapplication',
name='required_privileges',
- field=models.TextField(null=True),
+ field=models.TextField(help_text='Space-separated list of privilege strings from corehq.privileges', null=True),
),
] |
a1e7cade8fb5e4a301244a8a0cef382b49399d46 | us_ignite/awards/admin.py | us_ignite/awards/admin.py | from django.contrib import admin
from us_ignite.awards.models import Award
class AwardAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
admin.site.register(Award, AwardAdmin)
| from django.contrib import admin
from us_ignite.awards.models import Award, ApplicationAward
class AwardAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
class ApplicationAwardAdmin(admin.ModelAdmin):
list_display = ('award', 'application', 'created')
date_hierarchy = 'created'
list_filter = ('award__name',)
admin.site.register(Award, AwardAdmin)
admin.site.register(ApplicationAward, ApplicationAwardAdmin)
| Add mechanics to award applications. | Add mechanics to award applications.
https://github.com/madewithbytes/us_ignite/issues/77
The awards can be given in the admin section.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -1,8 +1,15 @@
from django.contrib import admin
-from us_ignite.awards.models import Award
+from us_ignite.awards.models import Award, ApplicationAward
class AwardAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
+
+class ApplicationAwardAdmin(admin.ModelAdmin):
+ list_display = ('award', 'application', 'created')
+ date_hierarchy = 'created'
+ list_filter = ('award__name',)
+
admin.site.register(Award, AwardAdmin)
+admin.site.register(ApplicationAward, ApplicationAwardAdmin) |
e2b382a69473dcfa6d93442f3ad3bc21ee6c90a0 | examples/tic_ql_tabular_selfplay_all.py | examples/tic_ql_tabular_selfplay_all.py | '''
In this example the Q-learning algorithm is used via self-play
to learn the state-action values for all Tic-Tac-Toe positions.
'''
from capstone.game.games import TicTacToe
from capstone.game.utils import tic2pdf
from capstone.rl import Environment, GameMDP
from capstone.rl.learners import QLearningSelfPlay
from capstone.rl.value_functions import TabularF
game = TicTacToe()
env = Environment(GameMDP(game))
qlearning = QLearningSelfPlay(env, n_episodes=1000, random_state=0)
qlearning.learn()
for move in game.legal_moves():
print('-' * 80)
value = qlearning.qf[(game, move)]
new_game = game.copy().make_move(move)
print(value)
print(new_game)
| '''
The Q-learning algorithm is used to learn the state-action values for all
Tic-Tac-Toe positions by playing games against itself (self-play).
'''
from capstone.game.games import TicTacToe
from capstone.game.players import GreedyQF, RandPlayer
from capstone.game.utils import play_series, tic2pdf
from capstone.rl import Environment, GameMDP
from capstone.rl.learners import QLearningSelfPlay
game = TicTacToe()
env = Environment(GameMDP(game))
qlearning = QLearningSelfPlay(env, n_episodes=100000, verbose=0)
qlearning.learn()
for move in game.legal_moves():
print('-' * 80)
value = qlearning.qf[game, move]
new_game = game.copy().make_move(move)
print(value)
print(new_game)
players = [GreedyQF(qlearning.qf), RandPlayer()]
play_series(TicTacToe(), players, n_matches=10000)
# show number of unvisited state?
| Fix Tic-Tac-Toe Q-learning tabular self-play example | Fix Tic-Tac-Toe Q-learning tabular self-play example
| Python | mit | davidrobles/mlnd-capstone-code | ---
+++
@@ -1,21 +1,26 @@
'''
-In this example the Q-learning algorithm is used via self-play
-to learn the state-action values for all Tic-Tac-Toe positions.
+The Q-learning algorithm is used to learn the state-action values for all
+Tic-Tac-Toe positions by playing games against itself (self-play).
'''
from capstone.game.games import TicTacToe
-from capstone.game.utils import tic2pdf
+from capstone.game.players import GreedyQF, RandPlayer
+from capstone.game.utils import play_series, tic2pdf
from capstone.rl import Environment, GameMDP
from capstone.rl.learners import QLearningSelfPlay
-from capstone.rl.value_functions import TabularF
game = TicTacToe()
env = Environment(GameMDP(game))
-qlearning = QLearningSelfPlay(env, n_episodes=1000, random_state=0)
+qlearning = QLearningSelfPlay(env, n_episodes=100000, verbose=0)
qlearning.learn()
for move in game.legal_moves():
print('-' * 80)
- value = qlearning.qf[(game, move)]
+ value = qlearning.qf[game, move]
new_game = game.copy().make_move(move)
print(value)
print(new_game)
+
+players = [GreedyQF(qlearning.qf), RandPlayer()]
+play_series(TicTacToe(), players, n_matches=10000)
+
+# show number of unvisited state? |
b09c7d7c8a0949e6c0a370e7608e51b1060b1ee8 | meinberlin/apps/mapideas/forms.py | meinberlin/apps/mapideas/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from adhocracy4.categories.forms import CategorizableFieldMixin
from adhocracy4.maps import widgets as maps_widgets
from . import models
class MapIdeaForm(CategorizableFieldMixin, forms.ModelForm):
def __init__(self, *args, **kwargs):
self.settings = kwargs.pop('settings_instance')
super().__init__(*args, **kwargs)
self.fields['point'].widget = maps_widgets.MapChoosePointWidget(
polygon=self.settings.polygon)
self.fields['point'].error_messages['required'] = _(
'Please locate your proposal on the map.')
class Meta:
model = models.MapIdea
fields = ['name', 'description', 'category', 'point', 'point_label']
class MapIdeaModerateForm(forms.ModelForm):
class Meta:
model = models.MapIdea
fields = ['moderator_feedback']
| from django import forms
from django.utils.translation import ugettext_lazy as _
from adhocracy4.categories.forms import CategorizableFieldMixin
from adhocracy4.maps import widgets as maps_widgets
from . import models
class MapIdeaForm(CategorizableFieldMixin, forms.ModelForm):
class Media:
js = ('js/select_dropdown_init.js',)
def __init__(self, *args, **kwargs):
self.settings = kwargs.pop('settings_instance')
super().__init__(*args, **kwargs)
self.fields['point'].widget = maps_widgets.MapChoosePointWidget(
polygon=self.settings.polygon)
self.fields['point'].error_messages['required'] = _(
'Please locate your proposal on the map.')
class Meta:
model = models.MapIdea
fields = ['name', 'description', 'category', 'point', 'point_label']
class MapIdeaModerateForm(forms.ModelForm):
class Meta:
model = models.MapIdea
fields = ['moderator_feedback']
| Initialize select dropdown for categories with maps | Initialize select dropdown for categories with maps
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | ---
+++
@@ -8,6 +8,8 @@
class MapIdeaForm(CategorizableFieldMixin, forms.ModelForm):
+ class Media:
+ js = ('js/select_dropdown_init.js',)
def __init__(self, *args, **kwargs):
self.settings = kwargs.pop('settings_instance') |
b5e13cb92f539545873d59553c03e1523eac1dbb | recipes/kaleido-core/run_test.py | recipes/kaleido-core/run_test.py | from subprocess import Popen, PIPE
import json
import platform
# Remove "sys.exit" after feedstock creation when running
# on linux-anvil-cos7-x86_64 image
if platform.system() == "Linux":
import sys
sys.exit(0)
if platform.system() == "Windows":
ext = ".cmd"
else:
ext = ""
p = Popen(
['kaleido' + ext, "plotly", "--disable-gpu"],
stdout=PIPE, stdin=PIPE, stderr=PIPE,
text=True
)
stdout_data = p.communicate(
input=json.dumps({"data": {"data": []}, "format": "png"})
)[0]
assert "iVBORw" in stdout_data
| from subprocess import Popen, PIPE
import json
import platform
# Remove "sys.exit" after feedstock creation when running
# on linux-anvil-cos7-x86_64 image
if platform.system() == "Linux":
import sys
sys.exit(0)
if platform.system() == "Windows":
ext = ".cmd"
else:
ext = ""
p = Popen(
['kaleido' + ext, "plotly", "--disable-gpu", "--no-sandbox", "--disable-breakpad"],
stdout=PIPE, stdin=PIPE, stderr=PIPE,
text=True
)
stdout_data = p.communicate(
input=json.dumps({"data": {"data": []}, "format": "png"})
)[0]
assert "iVBORw" in stdout_data
| Fix hanging test on MacOS | Fix hanging test on MacOS
| Python | bsd-3-clause | kwilcox/staged-recipes,ocefpaf/staged-recipes,stuertz/staged-recipes,johanneskoester/staged-recipes,jochym/staged-recipes,SylvainCorlay/staged-recipes,goanpeca/staged-recipes,igortg/staged-recipes,mariusvniekerk/staged-recipes,conda-forge/staged-recipes,patricksnape/staged-recipes,goanpeca/staged-recipes,johanneskoester/staged-recipes,scopatz/staged-recipes,ocefpaf/staged-recipes,ReimarBauer/staged-recipes,scopatz/staged-recipes,hadim/staged-recipes,hadim/staged-recipes,jochym/staged-recipes,patricksnape/staged-recipes,mariusvniekerk/staged-recipes,conda-forge/staged-recipes,stuertz/staged-recipes,jakirkham/staged-recipes,ReimarBauer/staged-recipes,igortg/staged-recipes,jakirkham/staged-recipes,SylvainCorlay/staged-recipes,kwilcox/staged-recipes | ---
+++
@@ -14,7 +14,7 @@
ext = ""
p = Popen(
- ['kaleido' + ext, "plotly", "--disable-gpu"],
+ ['kaleido' + ext, "plotly", "--disable-gpu", "--no-sandbox", "--disable-breakpad"],
stdout=PIPE, stdin=PIPE, stderr=PIPE,
text=True
) |
c3de0c71a8392a884f8fd08dbee8f337ba7833c7 | src/ggrc/migrations/versions/20130724021606_2bf7c04016c9_person_email_must_be.py | src/ggrc/migrations/versions/20130724021606_2bf7c04016c9_person_email_must_be.py | """Person.email must be unique
Revision ID: 2bf7c04016c9
Revises: 2b709b655bf
Create Date: 2013-07-24 02:16:06.282258
"""
# revision identifiers, used by Alembic.
revision = '2bf7c04016c9'
down_revision = '2b709b655bf'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_unique_constraint('uq_people_email', 'people', ['email'])
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('uq_people_email', 'people', type_='unique')
### end Alembic commands ###
| """Person.email must be unique
Revision ID: 2bf7c04016c9
Revises: d3af6d071ef
Create Date: 2013-07-24 02:16:06.282258
"""
# revision identifiers, used by Alembic.
revision = '2bf7c04016c9'
down_revision = 'd3af6d071ef'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_unique_constraint('uq_people_email', 'people', ['email'])
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('uq_people_email', 'people', type_='unique')
### end Alembic commands ###
| Update 'down' version in migration due to merge | Update 'down' version in migration due to merge
| Python | apache-2.0 | AleksNeStu/ggrc-core,edofic/ggrc-core,plamut/ggrc-core,uskudnik/ggrc-core,josthkko/ggrc-core,edofic/ggrc-core,j0gurt/ggrc-core,uskudnik/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,kr41/ggrc-core,vladan-m/ggrc-core,prasannav7/ggrc-core,AleksNeStu/ggrc-core,hyperNURb/ggrc-core,uskudnik/ggrc-core,hasanalom/ggrc-core,jmakov/ggrc-core,VinnieJohns/ggrc-core,hasanalom/ggrc-core,prasannav7/ggrc-core,josthkko/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,uskudnik/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,VinnieJohns/ggrc-core,hasanalom/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,hyperNURb/ggrc-core,vladan-m/ggrc-core,j0gurt/ggrc-core,hasanalom/ggrc-core,j0gurt/ggrc-core,jmakov/ggrc-core,vladan-m/ggrc-core,vladan-m/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,hyperNURb/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,kr41/ggrc-core,uskudnik/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,kr41/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,hasanalom/ggrc-core,prasannav7/ggrc-core,selahssea/ggrc-core,hyperNURb/ggrc-core,plamut/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,jmakov/ggrc-core,josthkko/ggrc-core,hyperNURb/ggrc-core,vladan-m/ggrc-core,andrei-karalionak/ggrc-core | ---
+++
@@ -1,14 +1,14 @@
"""Person.email must be unique
Revision ID: 2bf7c04016c9
-Revises: 2b709b655bf
+Revises: d3af6d071ef
Create Date: 2013-07-24 02:16:06.282258
"""
# revision identifiers, used by Alembic.
revision = '2bf7c04016c9'
-down_revision = '2b709b655bf'
+down_revision = 'd3af6d071ef'
from alembic import op
import sqlalchemy as sa |
ac9ee17f93b90a79b629d222d8c2846debed6f04 | chalice/__init__.py | chalice/__init__.py | from chalice.app import Chalice
from chalice.app import (
ChaliceViewError, BadRequestError, UnauthorizedError, ForbiddenError,
NotFoundError, ConflictError, TooManyRequestsError, Response, CORSConfig
)
__version__ = '0.8.0'
| from chalice.app import Chalice
from chalice.app import (
ChaliceViewError, BadRequestError, UnauthorizedError, ForbiddenError,
NotFoundError, ConflictError, TooManyRequestsError, Response, CORSConfig,
CustomAuthorizer, CognitoUserPoolAuthorizer
)
__version__ = '0.8.0'
| Add authorizers as top level import | Add authorizers as top level import
| Python | apache-2.0 | awslabs/chalice | ---
+++
@@ -1,7 +1,8 @@
from chalice.app import Chalice
from chalice.app import (
ChaliceViewError, BadRequestError, UnauthorizedError, ForbiddenError,
- NotFoundError, ConflictError, TooManyRequestsError, Response, CORSConfig
+ NotFoundError, ConflictError, TooManyRequestsError, Response, CORSConfig,
+ CustomAuthorizer, CognitoUserPoolAuthorizer
)
__version__ = '0.8.0' |
9b18cc62dc0338a9dff6ae7dd448a4dca960c941 | accounts/forms.py | accounts/forms.py | """forms for accounts app
"""
from django import forms
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.shortcuts import get_current_site
from accounts.tokens import LoginTokenGenerator
USER = get_user_model()
class LoginForm(forms.Form):
email = forms.EmailField(label="Email", max_length=254)
def generate_login_link(self, email, request):
protocol = 'http'
domain = get_current_site(request).domain
token = LoginTokenGenerator().make_token(email)
return '{}://{}/login/{}'.format(protocol, domain, token)
def save(self, request):
"""Generate a login token and send it to the email from the form.
"""
email = self.cleaned_data['email']
body = 'To complete the login process, simply click on this link: {}'
login_link = self.generate_login_link(email, request)
email_message = EmailMultiAlternatives(
'Your login link for ANIAuth',
body.format(login_link),
to=[email]
)
email_message.send()
| """forms for accounts app
"""
from django import forms
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse_lazy
from accounts.tokens import LoginTokenGenerator
USER = get_user_model()
class LoginForm(forms.Form):
email = forms.EmailField(label="Email", max_length=254)
def generate_login_link(self, email, request):
protocol = 'http'
domain = get_current_site(request).domain
url = reverse_lazy('login')
token = LoginTokenGenerator().make_token(email)
return '{}://{}{}?token={}'.format(protocol, domain, url, token)
def save(self, request):
"""Generate a login token and send it to the email from the form.
"""
email = self.cleaned_data['email']
body = 'To complete the login process, simply click on this link: {}'
login_link = self.generate_login_link(email, request)
email_message = EmailMultiAlternatives(
'Your login link for ANIAuth',
body.format(login_link),
to=[email]
)
email_message.send()
| Add the token as a get parameter | Add the token as a get parameter
| Python | mit | randomic/aniauth-tdd,randomic/aniauth-tdd | ---
+++
@@ -5,6 +5,7 @@
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.shortcuts import get_current_site
+from django.urls import reverse_lazy
from accounts.tokens import LoginTokenGenerator
@@ -18,8 +19,9 @@
def generate_login_link(self, email, request):
protocol = 'http'
domain = get_current_site(request).domain
+ url = reverse_lazy('login')
token = LoginTokenGenerator().make_token(email)
- return '{}://{}/login/{}'.format(protocol, domain, token)
+ return '{}://{}{}?token={}'.format(protocol, domain, url, token)
def save(self, request):
"""Generate a login token and send it to the email from the form. |
ade65a931408dd96e59b484dc9cb1bfae3bf8848 | wallace/sources.py | wallace/sources.py | from .models import Node, Info, Transmission
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
def _selector(self):
return []
def create_information(self):
"""Generate new information."""
return NotImplementedError
class RandomBinaryStringSource(Source):
"""An agent whose genome and memome are random binary strings. The source
only transmits; it does not update.
"""
__mapper_args__ = {"polymorphic_identity": "random_binary_string_source"}
@staticmethod
def _data():
return "".join([str(random.randint(0, 1)) for i in range(2)])
| from .models import Node, Info, Transmission
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
def _selector(self):
return None
def create_information(self):
"""Generate new information."""
return NotImplementedError
class RandomBinaryStringSource(Source):
"""An agent whose genome and memome are random binary strings. The source
only transmits; it does not update.
"""
__mapper_args__ = {"polymorphic_identity": "random_binary_string_source"}
@staticmethod
def _data():
return "".join([str(random.randint(0, 1)) for i in range(2)])
| Make the default selector null | Make the default selector null
| Python | mit | Dallinger/Dallinger,berkeley-cocosci/Wallace,Dallinger/Dallinger,suchow/Wallace,berkeley-cocosci/Wallace,berkeley-cocosci/Wallace,Dallinger/Dallinger,suchow/Wallace,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,suchow/Wallace,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger | ---
+++
@@ -10,7 +10,7 @@
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
def _selector(self):
- return []
+ return None
def create_information(self):
"""Generate new information.""" |
b92c75e1145915892723206a77593b9701e608bf | webapp/hello.py | webapp/hello.py | from flask import Flask, render_template, request
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from scipy import misc
import numpy as np
from VGG16_gs_model import *
# sett opp nevralt nettverk:
model = VGG_16()
fpath = '../models/vgg16_sg.h5';
model.load_weights(fpath)
# Sett opp webapp
app = Flask(__name__)
photos = UploadSet('photos', IMAGES)
app.config['UPLOADED_PHOTOS_DEST'] = 'img'
configure_uploads(app, photos)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
# Hent ut prediksjon
img = misc.imread('./img/' + filename)
img = misc.imresize(img, (224, 224))
img = img.transpose()
img = np.expand_dims(img, axis=0).astype(np.uint8)
preds, idxs, classes = predict(model, img)
return 'You are a ' + str(classes[0]) + ' with a confidence of ' + str(preds[0])
return render_template('upload.html')
@app.route("/")
def hello():
return "Hello Nabla and Timini!"
if __name__ == "__main__":
app.run(host = '0.0.0.0' )
| from flask import Flask, render_template, request
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from scipy import misc
import numpy as np
from VGG16_gs_model import *
# sett opp nevralt nettverk:
model = VGG_16()
fpath = '../models/vgg16_sg.h5';
model.load_weights(fpath)
# Sett opp webapp
app = Flask(__name__)
photos = UploadSet('photos', IMAGES)
app.config['UPLOADED_PHOTOS_DEST'] = 'img'
configure_uploads(app, photos)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
# Hent ut prediksjon
img = misc.imread('./img/' + filename)
img = misc.imresize(img, (224, 224))
img = img.transpose()
img = np.expand_dims(img, axis=0).astype(np.uint8)
preds, idxs, classes = predict(model, img)
return 'You are a ' + str(classes[0]) + ' with a confidence of ' + str(preds[0])
return render_template('upload.html')
@app.route("/")
def hello():
return "Hello Nabla and Timini!"
if __name__ == "__main__":
app.run(host = '0.0.0.0', port=5000)
| Add port on flask app | Add port on flask app
| Python | apache-2.0 | jchalvorsen/ConsultantOrNot,jchalvorsen/ConsultantOrNot,jchalvorsen/ConsultantOrNot | ---
+++
@@ -40,5 +40,5 @@
return "Hello Nabla and Timini!"
if __name__ == "__main__":
- app.run(host = '0.0.0.0' )
+ app.run(host = '0.0.0.0', port=5000)
|
ce443b03ca919e799566751d13a3d357299d38c2 | libcrowds_data/__init__.py | libcrowds_data/__init__.py | # -*- coding: utf8 -*-
"""
LibCrowdsData
-------------
Global data repository page for LibCrowds.
"""
import os
import json
import default_settings
from flask import current_app as app
from flask.ext.plugins import Plugin
__plugin__ = "LibCrowdsData"
__version__ = json.load(open(os.path.join(os.path.dirname(__file__),
'info.json')))['version']
class LibCrowdsData(Plugin):
"""Libcrowds data plugin class."""
def setup(self):
"""Setup the plugin."""
self.load_config()
self.setup_blueprint()
def load_config(self):
"""Configure the plugin."""
settings = [key for key in dir(default_settings) if key.isupper()]
for s in settings:
if not app.config.get(s):
app.config[s] = getattr(default_settings, s)
def setup_blueprint(self):
"""Setup blueprint."""
from .blueprint import DataBlueprint
here = os.path.dirname(os.path.abspath(__file__))
template_folder = os.path.join(here, 'templates')
static_folder = os.path.join(here, 'static')
blueprint = DataBlueprint(template_folder=template_folder,
static_folder=static_folder)
app.register_blueprint(blueprint, url_prefix="/data")
| # -*- coding: utf8 -*-
"""
LibCrowdsData
-------------
Global data repository page for LibCrowds.
"""
import os
import json
from . import default_settings
from flask import current_app as app
from flask.ext.plugins import Plugin
__plugin__ = "LibCrowdsData"
__version__ = json.load(open(os.path.join(os.path.dirname(__file__),
'info.json')))['version']
class LibCrowdsData(Plugin):
"""Libcrowds data plugin class."""
def setup(self):
"""Setup the plugin."""
self.load_config()
self.setup_blueprint()
def load_config(self):
"""Configure the plugin."""
settings = [key for key in dir(default_settings) if key.isupper()]
for s in settings:
if not app.config.get(s):
app.config[s] = getattr(default_settings, s)
def setup_blueprint(self):
"""Setup blueprint."""
from .blueprint import DataBlueprint
here = os.path.dirname(os.path.abspath(__file__))
template_folder = os.path.join(here, 'templates')
static_folder = os.path.join(here, 'static')
blueprint = DataBlueprint(template_folder=template_folder,
static_folder=static_folder)
app.register_blueprint(blueprint, url_prefix="/data")
| Use relative import for default settings | Use relative import for default settings
| Python | bsd-3-clause | LibCrowds/libcrowds-data,LibCrowds/libcrowds-data | ---
+++
@@ -8,7 +8,7 @@
import os
import json
-import default_settings
+from . import default_settings
from flask import current_app as app
from flask.ext.plugins import Plugin
|
c671adabcae728fb6992bb91001838b3b9cbfd8a | wrappers/python/setup.py | wrappers/python/setup.py | from distutils.core import setup
import os
PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0'
setup(
name='python3-indy',
version=PKG_VERSION,
packages=['indy'],
url='https://github.com/hyperledger/indy-sdk',
license='MIT/Apache-2.0',
author='Vyacheslav Gudkov',
author_email='vyacheslav.gudkov@dsr-company.com',
description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.',
install_requires=['base58'],
tests_require=['pytest<3.7', 'pytest-asyncio', 'base58']
)
| from distutils.core import setup
import os
PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0'
TEST_DEPS = [
'pytest<3.7', 'pytest-asyncio', 'base58'
]
setup(
name='python3-indy',
version=PKG_VERSION,
packages=['indy'],
url='https://github.com/hyperledger/indy-sdk',
license='MIT/Apache-2.0',
author='Vyacheslav Gudkov',
author_email='vyacheslav.gudkov@dsr-company.com',
description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.',
install_requires=['base58'],
tests_require=TEST_DEPS,
extras_require={
'test': TEST_DEPS
}
)
| Make test dependencies installable as an extra | Make test dependencies installable as an extra
Signed-off-by: Daniel Bluhm <6df8625bb799b640110458f819853f591a9910cb@sovrin.org>
| Python | apache-2.0 | Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk | ---
+++
@@ -2,6 +2,10 @@
import os
PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0'
+
+TEST_DEPS = [
+ 'pytest<3.7', 'pytest-asyncio', 'base58'
+]
setup(
name='python3-indy',
@@ -13,5 +17,8 @@
author_email='vyacheslav.gudkov@dsr-company.com',
description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.',
install_requires=['base58'],
- tests_require=['pytest<3.7', 'pytest-asyncio', 'base58']
+ tests_require=TEST_DEPS,
+ extras_require={
+ 'test': TEST_DEPS
+ }
) |
62f8c68165f7f519b5769c99db00ef8822e9f534 | yatsm/log_yatsm.py | yatsm/log_yatsm.py | import logging
_FORMAT = '%(asctime)s:%(levelname)s:%(module)s.%(funcName)s:%(message)s'
_formatter = logging.Formatter(_FORMAT)
_handler = logging.StreamHandler()
_handler.setFormatter(_formatter)
logger = logging.getLogger('yatsm')
logger.addHandler(_handler)
logger.setLevel(logging.INFO)
| import logging
_FORMAT = '%(asctime)s:%(levelname)s:%(module)s.%(funcName)s:%(message)s'
_formatter = logging.Formatter(_FORMAT, '%H:%M:%S')
_handler = logging.StreamHandler()
_handler.setFormatter(_formatter)
logger = logging.getLogger('yatsm')
logger.addHandler(_handler)
logger.setLevel(logging.INFO)
| Change time format in logs | Change time format in logs
| Python | mit | c11/yatsm,valpasq/yatsm,c11/yatsm,ceholden/yatsm,valpasq/yatsm,ceholden/yatsm | ---
+++
@@ -1,7 +1,7 @@
import logging
_FORMAT = '%(asctime)s:%(levelname)s:%(module)s.%(funcName)s:%(message)s'
-_formatter = logging.Formatter(_FORMAT)
+_formatter = logging.Formatter(_FORMAT, '%H:%M:%S')
_handler = logging.StreamHandler()
_handler.setFormatter(_formatter)
|
d0c05d5d254ef321d192975e0027d4dedca9a1f7 | app/main/views.py | app/main/views.py | from flask import render_template, current_app
from . import main
import os
@main.route('/')
def index():
return render_template('editor2.html')
| from flask import render_template, current_app
from . import main
import os
@main.route('/')
def index():
return render_template('editor.html')
| Fix bug where wrong template name was used | Fix bug where wrong template name was used
| Python | mit | TheVindicators/Vis,TheVindicators/Vis,TheVindicators/Vis | ---
+++
@@ -4,4 +4,4 @@
@main.route('/')
def index():
- return render_template('editor2.html')
+ return render_template('editor.html') |
2d85ea5594cf1395fef6caafccc690ed9a5db472 | crabigator/tests/test_wanikani.py | crabigator/tests/test_wanikani.py | """Tests for crabigator.wanikani."""
from __future__ import print_function
from crabigator.wanikani import WaniKani, WaniKaniError
import os
from unittest import TestCase
# TestCase exposes too many public methods. Disable the pylint warning for it.
# pylint: disable=too-many-public-methods
class TestWaniKani(TestCase):
"""Unit test cases for the WaniKani API wrapper."""
@classmethod
def test_wanikani(cls):
"""Test all public methods in crabigator.wanikani."""
wanikani = WaniKani(os.environ['WANIKANI_API_KEY'])
print(wanikani.user_information)
print(wanikani.study_queue)
print(wanikani.level_progression)
print(wanikani.srs_distribution)
print(wanikani.recent_unlocks)
print(wanikani.get_recent_unlocks(3))
print(wanikani.critical_items)
print(wanikani.get_recent_unlocks(65))
print(wanikani.radicals)
print(wanikani.get_radicals([1, 2]))
print(wanikani.kanji)
print(wanikani.get_kanji([1, 2]))
print(wanikani.vocabulary)
print(wanikani.get_vocabulary([1, 2]))
try:
wanikani.get_vocabulary([9999])
except WaniKaniError as ex:
print(ex)
| """Tests for crabigator.wanikani."""
from __future__ import print_function
import os
from unittest import TestCase
from crabigator.wanikani import WaniKani, WaniKaniError
# TestCase exposes too many public methods. Disable the pylint warning for it.
# pylint: disable=too-many-public-methods
class TestWaniKani(TestCase):
"""Unit test cases for the WaniKani API wrapper."""
@classmethod
def test_wanikani(cls):
"""Test all public methods in crabigator.wanikani."""
wanikani = WaniKani(os.environ['WANIKANI_API_KEY'])
print(wanikani.user_information)
print(wanikani.study_queue)
print(wanikani.level_progression)
print(wanikani.srs_distribution)
print(wanikani.recent_unlocks)
print(wanikani.get_recent_unlocks(3))
print(wanikani.critical_items)
print(wanikani.get_recent_unlocks(65))
print(wanikani.radicals)
print(wanikani.get_radicals([1, 2]))
print(wanikani.kanji)
print(wanikani.get_kanji([1, 2]))
print(wanikani.vocabulary)
print(wanikani.get_vocabulary([1, 2]))
try:
wanikani.get_vocabulary([9999])
except WaniKaniError as ex:
print(ex)
| Change import order to satisfy pylint. | Change import order to satisfy pylint.
| Python | mit | jonesinator/crabigator | ---
+++
@@ -1,9 +1,10 @@
"""Tests for crabigator.wanikani."""
from __future__ import print_function
-from crabigator.wanikani import WaniKani, WaniKaniError
import os
from unittest import TestCase
+
+from crabigator.wanikani import WaniKani, WaniKaniError
# TestCase exposes too many public methods. Disable the pylint warning for it. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.